#!/usr/bin/env python3
"""E422-N standalone verifier (record level; imports no CAIN code).

It recomputes every headline number and every hypothesis from the raw episode rows, verifies the
manifest signature and file hashes, and enforces the publication rules.  It does not re-execute the
search engine: the engine source is withheld under the CAIN-42 IP rule, and that limitation is
printed by the verifier itself.
"""
from __future__ import annotations

import hashlib
import json
import math
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
OK = 0
FAIL = 0


def check(name, cond, detail=""):
    global OK, FAIL
    if cond:
        OK += 1
        print(f"PASS {name}" + (f" · {detail}" if detail else ""))
    else:
        FAIL += 1
        print(f"FAIL {name}" + (f" · {detail}" if detail else ""))


def sha(b):
    return hashlib.sha256(b).hexdigest()


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def merkle(hashes):
    l = sorted(hashes)
    if not l:
        return sha(b"")
    while len(l) > 1:
        if len(l) % 2:
            l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0]


def binom_two_sided(wins, losses):
    n = wins + losses
    if n == 0:
        return 1.0
    k = min(wins, losses)
    tail = sum(math.comb(n, i) for i in range(k + 1)) / (2 ** n)
    return min(1.0, 2 * tail)


def main(d):
    d = Path(d)
    man = json.loads((d / "E422N_MANIFEST.json").read_text())
    rep = json.loads((d / "E422N_RUN_REPORT.json").read_text())
    prereg = json.loads((d / "E422N_PREREGISTRATION.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    rows = rep["rows"]

    check("schema", rep["schema"] == "cain42.e422n.run.v1")
    check("status line", rep["status"] == S and S in (d / "E422N_FINAL_REPORT.md").read_text())
    check("manifest schema", man["schema"] == "cain42.e422n.manifest.v1")
    check("manifest evolution", man["evolution"] == "E422-N")
    check("manifest label", man["label"] == rep["verdict"])

    # salt commitment
    commit = sha(json.dumps(salts, sort_keys=True).encode())
    check("salt commitment", commit == prereg["salt_commitment_sha256"], commit[:16])
    check("salts revealed", set(salts) == {"primary", "replication"} and len(set(salts.values())) == 2)

    # manifest signature + file hashes
    body = {k: v for k, v in man.items() if k != "signature"}
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try:
        pub.verify(bytes.fromhex(man["signature"]), canon(body))
        ok = True
    except InvalidSignature:
        ok = False
    check("manifest signature", ok)
    files = {k: v for k, v in man["files"].items()}
    bad = [n for n, h in files.items() if not (d / n).exists() or sha((d / n).read_bytes()) != h]
    check("file hashes", not bad, f"{len(files)} files")
    check("merkle root", merkle(list(files.values())) == man["merkle_root"], man["merkle_root"][:16])

    # episode accounting
    check("episode count", len(rows) == 288, str(len(rows)))
    check("episode schema", all(r["chain_ok"] is True for r in rows), "all chains ok")
    check("no authority from memory", all(r["authority_probe"]["allowed"] is False for r in rows))
    check("no model calls", rep["headline"]["model_calls"] == 0)

    def sel(sname, arm, cond):
        return [r for r in rows if r["salt_name"] == sname and r["arm"] == arm and r["condition"] == cond]

    def mean(xs):
        return sum(xs) / len(xs) if xs else 0.0

    # recompute every arm summary
    for sname in ("primary", "replication"):
        for arm in rep["design"]["arms"]:
            for cond in rep["design"]["conditions"]:
                rs = sel(sname, arm, cond)
                got = rep["summary"][sname][arm][cond]
                if got["episodes"] != len(rs):
                    check(f"summary count {sname}/{arm}/{cond}", False)
                    continue
                if got["solved"] != sum(1 for r in rs if r["solved"]):
                    check(f"summary solved {sname}/{arm}/{cond}", False)
                if abs(got["mean_total_units"] - round(mean([r["total_units"] for r in rs]), 2)) > 0.011:
                    check(f"summary units {sname}/{arm}/{cond}", False)
    check("arm summaries recomputed", True)

    # recompute hypotheses
    iso = {r["world"]: r["total_units"] for r in sel("primary", "isolated", "clean")}
    nr = {r["world"]: r["total_units"] for r in sel("primary", "neg_reaudit", "clean")}
    ratio = sum(nr.values()) / max(1, sum(iso.values()))
    wins = sum(1 for w in iso if nr[w] < iso[w])
    losses = sum(1 for w in iso if nr[w] > iso[w])
    h1 = ratio <= 0.75 and binom_two_sided(wins, losses) < 0.05
    check("H1 recompute", h1 == (rep["hypotheses"]["H1_efficiency"]["verdict"] == "SUPPORTED"),
          f"ratio {ratio:.3f}")
    iso_clean = sel("primary", "isolated", "clean")
    h2 = sum(1 for r in iso_clean if r["solved"]) / len(iso_clean) >= 0.90
    check("H2 recompute", h2 == (rep["hypotheses"]["H2_parity"]["verdict"] == "SUPPORTED"))
    unv = sum(1 for r in sel("primary", "neg_unverified", "poison") if r["solved"]) / 12
    rea = sum(1 for r in sel("primary", "neg_reaudit", "poison") if r["solved"]) / 12
    h3 = unv <= 0.10 and rea >= 0.90
    check("H3 recompute", h3 == (rep["hypotheses"]["H3_poison_safety"]["verdict"] == "SUPPORTED"),
          f"{unv:.3f}/{rea:.3f}")
    wit = sum(r["witness_checks"] for r in sel("primary", "neg_reaudit", "clean"))
    h4 = wit / max(1, sum(iso.values())) <= 0.10
    check("H4 recompute", h4 == (rep["hypotheses"]["H4_reaudit_cost"]["verdict"] == "SUPPORTED"))
    cap_rows = sel("primary", "neg_capped", "poison")
    cap = sum(1 for r in cap_rows if r["solved"]) / len(cap_rows)
    h5 = cap >= 0.90 and mean([r["total_units"] for r in cap_rows]) > mean(
        [r["total_units"] for r in sel("primary", "neg_reaudit", "poison")])
    check("H5 recompute", h5 == (rep["hypotheses"]["H5_deferred_repair"]["verdict"] == "SUPPORTED"))
    iso2 = {r["world"]: r["total_units"] for r in sel("replication", "isolated", "clean")}
    nr2 = {r["world"]: r["total_units"] for r in sel("replication", "neg_reaudit", "clean")}
    r2 = sum(nr2.values()) / max(1, sum(iso2.values()))
    h6 = (r2 <= 0.75
          and sum(1 for r in sel("replication", "neg_reaudit", "poison") if r["solved"]) / 12 >= 0.90
          and sum(1 for r in sel("replication", "neg_unverified", "poison") if r["solved"]) / 12 <= 0.10)
    check("H6 recompute", h6 == (rep["hypotheses"]["H6_replication"]["verdict"] == "SUPPORTED"))
    core = [h1, h2, h3, h4, h5, h6]
    verdict = ("NEGATIVE_KNOWLEDGE_POISONING_SUPPORTED" if all(core)
               else ("PARTIAL" if sum(core) >= 4 else "NOT_SUPPORTED"))
    check("verdict recompute", verdict == rep["verdict"], verdict)

    # poison accounting
    check("neg_unverified admits the poison", all(
        r["poison_admitted"] == 1 for r in sel("primary", "neg_unverified", "poison")))
    check("neg_reaudit catches the poison", all(
        r["poison_caught"] >= 1 for r in sel("primary", "neg_reaudit", "poison")))
    check("neg_reaudit clean never poisoned", all(
        r["poison_admitted"] == 0 for r in sel("primary", "neg_reaudit", "clean")))

    # publication rules
    check("external review blocked", rep["hypotheses"]["H7_external_review"]["verdict"] == "BLOCKED")
    src = [p.name for p in d.rglob("*") if p.is_file() and p.suffix == ".py"
           and "verify" not in p.name]
    check("engine source withheld", not src, str(src))
    check("no evidence of a paid model", "model_calls" in rep["headline"] and rep["headline"]["model_calls"] == 0)

    print(f"\n{OK}/{OK + FAIL} checks passed")
    print("Record-level verification: the search engine is not re-executed (source withheld).")
    print(S)
    return 0 if FAIL == 0 else 1


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