#!/usr/bin/env python3
import json
import yaml
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]

def main():
    registry_path = ROOT / "spec" / "48_module_io_contract_registry.yaml"
    out_path = ROOT / "Temp" / "module_io_coverage_v1.json"
    
    if not registry_path.exists():
        print(f"Registry not found: {registry_path}")
        return 1

    with registry_path.open("r", encoding="utf-8") as f:
        data = yaml.safe_load(f)

    modules = data.get("modules", {})
    total = len(modules)
    covered = 0
    
    module_details = []
    for mid, m in modules.items():
        # Check if schema and artifact exist
        schema_exists = (ROOT / m["schema"]).exists()
        artifact_exists = (ROOT / m["artifact_path"]).exists()
        
        is_covered = schema_exists and artifact_exists
        if is_covered:
            covered += 1
            
        module_details.append({
            "id": mid,
            "schema_exists": schema_exists,
            "artifact_exists": artifact_exists,
            "covered": is_covered
        })

    coverage_pct = (covered / total * 100) if total > 0 else 0
    
    result = {
        "formula_id": "MODULE_IO_COVERAGE_V1",
        "total_modules": total,
        "covered_modules": covered,
        "coverage_pct": coverage_pct,
        "module_details": module_details
    }
    
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
    print(f"Coverage: {coverage_pct:.1f}%")
    return 0

if __name__ == "__main__":
    main()
