#!/usr/bin/env python3
"""E423-N standalone verifier (record level; imports no CAIN code)."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
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(hs):
    l = sorted(hs)
    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 main(d):
    d = Path(d)
    man = json.loads((d / "E423N_MANIFEST.json").read_text())
    rep = json.loads((d / "E423N_RUN_REPORT.json").read_text())
    prereg = json.loads((d / "E423N_PREREGISTRATION.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    rows = rep["rows"]

    check("schema", rep["schema"] == "cain42.e423n.run.v1")
    check("status line", rep["status"] == S and S in (d / "E423N_FINAL_REPORT.md").read_text())
    check("manifest schema", man["schema"] == "cain42.e423n.manifest.v1")
    check("manifest evolution", man["evolution"] == "E423-N")
    check("manifest label", man["label"] == rep["verdict"])
    check("salt commitment", sha(json.dumps(salts, sort_keys=True).encode()) == prereg["salt_commitment_sha256"])
    check("salts revealed", set(salts) == {"primary", "replication"} and len(set(salts.values())) == 2)

    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)
    bad = [n for n, h in man["files"].items() if not (d / n).exists() or sha((d / n).read_bytes()) != h]
    check("file hashes", not bad, f"{len(man['files'])} files")
    check("merkle root", merkle(list(man["files"].values())) == man["merkle_root"])

    check("episode count", len(rows) == 576, str(len(rows)))
    check("all chains valid", all(r["chain_ok"] is True for r in rows))
    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(s, arm, cond):
        return [r for r in rows if r["salt_name"] == s and r["arm"] == arm and r["condition"] == cond]

    def rate(s, arm, cond):
        rs = sel(s, arm, cond)
        return sum(1 for r in rs if r["solved"]) / len(rs)

    def mrows(s, arm, cond):
        rs = sel(s, arm, cond)
        return sum(r["row_reads"] for r in rs) / len(rs)

    # recompute every summary
    for s in ("primary", "replication"):
        for arm in rep["design"]["arms"]:
            for cond in rep["design"]["conditions"]:
                got = rep["summary"][s][arm][cond]
                rs = sel(s, arm, cond)
                if got["solved"] != sum(1 for r in rs if r["solved"]):
                    check(f"summary solved {s}/{arm}/{cond}", False)
                if abs(got["mean_row_reads"] - round(sum(r["row_reads"] for r in rs) / len(rs), 1)) > 0.11:
                    check(f"summary rows {s}/{arm}/{cond}", False)
    check("arm summaries recomputed", True)

    h1 = rate("primary", "one_auditor", "poison1") <= 0.10
    h2 = rate("primary", "unanimous2", "poison1") >= 0.90 and rate("primary", "unanimous2", "poison2") <= 0.10
    h3 = rate("primary", "unanimous3", "poison2") >= 0.90
    iso = mrows("primary", "isolated", "clean")
    single = mrows("primary", "single", "clean")
    audit = ("one_auditor", "unanimous2", "majority3", "unanimous3")
    h4 = (all(mrows("primary", a, "clean") <= 1.05 * iso for a in audit)
          and (max(mrows("primary", a, "clean") for a in audit) - single) / iso <= 0.05)
    h5 = all(rate("primary", a, "clean") >= 0.90 for a in audit)
    h6 = (rate("replication", "one_auditor", "poison1") <= 0.10
          and rate("replication", "unanimous2", "poison1") >= 0.90
          and rate("replication", "unanimous2", "poison2") <= 0.10
          and rate("replication", "unanimous3", "poison2") >= 0.90)
    for name, val in (("H1", h1), ("H2", h2), ("H3", h3), ("H4", h4), ("H5", h5), ("H6", h6)):
        key = next(k for k in rep["hypotheses"] if k.startswith(name))
        check(f"{name} recompute", val == (rep["hypotheses"][key]["verdict"] == "SUPPORTED"))
    core = [h1, h2, h3, h4, h5, h6]
    verdict = ("NEGATIVE_KNOWLEDGE_AUDITOR_QUORUM_SUPPORTED" if all(core)
               else ("PARTIAL" if sum(core) >= 4 else "NOT_SUPPORTED"))
    check("verdict recompute", verdict == rep["verdict"], verdict)

    # the law itself, per condition
    check("single admits the lone poison", all(
        r["poison_admitted"] == 1 for r in sel("primary", "single", "poison0")))
    check("one auditor falls to a colluding auditor", all(
        r["poison_admitted"] == 1 for r in sel("primary", "one_auditor", "poison1")))
    check("unanimous-2 refutes a colluding auditor", all(
        r["poison_admitted"] == 0 for r in sel("primary", "unanimous2", "poison1")))
    check("unanimous-3 survives two colluders", all(
        r["poison_admitted"] == 0 for r in sel("primary", "unanimous3", "poison2")))
    check("clean worlds never quarantined by poison", all(
        r["poison_admitted"] == 0 for r in sel("primary", "unanimous3", "clean")))

    # every reported rate must equal the recomputed rate
    def close(a, b):
        return abs(float(a) - float(b)) < 1e-9
    hl = rep["headline"]
    checks = [
        ("headline single", hl["single_poison1"], rate("primary", "single", "poison1")),
        ("headline one_auditor", hl["one_auditor_poison1"], rate("primary", "one_auditor", "poison1")),
        ("headline unanimous2 p1", hl["unanimous2_poison1"], rate("primary", "unanimous2", "poison1")),
        ("headline unanimous2 p2", hl["unanimous2_poison2"], rate("primary", "unanimous2", "poison2")),
        ("headline majority3 p2", hl["majority3_poison2"], rate("primary", "majority3", "poison2")),
        ("headline unanimous3 p2", hl["unanimous3_poison2"], rate("primary", "unanimous3", "poison2")),
        ("H1 field", rep["hypotheses"]["H1_one_auditor_not_enough"]["one_auditor_poison1"],
         rate("primary", "one_auditor", "poison1")),
        ("H2 field p1", rep["hypotheses"]["H2_unanimous2_boundary"]["poison1"],
         rate("primary", "unanimous2", "poison1")),
        ("H2 field p2", rep["hypotheses"]["H2_unanimous2_boundary"]["poison2"],
         rate("primary", "unanimous2", "poison2")),
        ("H3 field", rep["hypotheses"]["H3_unanimous3"]["poison2"], rate("primary", "unanimous3", "poison2")),
    ]
    check("reported rates match rows", all(close(a, b) for _, a, b in checks),
          str([n for n, a, b in checks if not close(a, b)]))
    check("H4 field", abs(rep["hypotheses"]["H4_audit_cost"]["overhead_share"]
                          - (max(mrows("primary", x, "clean") for x in audit) - single) / iso) < 5e-5)
    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))

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