#!/usr/bin/env python3
"""E327 standalone verifier — stdlib + cryptography, imports no CAIN code."""
import hashlib, json, sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = {"live.py", "prereg.py"}


def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves: return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2: leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i+1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0]


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else "."); c = []
    def ck(n, ok, d=""): c.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})
    man = json.loads((B / "E327_MANIFEST.json").read_text())
    ck("status", man.get("status") == S)
    ck("label", man.get("label") in ("LIVE_SURFACE_VERIFIED", "DEFECTS_FOUND"))
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex: ck("signature", False, ex)
    files = man.get("files", {})
    ck("files", all((B / k).exists() for k in files))
    ck("hashes", not [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*") if x.is_file() and "__pycache__" not in x.parts}
    extra = {"E327_MANIFEST.json", "E327_SIGNED_BODY.json", "E327_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E327_OMEGA_SEAL.json", "E327_TAMPER_RESULTS.json"}
    ck("no unlisted", not (present - set(files) - extra), sorted(present - set(files) - extra)[:5])
    ck("code withheld", not any((B / n).exists() for n in ENG))
    pre = json.loads((B / "E327_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E327_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E327_RUN_REPORT.json").read_text())
    ck("prereg hash", sha((B / "E327_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("external not faked", json.loads((B / "E327_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("deviation disclosed", any(x.get("id") == "D4" and x.get("results_retained") is False for x in pre.get("deviations", [])))
    rows, homes, H = rep["rows"], rep["homes"], rep["hypotheses"]
    ck("rows", len(rows) == 168 and all(r["status"] == 200 for r in rows) and all(r["ok"] for r in rows))
    ck("homes", len(homes) == 3 and all(not h["missing"] and h["order_ok"] and h["status"] == 200 for h in homes.values()))
    ck("injections", len(H["H6_injected_defects"]["cases"]) == 4 and all(x["detected"] for x in H["H6_injected_defects"]["cases"]))
    req = ["H1_http_200", "H2_content_identity", "H3_seal_parity", "H4_blocks_present", "H5_canonical_order", "H6_injected_defects"]
    ck("hypotheses", all(H[k]["verdict"] == "SUPPORTED" for k in req))
    verdict = "LIVE_SURFACE_VERIFIED" if all(H[k]["verdict"] == "SUPPORTED" for k in req) else "DEFECTS_FOUND"
    ck("verdict", verdict == rep["verdict"] == man["label"])
    hd = man.get("headline", {})
    ck("headline", hd.get("claims") == 21 and hd.get("requests") == 168 and hd.get("matched") == 168
       and hd.get("homes") == 3 and hd.get("order_ok") is True and hd.get("injected") == 4)
    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e327.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "verdict": verdict}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


if __name__ == "__main__":
    sys.exit(main())
