#!/usr/bin/env python3
"""E332 standalone verifier — stdlib + cryptography, imports no CAIN code.

Recomputes every headline number from the recorded rows, checks the observation-table
certificate structural invariant on every wrong acceptance, the row hash chain, salt
commitments, the Ed25519 manifest signature and the preregistration freeze.

  python3 -I verify_e332_offline.py <bundle-dir>
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path


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(files):
    leaves = sorted(sha(p.read_bytes()) for p in files)
    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] if leaves else sha(b"")


CHECKS = []


def ck(name, ok, detail=None):
    CHECKS.append({"check": name, "ok": bool(ok), "detail": detail})
    return bool(ok)


def summarize(rows):
    honest = [r for r in rows if r["panel"] == "HONEST3"]
    coh = [r for r in rows if r["panel"].startswith("COHERENT2")]
    deep = [r for r in rows if r["panel"] == "COHERENT2_DEEP"]
    one = [r for r in rows if r["panel"] == "ONE_DECOY"]
    inc = [r for r in rows if r["panel"] == "INCOHERENT"]

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

    cert_rows = [r["cert_rows"] for r in rows if r["found"]]
    trace_rows = [r["trace_rows"] for r in rows if r["found"]]
    return {
        "rows": len(rows), "found": sum(1 for r in rows if r["found"]),
        "honest": len(honest), "honest_exact": c(honest, "NONE", "correct"),
        "honest_cert_accept": c(honest, "CERT", "accepted"),
        "honest_cert_refusal": c(honest, "CERT", "false_refusal"),
        "coherent": len(coh), "coherent_fooled": sum(1 for r in coh if r["eq_decoy"]),
        "coherent_none_false": c(coh, "NONE", "false_accept"),
        "coherent_cert_false": c(coh, "CERT", "false_accept"),
        "coherent_cert_reject": sum(1 for r in coh if not r["arms"]["CERT"]["accepted"]),
        "coherent_rand_false": c(coh, "RAND", "false_accept"),
        "coherent_spot_false": c(coh, "SPOT", "false_accept"),
        "coherent_cert_half_false": c(coh, "CERT_HALF", "false_accept"),
        "deep": len(deep), "deep_fooled": sum(1 for r in deep if r["eq_decoy"]),
        "deep_rand_false": c(deep, "RAND", "false_accept"),
        "deep_spot_false": c(deep, "SPOT", "false_accept"),
        "deep_cert_false": c(deep, "CERT", "false_accept"),
        "deep_cert_reject": sum(1 for r in deep if not r["arms"]["CERT"]["accepted"]),
        "deep_cert_hits": sum(1 for r in deep if r["cert_touches_corruption"]),
        "one_liar": len(one), "one_liar_exact": c(one, "NONE", "correct"),
        "incoherent": len(inc), "incoherent_failed": sum(1 for r in inc if not r["found"]),
        "incoherent_cert_false": c(inc, "CERT", "false_accept"),
        "all_cert_false": c(rows, "CERT", "false_accept"),
        "all_trace_false": c(rows, "TRACE", "false_accept"),
        "all_rand_false": c(rows, "RAND", "false_accept"),
        "all_spot_false": c(rows, "SPOT", "false_accept"),
        "all_cert_refusal": c(rows, "CERT", "false_refusal"),
        "cert_le_trace": sum(1 for r in rows if r["found"] and r["cert_rows"] <= r["trace_rows"]),
        "mean_cert_rows": round(sum(cert_rows) / max(1, len(cert_rows)), 3),
        "mean_trace_rows": round(sum(trace_rows) / max(1, len(trace_rows)), 3),
        "mean_queries": round(sum(r["queries"] for r in rows) / max(1, len(rows)), 3),
        "corrupt_fraction_mean": round(sum(r["corrupt_fraction"] for r in rows) / max(1, len(rows)), 6),
        "mean_corrupt_rows": round(sum(r["corrupt_rows"] for r in rows) / max(1, len(rows)), 3),
    }


def hyp_counts(s):
    return {
        "H1_honest_exact": (s["honest_exact"] == s["honest"] and s["honest_cert_accept"] == s["honest"]
                            and s["honest_cert_refusal"] == 0),
        "H2_coherent_fooled": s["coherent_fooled"] == s["coherent"],
        "H3_certificate_sound": (s["coherent_cert_false"] == 0 and s["all_cert_false"] == 0
                                 and s["coherent_cert_reject"] == s["coherent"]),
        "H4_partial_certificate_unsound": s["coherent_cert_half_false"] >= 1,
        "H5_spot_audit_unsound": s["deep_spot_false"] >= 1,
        "H6_certificate_cheaper": (s["mean_cert_rows"] < s["mean_trace_rows"]
                                   and s["cert_le_trace"] == s["found"]),
    }


def close(a, b):
    if isinstance(a, float) or isinstance(b, float):
        return abs(float(a) - float(b)) < 1e-9
    return a == b


def main(bundle):
    B = Path(bundle)
    man = json.loads((B / "MANIFEST.json").read_text())
    pre = json.loads((B / "E332_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E332_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E332_RUN_REPORT.json").read_text())
    sal = json.loads((B / "E332_SALT_REVEALED.json").read_text())
    chain = json.loads((B / "checkpoints/claim_chain.json").read_text())

    # 1. signature
    body = (B / "E332_SIGNED_BODY.json").read_bytes()
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), body)
        ck("manifest_signature", True)
    except Exception as e:  # noqa: BLE001
        ck("manifest_signature", False, str(e))
    ck("signed_body_is_manifest", json.loads(body)["files"] == man["files"])

    # 2. file digests and merkle
    ex = {"E332_MANIFEST.json", "E332_SIGNED_BODY.json", "E332_VERIFICATION_RESULTS.json",
          "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E332_OMEGA_SEAL.json",
          "E332_TAMPER_RESULTS.json"}
    files = sorted(p for p in B.rglob("*") if p.is_file()
                   and p.name not in ex and "__pycache__" not in p.parts)
    ck("file_count", len(files) == len(man["files"]),
       f"{len(files)} files vs {len(man['files'])}")
    bad = [str(p.relative_to(B)) for p in files
           if man["files"].get(str(p.relative_to(B))) != sha(p.read_bytes())]
    ck("file_digests", not bad, bad)
    ck("merkle_root", merkle(files) == man["merkle_root"] and
       (B / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])

    # 3. salts and freeze
    ck("salt_commitment_primary",
       sha(bytes.fromhex(sal["salts"]["primary"])) == pre["salt_commitment_sha256"]["primary"]
       == frz["salt_commitment_sha256"]["primary"])
    ck("salt_commitment_replication",
       sha(bytes.fromhex(sal["salts"]["replication"])) == pre["salt_commitment_sha256"]["replication"]
       == frz["salt_commitment_sha256"]["replication"])
    ck("prereg_freeze_hash", sha((B / "E332_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])

    # 4. recompute summaries and hypotheses
    rows = rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"]
    ck("row_count", len(rows) == rep["design"]["rows"] == chain["count"], f"{len(rows)} rows")
    ps, rs = summarize(rep["sets"]["primary"]["rows"]), summarize(rep["sets"]["replication"]["rows"])
    ts = summarize(rows)
    for name, got, want in (("primary", ps, rep["sets"]["primary"]["summary"]),
                            ("replication", rs, rep["sets"]["replication"]["summary"]),
                            ("all", ts, rep["summary"]["all"])):
        bad = [k for k in got if k not in want or not close(got[k], want[k])]
        ck(f"summary_{name}", not bad, bad[:6])
    ck("salted_sets_disjoint",
       rep["sets"]["primary"]["salt_commitment"] != rep["sets"]["replication"]["salt_commitment"])

    hc = hyp_counts(ps)
    hr = hyp_counts(rs)
    for k, ok in hc.items():
        ck(f"hypothesis_{k}", ok == (rep["hypotheses"][k]["verdict"] == "SUPPORTED"),
           f"recomputed={ok} stored={rep['hypotheses'][k]['verdict']}")
    ck("hypothesis_H7_replication", (all(hr.values())) ==
       (rep["hypotheses"]["H7_replication"]["verdict"] == "SUPPORTED"))
    ck("hypothesis_H8_blocked", rep["hypotheses"]["H8_external_review"]["verdict"] == "BLOCKED")
    ok_all = all(rep["hypotheses"][k]["verdict"] == "SUPPORTED" for k in list(rep["hypotheses"])[:7])
    ck("verdict_rule", rep["verdict"] ==
       ("SEQUENTIAL_CERTIFICATE_SOUNDNESS_SUPPORTED" if ok_all else "NOT_SUPPORTED"))
    ck("manifest_label", man["label"] == rep["verdict"])
    ck("identity_status", rep["status"] == pre["status"] and "NOT ESTABLISHED" in pre["status"])

    # 5. chain
    prev = "0" * 64
    ok_chain = True
    for r in rows:
        h = sha((prev + sha(canon({k: v for k, v in r.items() if k != "hash"}))).encode())
        ok_chain = ok_chain and h == r.get("hash")
        prev = h
    ck("row_chain", ok_chain and prev == chain["head"])
    ck("chain_mid", rows[len(rows) // 2 - 1]["hash"] == chain["mid"])

    # 6. structural soundness witnesses
    cert_false = [r for r in rows if r["arms"]["CERT"]["false_accept"]]
    ck("certificate_zero_false_accepts", not cert_false, [r["world"] for r in cert_false][:5])
    bad_wit = [r["world"] + "/" + r["panel"] for r in rows
               if r["arms"]["CERT"]["false_accept"] and not r["cert_touches_corruption"]]
    ck("certificate_witness", not bad_wit, bad_wit[:5])
    wrong_coh = [r for r in rows if r["panel"].startswith("COHERENT2") and
                 r["arms"]["NONE"]["false_accept"]]
    ck("every_coherent_wrong_rule_touches_certificate",
       all(r["cert_touches_corruption"] for r in wrong_coh),
       f"{len(wrong_coh)} wrong rules")
    ck("certificate_subset_of_trace", all(r.get("cert_subset_trace", True) for r in rows))
    ck("cert_rows_le_trace", all(r["cert_rows"] <= r["trace_rows"] for r in rows))
    ck("all_coherent_fooled", all(r["eq_decoy"] for r in rows
                                  if r["panel"].startswith("COHERENT2")))
    ck("honest_identification_exact",
       all(r["eq_truth"] for r in rows if r["panel"] == "HONEST3"))
    ck("one_liar_outvoted",
       all(r["eq_truth"] for r in rows if r["panel"] == "ONE_DECOY"))
    ck("incoherent_never_confidently_wrong",
       all((not r["found"]) or r["eq_truth"] for r in rows if r["panel"] == "INCOHERENT"))
    ck("arm_discipline", all(
        (a["correct"] + a["false_accept"]) <= 1 and not (a["accepted"] and a["false_refusal"])
        for r in rows for a in r["arms"].values()))

    # 6b. manifest headline must equal the recomputed numbers
    hl = man["headline"]
    ck("manifest_headline", (
        hl["rows"] == ts["rows"] and hl["cert_false_accepts"] == ts["all_cert_false"]
        and hl["coherent_fooled"] == f"{ts['coherent_fooled']}/{ts['coherent']}"
        and hl["coherent_cert_reject"] == f"{ts['coherent_cert_reject']}/{ts['coherent']}"
        and hl["half_cert_false"] == ts["coherent_cert_half_false"]
        and hl["spot_false"] == ts["coherent_spot_false"]
        and hl["cost_matched_random_false"] == ts["coherent_rand_false"]
        and close(hl["mean_cert_rows"], ts["mean_cert_rows"])
        and close(hl["mean_trace_rows"], ts["mean_trace_rows"])
        and hl["model_calls"] == 0), hl)

    # 7. resources
    ck("no_model_calls", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0
       and rep["resources"]["weights_changed"] is False)
    ck("no_engine_source_published",
       not any(p.suffix == ".py" and p.name != "verify_e332_offline.py" for p in B.rglob("*"))
       and not any(p.name in ("automata.py", "learner.py", "experiment.py", "run.py") for p in B.rglob("*")))
    ck("external_review_blocked",
       json.loads((B / "E332_EXTERNAL_REVIEW_STATUS.json").read_text())["status"] == "NOT_OBTAINED")

    passed = sum(1 for c in CHECKS if c["ok"])
    out = {"schema": "cain42.e332.verification.v1", "evolution": "E332",
           "checks": len(CHECKS), "passed": passed, "failed": [c for c in CHECKS if not c["ok"]],
           "verdict": rep["verdict"], "merkle_root": man["merkle_root"]}
    print(json.dumps(out, indent=1))
    return 0 if passed == len(CHECKS) else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
