#!/usr/bin/env python3
"""E338 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 partition results, checks the salt commitments, the p^k independence prediction, 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/e338/repeat.py", "cain/cain2027/e338/run.py")
ARMS = ("ROW", "P2_1", "P2_2", "P2_4", "P2_8", "G8_1", "G8_3", "G8_6",
        "G16_1", "G16_3", "G16_6")
EX = {"E338_MANIFEST.json", "E338_SIGNED_BODY.json", "E338_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E338_OMEGA_SEAL.json",
      "E338_TAMPER_RESULTS.json", "E338_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 / "E338_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e338.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 / "E338_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E338_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E338_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E338_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E338_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 / "E338_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("engine hashes", len(pre.get("engine_sha256", {})) == 8)

    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("alias estimates", all(abs(sum(r["alias_rate"].values()) - sum(r["alias_rate"].values())) < 1e-12
                              and all(0.0 <= v <= 1.0 for v in r["alias_rate"].values()) for r in acc))

    def det(rs, arm):
        return (sum(1 for r in rs if not r["arms"][arm]["accept"]) / len(rs)) if rs else 0.0

    def fa(rs, arm):
        return sum(1 for r in rs if r["arms"][arm]["accept"])

    def ref(rs, arm):
        return sum(1 for r in rs if not r["arms"][arm]["accept"])

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

    by = {}
    for s in ("primary", "replication"):
        by[s] = [r for r in rep["sets"][s]["rows"] if r["accepted"] and not r["correct"]]
    cp, cr = by["primary"], by["replication"]
    hp = [r for r in rep["sets"]["primary"]["rows"] if r["accepted"] and r["correct"]]
    hr = [r for r in rep["sets"]["replication"]["rows"] if r["accepted"] and r["correct"]]

    h1 = (fa(cp, "ROW") == 0 and fa(cr, "ROW") == 0 and
          ref(hp, "ROW") == 0 and ref(hr, "ROW") == 0 and
          det(cp, "ROW") == 1.0 and det(cr, "ROW") == 1.0)
    mono, strict = True, False
    for ks in (("P2_1", "P2_2", "P2_4", "P2_8"), ("G8_1", "G8_3", "G8_6"),
               ("G16_1", "G16_3", "G16_6")):
        for rs in (cp, cr):
            vals = [det(rs, a) for a in ks]
            if any(vals[i] > vals[i + 1] + 1e-12 for i in range(len(vals) - 1)):
                mono = False
            if vals[0] < 1.0 and vals[-1] > vals[0]:
                strict = True
    h2 = mono and strict
    h3 = all(det(c, "G8_3") >= 0.99 and q(c, "G8_3") <= 0.5 * q(c, "ROW")
             for c in (cp, cr))
    pred_det = 1.0 - sum(r["alias_rate"]["8"] ** 3 for r in cap) / len(cap)
    obs_det = det(cap, "G8_3")
    h4 = abs(pred_det - obs_det) <= 0.03
    h5 = any(det(cap, a) >= 0.99 and q(cap, a) < 0.5 * q(cap, "ROW")
             for a in ARMS if a != "ROW")
    h6 = all(ref(hp, a) == 0 and ref(hr, a) == 0 for a in ARMS)
    h7 = (mono and det(cr, "G8_3") >= 0.99 and q(cr, "G8_3") <= 0.5 * q(cr, "ROW") and
          abs((1.0 - sum(r["alias_rate"]["8"] ** 3 for r in cr) / len(cr)) -
              det(cr, "G8_3")) <= 0.05)
    H = rep["hypotheses"]
    for k, ok in (("H1_row_audit_exact", h1), ("H2_repetition_helps", h2),
                  ("H3_group8x3_cheap_exact", h3), ("H4_independence_model", h4),
                  ("H5_pooling_frontier", h5), ("H6_honest_never_refused", h6),
                  ("H7_replication", h7)):
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    verdict = ("REPEATED_PARTITION_AUDIT_SUPPORTED"
               if all((h1, h2, h3, h4, h5, h6, h7)) 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 cost", all(abs(sm["cost_ratio"][a] - q(cap, a) / q(cap, "ROW")) < 1e-9 for a in ARMS))
    ck("H3 values", abs(H["H3_group8x3_cheap_exact"]["cost_ratio_primary"] -
                        q(cp, "G8_3") / q(cp, "ROW")) < 1e-9)
    ck("H4 values", abs(H["H4_independence_model"]["predicted_detection"] - pred_det) < 1e-9 and
       abs(H["H4_independence_model"]["observed_detection"] - obs_det) < 1e-9)
    ck("mean cert", abs(sm["mean_cert"] - sum(r["cert_size"] for r in acc) / len(acc)) < 1e-9)
    # the honest nuance: group 16 repetition cannot fix a certificate no wider than a group
    stuck = [r for r in cap if r["arms"]["G16_1"]["accept"]]
    ck("group16 stuck disclosed", all(r["cert_size"] <= 16 for r in stuck))

    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 / "E338_DEVIATIONS.json").read_text())
                                ["deviations"]) == 1)
    ck("status line", S in (B / "E338_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)

    passed = sum(1 for x in c if x["ok"])
    out = {"schema": "cain42.e338.verify.v1", "checks": len(c), "passed": passed,
           "failed": [x for x in c if not x["ok"]], "verdict": verdict,
           "g8x1": round(det(cap, "G8_1"), 4), "g8x3": round(det(cap, "G8_3"), 4),
           "g8x3_cost": round(q(cap, "G8_3") / q(cap, "ROW"), 4),
           "g16x1": round(det(cap, "G16_1"), 4), "g16x6": round(det(cap, "G16_6"), 4),
           "predicted": round(pred_det, 4)}
    print(json.dumps(out))
    try:
        (B.parent / "E338_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())
