from __future__ import annotations

import json
from pathlib import Path

from refactor_master_helpers import ROOT, load_yaml


def main() -> int:
    manifest = load_yaml(ROOT / "artifacts" / "canonical_manifest.yaml")
    concepts = manifest.get("concepts", {}) if isinstance(manifest.get("concepts"), dict) else {}
    issues = []
    for concept, info in concepts.items():
        if not isinstance(info, dict):
            issues.append({"concept": concept, "issue": "bad_entry"})
            continue
        canon = info.get("canonical_path")
        source = info.get("source_file")
        if not canon or not (ROOT / canon).exists():
            issues.append({"concept": concept, "issue": "missing_canonical", "path": str(canon)})
        if not source or not (ROOT / source).exists():
            issues.append({"concept": concept, "issue": "missing_source", "path": str(source)})
    result = {
        "formula_id": "CANONICAL_ARTIFACT_RESOLVER_V1",
        "concept_count": len(concepts),
        "issue_count": len(issues),
        "issues": issues[:200],
        "gate": "PASS" if not issues else "FAIL",
    }
    out = ROOT / "Temp" / "canonical_artifact_resolver_v1_validation.json"
    out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if not issues else 1


if __name__ == "__main__":
    raise SystemExit(main())
