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

Recomputes every hypothesis and the verdict from the 48 raw identification rows and their
per-arm Monte Carlo accept rates, checks the salt commitments, the SHA-256 claim chain, the
manifest signature, the file hashes and the Merkle root.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("cain/cain2027/e340/noise.py", "cain/cain2027/e340/run.py")
ARMS = ("ROW_EXACT", "G8_3_EXACT", "ROW_E01", "G8_3_E01", "ROW_E05", "G8_3_E05",
        "G8_3_E10", "G8_3_E05_T1", "G8_6_E05_T1", "G8_3_E05_T2", "G2_3_E05_T1",
        "G16_3_E05_T1")
EX = {"E340_MANIFEST.json", "E340_SIGNED_BODY.json", "E340_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E340_OMEGA_SEAL.json",
      "E340_TAMPER_RESULTS.json", "E340_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 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 / "E340_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e340.manifest.v1")
    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"))
    ck("merkle file", (B / "MERKLE_ROOT.txt").read_text().strip() == 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 / "E340_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E340_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E340_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E340_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E340_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(rev[k])) ==
                               pre["salt_commitment_sha256"][k] for k in ("primary", "replication")))
    ck("external not faked",
       json.loads((B / "E340_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("engine hashes", len(pre.get("engine_sha256", {})) == 8)
    ck("calibration disclosed", "calibrat" in json.dumps(pre).lower())
    ck("100 draws", rep["summary"]["draws"] == 100)

    allr = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 24, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["world"], r["panel"]) for r in rows}) == 24)
    ck("total runs", len(allr) == 48, len(allr))
    acc = [r for r in allr if r["accepted"]]
    cap = [r for r in acc if not r["correct"]]
    hon = [r for r in acc if r["correct"]]
    ck("accepted", len(acc) == 48, len(acc))
    ck("captured/honest", len(cap) == 24 and len(hon) == 24, (len(cap), len(hon)))
    ck("arms present", all(set(r["arms"]) == set(ARMS) for r in acc))
    ck("certificates valid", all(r["cert_valid"] for r in acc))
    ck("draw accounting", all(r["arms"][a]["draws"] == 100 and 0 <= r["arms"][a]["accepts"] <= 100
                              for r in acc for a in ARMS))
    ck("accept rate consistency", all(abs(r["arms"][a]["accept_rate"] -
                                          r["arms"][a]["accepts"] / r["arms"][a]["draws"]) < 1e-12
                                      for r in acc for a in ARMS))

    def det(rs, arm):
        return sum(1.0 - r["arms"][arm]["accept_rate"] for r in rs) / len(rs) if rs else 0.0

    def fr(rs, arm):
        return sum(1.0 - r["arms"][arm]["accept_rate"] for r in rs) / len(rs) if rs else 0.0

    def q(rs, arm):
        return sum(r["arms"][arm]["groups"] for r in rs) / len(rs) if rs else 0.0

    def by_salt(s):
        rs = rep["sets"][s]["rows"]
        return ([r for r in rs if r["accepted"] and not r["correct"]],
                [r for r in rs if r["accepted"] and r["correct"]])

    cp, hp = by_salt("primary")
    cr, hr = by_salt("replication")
    h1 = (det(cp, "ROW_EXACT") >= 0.999 and det(cr, "ROW_EXACT") >= 0.999
          and fr(hp, "ROW_EXACT") == 0.0 and fr(hr, "ROW_EXACT") == 0.0
          and det(cap, "G8_3_EXACT") >= 0.999
          and q(cap, "G8_3_EXACT") <= 0.5 * q(cap, "ROW_EXACT"))
    h2 = fr(hon, "G8_3_E01") <= 0.15 and det(cap, "G8_3_E01") >= 0.99
    h3 = fr(hon, "G8_3_E05") >= 0.70 and det(cap, "G8_3_E05") >= 0.99
    h4 = fr(hon, "ROW_E05") <= fr(hon, "G8_3_E05") - 0.20
    h5 = fr(hon, "G8_3_E05_T1") <= 0.25 and det(cap, "G8_3_E05_T1") >= 0.75
    h6 = (fr(hon, "G8_3_E05_T2") < fr(hon, "G8_3_E05_T1")
          and det(cap, "G8_3_E05_T2") < det(cap, "G8_3_E05_T1"))
    h7 = (det(cap, "G8_6_E05_T1") >= det(cap, "G8_3_E05_T1") + 0.05
          and fr(hon, "G8_6_E05_T1") >= fr(hon, "G8_3_E05_T1") + 0.05)
    h8 = (fr(hr, "G8_3_E01") <= 0.15 and det(cr, "G8_3_E01") >= 0.99
          and fr(hr, "G8_3_E05") >= 0.70
          and fr(hr, "ROW_E05") <= fr(hr, "G8_3_E05") - 0.20
          and fr(hr, "G8_3_E05_T1") <= 0.25 and det(cr, "G8_3_E05_T1") >= 0.75
          and fr(hr, "G8_3_E05_T2") < fr(hr, "G8_3_E05_T1")
          and det(cr, "G8_3_E05_T2") < det(cr, "G8_3_E05_T1")
          and det(cr, "G8_6_E05_T1") >= det(cr, "G8_3_E05_T1") + 0.05
          and fr(hr, "G8_6_E05_T1") >= fr(hr, "G8_3_E05_T1") + 0.05)
    H = rep["hypotheses"]
    for k, ok in (("H1_exact_arms_replicate", h1), ("H2_one_percent_manageable", h2),
                  ("H3_five_percent_breaks_specificity", h3),
                  ("H4_pooling_amplifies_noise", h4),
                  ("H5_tolerance_recovers_liveness", h5),
                  ("H6_tolerance_two_trades_more", h6),
                  ("H7_repetition_under_noise", h7), ("H8_replication", h8)):
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    verdict = ("NOISY_AUDIT_BOUNDARY_SUPPORTED"
               if all((h1, h2, h3, h4, h5, h6, h7, h8)) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    sm = rep["summary"]
    ck("summary detection", all(abs(sm["detection"][a] - det(cap, a)) < 1e-9 for a in ARMS))
    ck("summary false refusal", all(abs(sm["false_refusal"][a] - fr(hon, a)) < 1e-9 for a in ARMS))
    ck("summary cost", all(abs(sm["cost_ratio"][a] - q(cap, a) / q(cap, "ROW_EXACT")) < 1e-9
                           for a in ARMS))
    ck("H4 values", abs(H["H4_pooling_amplifies_noise"]["gap"] -
                        (fr(hon, "G8_3_E05") - fr(hon, "ROW_E05"))) < 1e-9)
    ck("H5 values", abs(H["H5_tolerance_recovers_liveness"]["detection"] -
                        det(cap, "G8_3_E05_T1")) < 1e-9)
    ck("mean cert", abs(sm["mean_cert"] - sum(r["cert_size"] for r in acc) / len(acc)) < 1e-9)

    ch = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", len(ch) == 48, len(ch))
    prev = "0" * 64
    okc = True
    for h, r in zip(ch, allr):
        e = {"i": r.get("world", 0), "grammar": r["grammar"], "panel": r["panel"],
             "salt": "primary" if r in rep["sets"]["primary"]["rows"] else "replication",
             "accepted": r["accepted"], "correct": r["correct"]}
        if h["prev"] != prev or h["hash"] != sha((prev + sha(canon(e))).encode()):
            okc = False
            break
        prev = h["hash"]
    ck("chain recompute", okc)
    ck("deviation recorded", len(json.loads((B / "E340_DEVIATIONS.json").read_text())
                                ["deviations"]) == 1)
    ck("status line", S in (B / "E340_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 7)
    ck("zero model calls", rep["resources"]["model_calls"] == 0 and
       rep["resources"]["api_spend_usd"] == 0.0)
    ck("failed hypotheses kept", all(H[k]["verdict"] == "NOT_SUPPORTED"
                                     for k in ("H1_exact_arms_replicate",
                                               "H2_one_percent_manageable", "H8_replication")))

    passed = sum(1 for x in c if x["ok"])
    out = {"schema": "cain42.e340.verify.v1", "checks": len(c), "passed": passed,
           "failed": [x for x in c if not x["ok"]], "verdict": verdict,
           "row_e05_fr": round(fr(hon, "ROW_E05"), 4),
           "g8_e05_fr": round(fr(hon, "G8_3_E05"), 4),
           "g8_e01_fr": round(fr(hon, "G8_3_E01"), 4),
           "g8_t1_fr": round(fr(hon, "G8_3_E05_T1"), 4),
           "g8_t1_det": round(det(cap, "G8_3_E05_T1"), 4),
           "g8_t2_fr": round(fr(hon, "G8_3_E05_T2"), 4),
           "g8_t2_det": round(det(cap, "G8_3_E05_T2"), 4),
           "g8_3_exact_det": round(det(cap, "G8_3_EXACT"), 4)}
    print(json.dumps(out))
    try:
        (B.parent / "E340_VERIFICATION_RESULTS.json").write_text(json.dumps(
            {"returncode": 0 if passed == len(c) else 1, "checks": len(c),
             "passed": passed, "output": json.dumps(out)}, indent=1))
    except OSError:
        pass
    return 0 if passed == len(c) else 1


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