#!/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
- for WSC: target_type consistency (cst implies 'CST' in target)
- class_label consistency: A/B/C => WSC, D => WOB
"""
import json, sys
from pathlib import Path

def fail(msg):
    print("FAIL:", msg)
    sys.exit(1)

def main():
    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")

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

        if e["class_label"] == "Class D":
            # expect WOB
            oid = data.get("obstruction_id")
            if oid != e["artifact_id"]:
                fail(f"artifact_id mismatch for {e['label']}: index {e['artifact_id']} vs file {oid}")
            if data.get("witness_tier") != e["tier"]:
                fail(f"tier mismatch for {e['label']}")
        else:
            cid = data.get("certificate_id")
            if cid != e["artifact_id"]:
                fail(f"artifact_id mismatch for {e['label']}: index {e['artifact_id']} vs file {cid}")
            if data.get("witness_tier") != e["tier"]:
                fail(f"tier mismatch for {e['label']}")
            tgt = str(data.get("target",""))
            if e["target_type"] == "cst" and "CST" not in tgt and "cst" not in tgt:
                fail(f"target_type cst but target does not mention CST for {e['label']}")
        # basic tier check
        if e["tier"] not in ("WTR-G","WTR-E","WTR-C"):
            fail(f"bad tier in index for {e['label']}")

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

if __name__ == "__main__":
    main()
