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

Recomputes every headline number from the recorded rows, the certificate witness, the adversary
coverage masks, the row hash chain, the salt commitments, the preregistration freeze and the
Ed25519 manifest signature.

  python3 -I verify_e333_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):
    dec = [r for r in rows if r["panel"] in ("COHERENT2_A", "COHERENT2_B")]
    coh_a = [r for r in rows if r["panel"] == "COHERENT2_A"]
    coh_b = [r for r in rows if r["panel"] == "COHERENT2_B"]
    hon = [r for r in rows if r["panel"] == "HONEST3"]
    found = [r for r in rows if r["found"]]

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

    masks = [(m["class"], m["mask"]) for r in hon for m in r["coverage_masks"]]
    le = [m for m in masks if m[0] == "le"]
    gt = [m for m in masks if m[0] == "gt"]
    oe = [m for m in masks if m[0] == "one_edit"]
    return {
        "rows": len(rows), "found": len(found), "honest": len(hon), "decoys": len(dec),
        "decoy_a": len(coh_a), "decoy_b": len(coh_b),
        "honest_exact": c(hon, "NONE", "correct"),
        "table_false": c(dec, "TABLE", "false_accept"),
        "table_reject": sum(1 for r in dec if not r["arms"]["TABLE"]["accepted"]),
        "closed_false": c(dec, "CLOSED", "false_accept"),
        "closed_reject": sum(1 for r in dec if not r["arms"]["CLOSED"]["accepted"]),
        "state_only_false": c(dec, "STATE_ONLY", "false_accept"),
        "state_only_reject": sum(1 for r in dec if not r["arms"]["STATE_ONLY"]["accepted"]),
        "onerow_in_reject": sum(1 for r in coh_a if not r["arms"]["ONEROW"]["accepted"]),
        "onerow_in_total": len(coh_a),
        "onerow_out_reject": sum(1 for r in coh_b if not r["arms"]["ONEROW"]["accepted"]),
        "onerow_out_total": len(coh_b),
        "rand_false": c(dec, "RAND", "false_accept"),
        "mean_table": round(sum(r["table_rows"] for r in found) / max(1, len(found)), 3),
        "mean_state_only": round(sum(r["state_only_rows"] for r in found) / max(1, len(found)), 3),
        "mean_closed": round(sum(r["closed_rows"] for r in found) / max(1, len(found)), 3),
        "mean_trace": round(sum(r["trace_rows"] for r in found) / max(1, len(found)), 3),
        "closed_lt_table": sum(1 for r in found if r["closed_rows"] < r["table_rows"]),
        "honest_refusal": c(hon, "CLOSED", "false_refusal"),
        "coverage_one_edit": {"total": len(oe), "rejected": sum(1 for m in oe if m[1])},
        "coverage_le": {"total": len(le), "rejected": sum(1 for m in le if m[1])},
        "coverage_gt": {"total": len(gt), "rejected": sum(1 for m in gt if m[1])},
        "onerow_size_mean": round(sum(len(r["onerow"]) for r in coh_a) / max(1, len(coh_a)), 3),
    }


def hyp_counts(s):
    return {
        "H1_table_sound": s["table_false"] == 0 and s["table_reject"] == s["decoys"],
        "H2_closed_sound": (s["closed_false"] == 0 and s["closed_reject"] == s["decoys"]
                            and s["coverage_one_edit"]["rejected"] == s["coverage_one_edit"]["total"]
                            and s["coverage_le"]["rejected"] == s["coverage_le"]["total"]),
        "H3_closed_smaller": s["mean_closed"] < s["mean_table"],
        "H4_state_only_unsound": s["state_only_false"] >= 1,
        "H5_onerow_overfits": (s["onerow_in_reject"] == s["onerow_in_total"]
                               and s["onerow_out_reject"] < s["onerow_out_total"]),
        "H6_cost_order": s["mean_closed"] < s["mean_table"] < s["mean_trace"],
    }


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 / "E333_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E333_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E333_RUN_REPORT.json").read_text())
    sal = json.loads((B / "E333_SALT_REVEALED.json").read_text())
    chain = json.loads((B / "checkpoints/claim_chain.json").read_text())

    body = (B / "E333_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"])

    ex = {"E333_MANIFEST.json", "E333_SIGNED_BODY.json", "E333_VERIFICATION_RESULTS.json",
          "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E333_OMEGA_SEAL.json",
          "E333_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"])

    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 / "E333_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])

    rows = rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"]
    ck("row_count", len(rows) == 72, f"{len(rows)} rows")
    ck("row_count_chain", len(rows) == chain["count"])
    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, hr = hyp_counts(ps), 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"] ==
       ("TRANSITION_CLOSURE_CERTIFICATE_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"])

    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"])

    # certificate witnesses
    ck("table_zero_false_accepts", all(not r["arms"]["TABLE"]["false_accept"] for r in rows))
    ck("closed_zero_false_accepts", all(not r["arms"]["CLOSED"]["false_accept"] for r in rows))
    ck("state_only_fails_somewhere", any(r["arms"]["STATE_ONLY"]["false_accept"]
                                        for r in rows if r["panel"].startswith("COHERENT2")))
    arows = [r for r in rows if r["panel"] == "COHERENT2_A"]
    bros = [r for r in rows if r["panel"] == "COHERENT2_B"]
    ck("onerow_is_one_row", all(len(r["onerow"]) <= 1 for r in arows))
    ck("onerow_rejects_in_sample", all(not r["arms"]["ONEROW"]["accepted"] for r in arows))
    ck("onerow_misses_held_out", any(r["arms"]["ONEROW"]["accepted"] for r in bros))
    ck("closed_rows_at_least_state_only", all(r["closed_rows"] >= r["state_only_rows"] for r in rows))

    # adversary coverage masks
    ok_cov, bad_cov = True, []
    for r in rows:
        if r["panel"] != "HONEST3":
            continue
        ms = r["coverage_masks"]
        dg = sha(canon([(m["class"], m["size"], m["mask"]) for m in ms]))
        stored = r["coverage"]
        if dg != stored["mask_sha256"] or stored["adversaries"] != len(ms):
            ok_cov = False
            bad_cov.append(r["world"])
    ck("coverage_digest_and_counts", ok_cov, bad_cov[:5])
    ck("coverage_one_edit_total", ps["coverage_one_edit"]["total"] > 0
       and ps["coverage_le"]["total"] > 0)

    hl = man["headline"]
    ck("manifest_headline", (
        hl["rows"] == ts["rows"] and hl["closed_false_accepts"] == ts["closed_false"]
        and hl["state_only_false_accepts"] == ts["state_only_false"]
        and hl["table_false_accepts"] == ts["table_false"]
        and hl["onerow_held_out_rejected"] == ts["onerow_out_reject"]
        and hl["onerow_held_out_total"] == ts["onerow_out_total"]
        and close(hl["mean_closed_rows"], ts["mean_closed"])
        and close(hl["mean_table_rows"], ts["mean_table"])
        and hl["model_calls"] == 0), hl)

    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_e333_offline.py" for p in B.rglob("*"))
       and not any(p.name in ("certificates.py", "run.py", "automata.py", "learner.py") for p in B.rglob("*")))
    ck("external_review_blocked",
       json.loads((B / "E333_EXTERNAL_REVIEW_STATUS.json").read_text())["status"] == "NOT_OBTAINED")

    passed = sum(1 for c in CHECKS if c["ok"])
    out = {"schema": "cain42.e333.verification.v1", "evolution": "E333",
           "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 "."))
