#!/usr/bin/env python3
"""FDC standalone auditor: re-runs each cited bundle's own auditor and checks the signed certificate."""
import hashlib, json, subprocess, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def merkle(ps):
    l = sorted(sha(p.read_bytes()) for p in ps)
    while len(l) > 1:
        if len(l) % 2: l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0] if l else sha(b"")
def fail(m): print("FAIL:", m); sys.exit(1)
def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    man = json.loads((root / "FDC_MANIFEST.json").read_text())
    if man.get("status") != S or man.get("external_review") != "NOT_OBTAINED": fail("manifest fields")
    body = {k: v for k, v in man.items() if k != "signature"}
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
    except Exception: fail("manifest signature")
    for n, h in man["files"].items():
        p = root / n
        if not p.exists() or sha(p.read_bytes()) != h: fail(f"file {n}")
    if merkle([root / n for n in man["files"]]) != man["merkle_root"]: fail("merkle")
    cert = json.loads((root / "FDC_CERTIFICATE.json").read_text())
    cbody = {k: v for k, v in cert.items() if k != "signature"}
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(cert["pubkey_ed25519"])).verify(bytes.fromhex(cert["signature"]), canon(cbody))
    except Exception: fail("certificate signature")
    scope = json.loads((root / "FDC_SCOPE.json").read_text())
    if sha(canon(scope["members"])) != cert["scope_root"] or sha(canon(scope["members"])) != scope.get("scope_root", sha(canon(scope["members"]))):
        fail("scope root")
    if [r["short"] for r in scope["members"] if r["verdict"] == "NOT_SUPPORTED"] != cert["negatives"]:
        fail("negatives list")
    if cert["counts"]["members"] != len(scope["members"]): fail("count")
    for row in scope["members"]:
        d = root / "cited" / row["name"]
        p = subprocess.run([sys.executable, "-I", str(d / row["verifier"]), str(d)], capture_output=True, text=True, timeout=300)
        out = (p.stdout or p.stderr).strip().splitlines()[-1] if (p.stdout or p.stderr) else ""
        if p.returncode != 0: fail(f"cited auditor {row['short']}")
        if sha(out.encode()) != row["auditor_output_sha256"]: fail(f"auditor output {row['short']}")
        mp = d / f"{row['short']}_MANIFEST.json"
        if json.loads(mp.read_text())["merkle_root"] != row["merkle_root"]: fail(f"merkle {row['short']}")
        if row["merkle_root"] != row["seal_merkle_root"]: fail(f"seal merkle {row['short']}")
        if row["seal_verdict"] != "ALLOWED": fail(f"seal {row['short']}")
    print(f"OK: FDC verified — {len(scope['members'])} members re-run from clean copies, "
          f"{cert['counts']['supported']} supported, {cert['counts']['negatives']} preserved negative")
    return 0
if __name__ == "__main__":
    sys.exit(main())
