#!/usr/bin/env python3
"""E301 standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Recomputes every headline number from the raw claim rows: cell summaries, both
hypotheses sets, the verdict, the anchor fraction, the fail-closed counts, the
truth-in-surviving-set count and the SHA-256 claim chain. Verifies the preregistration
hash, the salt commitments, the manifest signature, every file digest and the Merkle
root.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("world.py", "oracles.py", "enumerate.py", "identify.py", "run.py", "prereg.py")
GRAMMARS = ("A", "B", "C")
PANELS = ("honest4", "one_decoy4", "two_decoy4", "two_disjoint4")
ARMS = ("PIN3", "PIN4", "PIN4A")
EX = {"E301_MANIFEST.json", "E301_SIGNED_BODY.json", "E301_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E301_OMEGA_SEAL.json",
      "E301_TAMPER_RESULTS.json", "E301_ACCEPTANCE_REGISTRY.json"}


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 summary(rows):
    n = len(rows)
    if not n:
        return None
    return {
        "n": n,
        "accepted": sum(1 for r in rows if r["accepted"]),
        "accepted_correct": sum(1 for r in rows if r["accepted"] and r["correct"]),
        "false_accept": sum(1 for r in rows if r["false_accept"]),
        "correct": sum(1 for r in rows if r["correct"]),
        "failed": sum(1 for r in rows if r["failed"]),
        "cap_or_empty": sum(1 for r in rows if r["failed"] == "cap_or_empty"),
        "budget": sum(1 for r in rows if r["failed"] == "budget"),
        "truth_in": sum(1 for r in rows if r["truth_in"]),
        "mean_labels": sum(r["labels"] for r in rows) / n,
        "mean_anchor_queries": sum(r["anchor_queries"] for r in rows) / n,
        "anchor_fraction": (sum(r["anchor_queries"] for r in rows) /
                            max(1, sum(r["labels"] for r in rows))),
        "decoy_diff_fraction": sum(r["decoy_diff"] for r in rows) / n,
    }


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        h = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": h})
        prev = h
    return out


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    c = []

    def ck(name, ok, detail=""):
        c.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})

    man = json.loads((B / "E301_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e301.manifest.v1", man.get("schema"))
    ck("status", man.get("status") == S)
    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 present", all((B / k).exists() for k in files))
    ck("file 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}
    ck("no unlisted file", not (present - set(files) - EX), sorted(present - set(files) - EX)[:5])
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E301_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E301_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E301_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E301_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E301_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"],
       f'{frz["frozen_at"]} <= {rep["generated_at"]}')
    ck("two salts", set(rev["salts"]) == {"primary", "replication"})
    ck("salt commitments", all(sha(bytes.fromhex(rev["salts"][k])) ==
                               pre["salt_commitment_sha256"][k] for k in rev["salts"]))
    ck("external not faked",
       json.loads((B / "E301_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")

    allr = []
    for salt in ("primary", "replication"):
        st = rep["sets"][salt]
        rows = st["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 432, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["panel"], r["arm"], r["world"]) for r in rows}) == 432)
        for g in GRAMMARS:
            for p in PANELS:
                for a in ARMS:
                    k = f"{g}|{p}|{a}"
                    ck(f"{salt} {k}", summary([r for r in rows if r["grammar"] == g and
                                               r["panel"] == p and r["arm"] == a]) == st["summary"][k])
    ck("total claims", len(allr) == 864, len(allr))

    p4a = [r for r in allr if r["arm"] == "PIN4A"]
    p4 = [r for r in allr if r["arm"] == "PIN4"]
    p3 = [r for r in allr if r["arm"] == "PIN3"]
    rp = rep["sets"]["primary"]["rows"]
    rr = rep["sets"]["replication"]["rows"]
    p3d = [r for r in rp if r["arm"] == "PIN3" and r["panel"] in ("two_decoy4", "two_disjoint4")]
    p4ad = [r for r in rp if r["arm"] == "PIN4A" and r["panel"] in ("two_decoy4", "two_disjoint4")]
    p4d = [r for r in rp if r["arm"] == "PIN4" and r["panel"] in ("two_decoy4", "two_disjoint4")]
    r4a = [r for r in rr if r["arm"] == "PIN4A"]
    r4ad = [r for r in rr if r["arm"] == "PIN4A" and r["panel"] in ("two_decoy4", "two_disjoint4")]
    r4d = [r for r in rr if r["arm"] == "PIN4" and r["panel"] in ("two_decoy4", "two_disjoint4")]

    h1 = sum(1 for r in p4a if r["false_accept"]) == 0
    acc4a = sum(1 for r in p4a if r["accepted"] and r["correct"])
    h2 = acc4a >= 0.95 * len(p4a)
    h3 = sum(1 for r in p3d if r["false_accept"]) >= 1
    af = sum(r["anchor_queries"] for r in p4a) / max(1, sum(r["labels"] for r in p4a))
    h4 = af <= 0.50 and (
        sum(1 for r in p4ad if r["accepted"] and r["correct"]) >=
        sum(1 for r in p4d if r["accepted"] and r["correct"]))
    h5 = all((not r["false_accept"]) and r["failed"] != "cap_or_empty"
             for r in rp if r["arm"] == "PIN4A" and r["grammar"] == "C")
    raf = sum(r["anchor_queries"] for r in r4a) / max(1, sum(r["labels"] for r in r4a))
    h6 = (sum(1 for r in r4a if r["false_accept"]) == 0 and
          sum(1 for r in r4a if r["accepted"] and r["correct"]) >= 0.95 * len(r4a) and
          raf <= 0.50 and
          sum(1 for r in r4ad if r["accepted"] and r["correct"]) >=
          sum(1 for r in r4d if r["accepted"] and r["correct"]) and
          all((not r["false_accept"]) and r["failed"] != "cap_or_empty"
              for r in rr if r["arm"] == "PIN4A" and r["grammar"] == "C"))
    h7 = all(r["truth_in"] for r in p4a)
    exp = {"H1_decoy_no_false": h1, "H2_pin4a_liveness": h2, "H3_pin3_captured": h3,
           "H4_minimal_anchor": h4, "H5_scale_c": h5, "H6_replication": h6, "H7_soundness": h7}
    H = rep["hypotheses"]
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"),
           f'{H[k]["verdict"]} vs {"SUPPORTED" if ok else "NOT_SUPPORTED"}')
    ck("H1 count", H["H1_decoy_no_false"]["false_accepts"] ==
       sum(1 for r in p4a if r["false_accept"]))
    ck("H2 count", H["H2_pin4a_liveness"]["accepted_correct"] == acc4a)
    ck("H3 count", H["H3_pin3_captured"]["pin3_false_accepts_two_colluders"] ==
       sum(1 for r in p3d if r["false_accept"]))
    ck("H4 fraction", abs(H["H4_minimal_anchor"]["mean_anchor_fraction"] - af) < 1e-4)
    ck("H7 count", H["H7_soundness"]["truth_in"] == sum(1 for r in p4a if r["truth_in"]))
    ck("soundness report", rep["soundness"]["truth_in"] == sum(1 for r in p4a if r["truth_in"]) and
       rep["soundness"]["pin4a_claims"] == len(p4a))
    ck("resources counts", rep["resources"]["claims"] == 864 and rep["resources"]["decisions"] == 864)
    verdict = ("ADAPTIVE_DECOY_PINNING_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"), f'{verdict} vs {rep["verdict"]}')
    ck("manifest headline", man.get("headline", {}).get("verdict") == rep["verdict"])
    ck("manifest counts", man.get("headline", {}).get("claims") == 864 and
       man.get("headline", {}).get("decisions") == 864)

    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 864)
    ck("chain head", cp["head"] == ch[-1]["hash"])
    ck("chain mid", cp["mid"] == ch[len(ch) // 2]["hash"])
    ck("chain file", len(json.loads("[" + ",".join(
        (B / "checkpoints/claim_chain.jsonl").read_text().strip().splitlines()) + "]")) == 864)
    ck("chain recompute", sha((ch[-2]["hash"] + sha(canon(allr[-1]))).encode()) == ch[-1]["hash"])
    ck("resume", rep["checkpoint"]["resume"] is True)
    ck("status line", S in (B / "E301_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 5)
    ck("zero model calls", rep["resources"]["model_calls"] == 0 and
       rep["resources"]["api_spend_usd"] == 0.0)

    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e301.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())
