#!/usr/bin/env python3
"""E367 standalone verifier (stdlib + cryptography; imports no CAIN code)."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
PANELS = ("honest3", "p3_m2_ad", "p5_m3_ad")
MODES = ("A1", "A3_1", "A3_2", "A5_2", "A5_3")
SALTS = ("primary", "replication")
EX = {"E367_MANIFEST.json", "E367_SIGNED_BODY.json", "E367_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E367_OMEGA_SEAL.json",
      "E367_TAMPER_RESULTS.json"}


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


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    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]


def count(rows, salt, pname, mode):
    rs = [r for r in rows if r["salt"] == salt and r["panel"] == pname]
    return _count(rs, mode)


def count_panel(rows, pname, mode):
    return _count([r for r in rows if r["panel"] == pname], mode)


def _count(rs, mode):
    if mode == "majority":
        return {"n": len(rs), "verified": sum(1 for r in rs if r["majority"]["verified"]),
                "false_accept": sum(1 for r in rs if r["majority"]["false_accept"]),
                "mean_labels": round(sum(r["majority"]["labels"] for r in rs) / len(rs), 2) if rs else None}
    return {"n": len(rs), "verified": sum(1 for r in rs if r["repair"][mode]["verified"]),
            "false_accept": sum(1 for r in rs if r["repair"][mode]["false_accept"]),
            "mean_labels": round(sum(r["repair"][mode]["labels"] for r in rs) / len(rs), 2) if rs else None,
            "mean_anchor_reads": round(sum(r["repair"][mode]["anchor_reads"] for r in rs) / len(rs), 2) if rs else None,
            "attribution_correct": sum(1 for r in rs if r["repair"][mode]["attribution_correct"]),
            "attribution_inverted": sum(1 for r in rs if r["repair"][mode]["attribution_inverted"])}


def decide(rows):
    summ = {sn: {pn: {m: count(rows, sn, pn, m) for m in ("majority",) + MODES} for pn in PANELS}
            for sn in SALTS}
    p = {pn: {m: count_panel(rows, pn, m) for m in ("majority",) + MODES} for pn in PANELS}
    q = summ["replication"]
    lost = ("p3_m2_ad", "p5_m3_ad")

    def v(pn, m):
        return p[pn][m]["verified"]

    def fa(pn, m):
        return p[pn][m]["false_accept"]

    H = {
        "H1_truthful_anchor_repairs": {
            "verdict": "SUPPORTED" if all(v(pn, "A1") >= 18 and fa(pn, "A1") == 0 for pn in lost) else "NOT_SUPPORTED",
            "detail": "the single truthful anchor (E363-A baseline) verifies >=18/24 with 0 false accepts in both lost-quorum panels"},
        "H2_one_anchor_liar_is_outvoted": {
            "verdict": "SUPPORTED" if all(v(pn, "A3_1") >= 18 and fa(pn, "A3_1") == 0 for pn in lost) else "NOT_SUPPORTED",
            "detail": "a 2-of-3 anchor with one independent liar still repairs >=18/24 with 0 false accepts"},
        "H3_two_anchor_colluders_break": {
            "verdict": "SUPPORTED" if all(v(pn, "A3_2") <= 4 for pn in lost) else "NOT_SUPPORTED",
            "detail": "a 2-of-3 anchor with two colluders fails to repair (<=4/24) in both lost-quorum panels"},
        "H4_3of5_anchor_absorbs_two": {
            "verdict": "SUPPORTED" if all(v(pn, "A5_2") >= 18 and fa(pn, "A5_2") == 0 for pn in lost) else "NOT_SUPPORTED",
            "detail": "a 3-of-5 anchor with two colluders still repairs >=18/24 with 0 false accepts"},
        "H5_3of5_anchor_breaks_at_three": {
            "verdict": "SUPPORTED" if all(v(pn, "A5_3") <= 4 for pn in lost) else "NOT_SUPPORTED",
            "detail": "a 3-of-5 anchor with three colluders fails to repair (<=4/24) in both lost-quorum panels"},
        "H6_cost": {
            "verdict": ("SUPPORTED" if all((p[pn][m]["mean_labels"] or 0) <= 8 * (p[pn]["majority"]["mean_labels"] or 1)
                                           and (p[pn][m]["mean_anchor_reads"] or 0) <= 60
                                           for pn in lost for m in ("A1", "A3_1", "A5_2")) else "NOT_SUPPORTED"),
            "detail": "the working anchor modes use <=60 anchor reads and <=8x the colony's labels in the lost-quorum panels"},
        "H7_replication": {
            "verdict": ("SUPPORTED" if (q["p3_m2_ad"]["A1"]["verified"] >= 9
                                        and q["p5_m3_ad"]["A1"]["verified"] >= 9
                                        and q["p3_m2_ad"]["A3_1"]["verified"] >= 9
                                        and q["p5_m3_ad"]["A3_1"]["verified"] >= 9
                                        and q["p3_m2_ad"]["A3_2"]["verified"] <= 2
                                        and q["p5_m3_ad"]["A3_2"]["verified"] <= 2) else "NOT_SUPPORTED"),
            "detail": "the replication salt repeats H1-H3 at >=9/12 or <=2/12"},
        "H8_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("FALLIBLE_ANCHOR_QUORUM_SUPPORTED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H8_external_review")
               else "NOT_SUPPORTED")
    return summ, p, H, verdict


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(n, c):
        checks.append((n, bool(c)))

    man = json.loads((d / "E367_MANIFEST.json").read_text())
    pre = json.loads((d / "E367_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E367_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E367_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E367_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E367_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E367_DEVIATIONS.json").read_text())
    raw = json.loads((d / "E367_RAW_ROWS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e367.manifest.v1" and rep.get("evolution") == "E367")
    files = sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX
                   and "__pycache__" not in p.parts)
    ck("files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle", man["merkle_root"] == merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body = json.loads((d / "E367_SIGNED_BODY.json").read_text())
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]), canon(body))
    ck("signature", True)
    ck("freeze", sha((d / "E367_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("salts", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                    for k, v in salt["salts"].items()))
    ck("source withheld", not any(q.name in ("run.py", "verify.py") for q in d.rglob("*") if q.is_file()))
    rows = rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"]
    ck("episodes", len(rows) == 72 and len(raw) == 72)
    ck("raw rows", raw == rows)
    summ, p, H, verdict = decide(rows)
    ck("summary", summ == rep["summaries"])
    ck("verdict", verdict == rep["verdict"])
    ck("hypotheses", H == rep["hypotheses"])
    ch = [json.loads(l) for l in (d / "checkpoints/claim_chain.jsonl").read_text().splitlines()]
    prev = "0" * 64
    rec = []
    for r in rows:
        hh = sha((prev + sha(json.dumps(r, sort_keys=True, separators=(",", ":")))).encode())
        rec.append(hh)
        prev = hh
    ck("chain", [x["hash"] for x in ch] == rec
       and [x["prev"] for x in ch] == (["0" * 64] + rec[:-1]) and ch[-1]["hash"] == rep["checkpoint"]["head"])
    cp = json.loads((d / "checkpoints/claim_chain.json").read_text())
    ck("chain file", cp["count"] == len(ch) and cp["head"] == rec[-1])
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E367_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E367_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("deviations", isinstance(dev.get("deviations"), list) and len(dev["deviations"]) == 0)
    ck("resources", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)
    ck("finding", rep["finding"]["episodes"] == len(rows) and rep["finding"]["worlds"] == 12
       and rep["finding"]["law"] == "the repair anchor obeys the same quorum law: n > 2m repairs, n <= 2m does not")
    ck("audit", rep["design"]["audit_rows"] == 80)
    ck("status", rep["status"] == S and man["status"] == S)
    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


if __name__ == "__main__":
    sys.exit(main())
