#!/usr/bin/env python3
"""
SFT Audit: Convergence Certificate (CC)

Checks:
- required fields exist (including structured baseline + target_type)
- kind is RNF or NDB_MXC
- baseline is correct for the declared target (CTP/CHT meaning rule)
- NDB_MXC includes rate_lambda or ledger_ref
"""
import json, sys
from pathlib import Path

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

def parse_baseline(b):
    if not isinstance(b, dict):
        fail("baseline must be an object with fields {kind, target_type, description?}")
    kind = str(b.get("kind","")).strip()
    ttype = str(b.get("target_type","")).strip().lower()
    if kind not in ("haar","coupled_haar"):
        fail(f"baseline.kind must be haar or coupled_haar (got {kind!r})")
    if ttype not in ("circle","torus","cst","embedded"):
        fail(f"baseline.target_type must be circle/torus/cst/embedded (got {ttype!r})")
    desc = b.get("description", None)
    if desc is not None and not isinstance(desc, str):
        fail("baseline.description must be a string when present")
    return {"kind": kind, "target_type": ttype, "description": desc}

def main():
    if len(sys.argv) != 2:
        fail("Usage: audit_cc.py path/to/CC.json")
    p = Path(sys.argv[1])
    if not p.exists():
        fail(f"File not found: {p}")
    data = json.loads(p.read_text(encoding="utf-8"))

    for k in ["sft_version","convergence_id","kind","target","target_type","baseline","assumptions"]:
        if k not in data:
            fail(f"Missing required field: {k}")

    if data["kind"] not in ("RNF","NDB_MXC"):
        fail("kind must be RNF or NDB_MXC")

    if not isinstance(data["assumptions"], list):
        fail("assumptions must be a list")

    if data["kind"] == "NDB_MXC":
        if data.get("rate_lambda") in (None, "") and data.get("ledger_ref") in (None, ""):
            fail("NDB_MXC must include rate_lambda or ledger_ref")

    target_type = str(data.get("target_type","")).strip().lower()
    if target_type not in ("circle","torus","cst","embedded"):
        fail("target_type must be circle/torus/cst/embedded")

    base = parse_baseline(data["baseline"])
    if base["target_type"] != target_type:
        fail("baseline.target_type must match target_type")

    if target_type == "cst":
        if base["kind"] != "coupled_haar":
            fail("CST target requires baseline.kind=coupled_haar")
    else:
        if base["kind"] != "haar":
            fail("Non-CST target requires baseline.kind=haar")

    print("OK:", p.name)
    print("Summary")
    print("  convergence_id:", data["convergence_id"])
    print("  kind:", data["kind"])
    print("  target:", data["target"])
    print("  target_type:", target_type)

if __name__ == "__main__":
    main()
