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

Checks:
- required fields exist
- kind is RNF or NDB_MXC
- baseline text is consistent with target type
- 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 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","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")

    # baseline sanity: must mention correct target
    base = str(data["baseline"]).lower()
    tgt = str(data["target"]).lower()
    if "cst" in tgt and "cst" not in base and "coupled" not in base:
        fail("baseline should indicate coupled Haar on CST when target mentions CST")

    print("PASS: Basic CC checks succeeded")
    print("Summary")
    print("  convergence_id:", data["convergence_id"])
    print("  kind:", data["kind"])
    print("  target:", data["target"])

if __name__ == "__main__":
    main()
