#!/usr/bin/env python3
"""
SFT Audit: Witness Atlas Index

Checks:
- referenced artifact files exist
- artifact_id matches the file content (certificate_id or obstruction_id)
- tier matches
- target_type in index matches artifact target_type for WSC entries
- CST discipline: cst target_type implies coupled baseline and CST in target description
- class_label consistency: A/B/C => WSC, D => WOB
- COC labeling gate: in_coc => WSC-class entry; boundary_wob => WOB-class entry
- family bucket is present and one of the declared atlas families
"""

import json
import sys
from pathlib import Path


FAMILIES = {
    "Rotation & periodic forcing",
    "Embedded loops & defects",
    "Coupled targets (CST)",
    "Torus drives & equidistribution",
    "Noise-to-diffusion mixing upgrades",
    "Boundary obstructions",
}


def fail(msg: str) -> None:
    print("FAIL:", msg)
    sys.exit(1)


def main() -> None:
    if len(sys.argv) != 3:
        fail("Usage: audit_atlas.py path/to/atlas_index.json path/to/engine/artifacts")

    index_path = Path(sys.argv[1])
    art_dir = Path(sys.argv[2])

    if not index_path.exists():
        fail("atlas index not found")
    if not art_dir.exists():
        fail("artifacts dir not found")

    idx = json.loads(index_path.read_text(encoding="utf-8"))
    if "entries" not in idx or not isinstance(idx["entries"], list):
        fail("entries missing or not list")

    labels = set()

    for e in idx["entries"]:
        lab = e.get("label", "?")
        if lab in labels:
            fail(f"duplicate label in atlas index: {lab}")
        labels.add(lab)

        cs = e.get("coc_status", None)
        if cs not in ("in_coc", "boundary_wob"):
            fail(f"missing or invalid coc_status for {lab}")

        fam = e.get("family", None)
        if fam not in FAMILIES:
            fail(f"missing or invalid family for {lab}: {fam!r}")

        af = art_dir / e["artifact_file"]
        if not af.exists():
            fail(f"Missing artifact file: {e['artifact_file']} for {lab}")
        data = json.loads(af.read_text(encoding="utf-8"))

        if e["class_label"] == "Class D":
            if cs != "boundary_wob":
                fail(f"coc_status must be boundary_wob for Class D entry {lab}")
            # expect WOB
            oid = data.get("obstruction_id")
            if oid != e["artifact_id"]:
                fail(f"artifact_id mismatch for {lab}: index {e['artifact_id']} vs file {oid}")
            if data.get("witness_tier") != e["tier"]:
                fail(f"tier mismatch for {lab}")
            oc = str(data.get("obstruction_code", ""))
            if not oc.startswith("WOB-"):
                fail(f"missing obstruction_code for {lab}")
        else:
            if cs != "in_coc":
                fail(f"coc_status must be in_coc for non-Class-D entry {lab}")
            cid = data.get("certificate_id")
            if cid != e["artifact_id"]:
                fail(f"artifact_id mismatch for {lab}: index {e['artifact_id']} vs file {cid}")
            if data.get("witness_tier") != e["tier"]:
                fail(f"tier mismatch for {lab}")

            at_tt = str(data.get("target_type", ""))
            if at_tt != e.get("target_type"):
                fail(f"target_type mismatch for {lab}: index {e.get('target_type')} vs file {at_tt}")

            tgt = str(data.get("target", ""))
            if e["target_type"] == "cst":
                if "CST" not in tgt and "cst" not in tgt:
                    fail(f"target_type cst but target does not mention CST for {lab}")

        if e["tier"] not in ("WTR-G", "WTR-E", "WTR-C"):
            fail(f"bad tier in index for {lab}")

    print("OK: Atlas index consistency checks succeeded")
    print("Entries:", len(idx["entries"]))


if __name__ == "__main__":
    main()
