#!/usr/bin/env python3
"""E433-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
RULE = {
    "trust1": lambda f, g: f == 0 and g == 0,
    "union3": lambda f, g: f < 3 and g == 0,
    "hash3": lambda f, g: f == 0 and g < 3,
    "union_hash": lambda f, g: f < 3 and g < 3,
    "full_scan": lambda f, g: g < 3,
}


def check(n, c, d=""):
    global OK, FAIL
    if c:
        OK += 1
        print(f"PASS {n}" + (f" · {d}" if d else ""))
    else:
        FAIL += 1
        print(f"FAIL {n}" + (f" · {d}" if d 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 cheapest(f, g):
    if g == 3:
        return None
    if f == 3:
        return "full_scan"
    if f == 0 and g == 0:
        return "trust1"
    if f > 0 and g == 0:
        return "union3"
    if f == 0 and g > 0:
        return "hash3"
    return "union_hash"


def main(d):
    d = Path(d)
    man = json.loads((d / "E433N_MANIFEST.json").read_text())
    rep = json.loads((d / "E433N_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E433N_PREREGISTRATION.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    dev = json.loads((d / "E433N_DEVIATIONS.json").read_text())
    rows = rep["rows"]

    check("schema", rep["schema"] == "cain42.e433n.run.v1")
    check("status line", rep["status"] == S and S in (d / "E433N_FINAL_REPORT.md").read_text())
    check("manifest", man["schema"] == "cain42.e433n.manifest.v1" and man["evolution"] == "E433-N")
    check("manifest label", man["label"] == rep["verdict"])
    check("salt commitment", sha(json.dumps(salts, sort_keys=True).encode()) == pre["salt_commitment_sha256"])
    check("salts revealed", set(salts) == {"primary", "replication"} and len(set(salts.values())) == 2)
    check("deviations recorded", len(dev["deviations"]) == 2 and {x["id"] for x in dev["deviations"]} == {"D1", "D2"})

    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) == 5120, str(len(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, f, g, p):
        return [r for r in rows if r["salt_name"] == s and r["f"] == f and r["g"] == g and r["policy"] == p]

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

    def work(s, f, g, p):
        rs = sel(s, f, g, p)
        return sum(r["work"] for r in rs) / len(rs)

    for s in ("primary", "replication"):
        for f in range(4):
            for g in range(4):
                for p in rep["design"]["policies"]:
                    got = rep["cells"][s][f"{f},{g}"][p]
                    if abs(got["rate"] - round(rate(s, f, g, p), 4)) > 1e-9:
                        check(f"cell rate {s}/{f},{g}/{p}", False)
                    if abs(got["work"] - round(work(s, f, g, p), 2)) > 0.011:
                        check(f"cell work {s}/{f},{g}/{p}", False)
    check("cell table recomputed", True)

    def frontier_ok(s):
        return all((rate(s, f, g, p) >= 0.90) == RULE[p](f, g)
                   for f in range(4) for g in range(4) for p in rep["design"]["policies"])

    def cheapest_ok(s):
        for f in range(4):
            for g in range(4):
                c = cheapest(f, g)
                exact = [p for p in rep["design"]["policies"] if rate(s, f, g, p) >= 0.90]
                if c is None:
                    if exact:
                        return False
                else:
                    if c not in exact:
                        return False
                    if min(work(s, f, g, p) for p in exact) < work(s, f, g, c) - 1e-9:
                        return False
        return True

    h1 = frontier_ok("primary")
    h2 = cheapest_ok("primary")
    h3 = all(work("primary", f, g, "union_hash") < work("primary", f, g, "full_scan")
             for f in range(1, 3) for g in range(1, 3))
    h4 = (all(rate("primary", f, 3, p) < 0.90 for f in range(4) for p in rep["design"]["policies"])
          and all(rate("primary", 3, g, "full_scan") >= 0.90 for g in (0, 1, 2))
          and all(rate("primary", 3, g, p) < 0.90 for g in (0, 1, 2)
                  for p in rep["design"]["policies"] if p != "full_scan"))
    h5 = frontier_ok("replication") and cheapest_ok("replication")
    for name, val in (("H1", h1), ("H2", h2), ("H3", h3), ("H4", h4), ("H5", h5)):
        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]
    verdict = ("RETRIEVAL_COST_FRONTIER_SUPPORTED" if all(core)
               else ("PARTIAL" if sum(core) >= 3 else "NOT_SUPPORTED"))
    check("verdict recompute", verdict == rep["verdict"], verdict)

    check("frontier table present", all(rep["frontier"][f"{f},{g}"] == cheapest(f, g)
                                       for f in range(4) for g in range(4)))
    check("g=3 is unrecoverable", all(rate("primary", f, 3, p) < 0.90
                                     for f in range(4) for p in rep["design"]["policies"]))
    check("external review blocked", rep["hypotheses"]["H6_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 retrieval 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 "."))
