#!/usr/bin/env python3
"""
SFT Audit: Witness Stability Certificate

This script is intentionally lightweight:
- validates that required fields exist
- checks basic margin inequalities (LCM < pi, HMR < P/2)
- prints a PASS/FAIL summary

It is designed as a template that can be extended to recompute degree/holonomy
from concrete witness data when you choose to include that data.
"""
import json, math, sys
from pathlib import Path

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

def main() -> None:
    if len(sys.argv) != 2:
        fail("Usage: audit_wsc.py path/to/WSC.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"))

    required = ["sft_version","certificate_id","witness_tier","mechanism","target","period_P","witness_value","perturbation_model","margins","assumptions","artifacts"]
    missing = [k for k in required if k not in data]
    if missing:
        fail("Missing required fields: " + ", ".join(missing))

    P = float(data["period_P"])
    if not (P > 0):
        fail("period_P must be > 0")

    margins = data.get("margins", {})
    if "LCM_pi" in margins:
        lcm = float(margins["LCM_pi"])
        if not (0 < lcm < math.pi):
            fail(f"LCM_pi must satisfy 0 < LCM_pi < pi. Got {lcm}")

    if "HMR_P" in margins:
        hmr = float(margins["HMR_P"])
        if not (0 < hmr < P/2):
            fail(f"HMR_P must satisfy 0 < HMR_P < P/2. Got {hmr}, P={P}")

    print("PASS: Basic WSC checks succeeded")
    print("Summary")
    print("  certificate_id:", data["certificate_id"])
    print("  witness_tier:", data["witness_tier"])
    print("  mechanism:", data["mechanism"])
    print("  target:", data["target"])
    print("  assumptions:", ", ".join(data.get("assumptions", [])))

if __name__ == "__main__":
    main()
