#!/usr/bin/env python3
"""E339 standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Recomputes every hypothesis and the verdict from the raw cells, checks the row chain, the
preregistration/freeze ordering, the salt commitments, the manifest, and that no engine source is
published. Record-level: it validates the recorded rows and the decision rule, not the engine.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ARMS = ("NONE", "CERT_P2", "CERT_TRUTH", "REID_ONE", "REID_SHARED")
EX = {"E339_MANIFEST.json", "E339_SIGNED_BODY.json", "E339_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E339_OMEGA_SEAL.json",
      "E339_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).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 _frac(n, d):
    return round(n / d, 6) if d else None


def summarize(rows):
    wrong = [r for r in rows if r["anchor"]["accepted"] and not r["anchor"]["correct"]]
    good = [r for r in rows if r["anchor"]["accepted"] and r["anchor"]["correct"]]
    out = {"cells": len(rows), "wrong_anchors": len(wrong), "correct_anchors": len(good)}

    def counts(arm):
        acc = [r for r in rows if r["arms"][arm]["accepted"]]
        return {
            "accepted": len(acc),
            "wrong_accepted": sum(1 for r in wrong if r["arms"][arm]["wrong_family"]),
            "refusal_fraction_on_wrong": _frac(sum(1 for r in wrong if not r["arms"][arm]["accepted"]), len(wrong)),
            "false_refusal_fraction": _frac(sum(1 for r in good if r["arms"][arm]["false_refusal"]), len(good)),
            "wrong_family_fraction": _frac(sum(1 for r in wrong if r["arms"][arm]["wrong_family"]), len(wrong)),
            "mean_cost": _frac(sum(r["arms"][arm]["cost"] for r in rows), len(rows)),
            "total_cost": sum(r["arms"][arm]["cost"] for r in rows),
            "total_labels": sum(r["arms"][arm]["total_labels"] for r in rows),
            "mean_total_labels": _frac(sum(r["arms"][arm]["total_labels"] for r in rows), len(rows)),
            "families_bought": len(acc),
            "wrong_families_bought": sum(1 for r in rows if r["arms"][arm]["wrong_family"]),
        }

    out["arms"] = {arm: counts(arm) for arm in ARMS}
    out["two_decoy_none_wrong_fraction"] = _frac(
        sum(1 for r in rows if r["p1"] == "two_decoy3" and r["arms"]["NONE"]["wrong_family"]),
        sum(1 for r in rows if r["p1"] == "two_decoy3"))
    none_total = out["arms"]["NONE"]["total_labels"]
    cert_total = out["arms"]["CERT_P2"]["total_labels"]
    reid_total = out["arms"]["REID_ONE"]["total_labels"]
    out["economics"] = {
        "none_total_labels": none_total,
        "cert_total_labels": cert_total,
        "reid_total_labels": reid_total,
        "cert_net_saving": none_total - cert_total,
        "reid_net_saving": none_total - reid_total,
        "cert_ratio_of_reid": _frac(cert_total, reid_total),
        "cost_ratio_check_vs_reid": _frac(out["arms"]["CERT_P2"]["mean_cost"],
                                          out["arms"]["REID_ONE"]["mean_cost"]),
    }
    return out


def h1_s(s):
    return (s["arms"]["CERT_P2"]["wrong_accepted"] == 0
            and s["arms"]["REID_ONE"]["wrong_accepted"] == 0
            and (s["arms"]["CERT_P2"]["refusal_fraction_on_wrong"] or 0) >= 0.95
            and (s["arms"]["REID_ONE"]["refusal_fraction_on_wrong"] or 0) >= 0.95)


def h2_s(s):
    return ((s["arms"]["CERT_P2"]["false_refusal_fraction"] or 0) <= 0.05
            and (s["arms"]["REID_ONE"]["false_refusal_fraction"] or 0) <= 0.05)


def h3_s(s):
    c = s["arms"]["CERT_P2"]["mean_cost"] or 0
    r = s["arms"]["REID_ONE"]["mean_cost"] or 1
    return c < r and (c / r) <= 0.75


def h4_s(s):
    e = s["economics"]
    return e["cert_net_saving"] > 0 and e["reid_net_saving"] <= 0


def h5_s(s):
    return (s["arms"]["REID_SHARED"]["wrong_family_fraction"] or 0) >= 0.95


def decide(sa, sr):
    H = {
        "H1_both_exact": ("SUPPORTED" if h1_s(sa) else "NOT_SUPPORTED"),
        "H2_no_false_refusals": ("SUPPORTED" if h2_s(sa) else "NOT_SUPPORTED"),
        "H3_check_is_cheaper": ("SUPPORTED" if h3_s(sa) else "NOT_SUPPORTED"),
        "H4_only_check_is_self_funding": ("SUPPORTED" if h4_s(sa) else "NOT_SUPPORTED"),
        "H5_shared_reid_fails": ("SUPPORTED" if h5_s(sa) else "NOT_SUPPORTED"),
        "H6_replication": ("SUPPORTED" if (h1_s(sr) and h2_s(sr) and h4_s(sr)) else "NOT_SUPPORTED"),
        "H7_external_review": "BLOCKED",
    }
    verdict = ("CHEAP_VERIFICATION_DOMINATES"
               if all(H[k] == "SUPPORTED" for k in H if k != "H7_external_review")
               else "NOT_SUPPORTED")
    return H, verdict


def chain_ok(chain):
    prev = "0" * 64
    for i, x in enumerate(chain):
        if x["i"] != i or x["prev"] != prev:
            return False
        prev = x["hash"]
    return True


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

    def ck(name, cond):
        checks.append((name, bool(cond)))

    man = json.loads((d / "E339_MANIFEST.json").read_text())
    pre = json.loads((d / "E339_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E339_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E339_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E339_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E339_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E339_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E339_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E339_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e339.manifest.v1")
    ck("evolution", man.get("evolution") == "E339" and rep.get("evolution") == "E339")
    ck("status", man.get("status") == S and rep.get("status") == S)
    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("manifest files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("manifest 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 / "E339_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("signed body binds merkle", body["merkle_root"] == man["merkle_root"])

    ck("prereg freeze", sha((d / "E339_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("freeze precedes run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                               for k, v in salt["salts"].items()))
    ck("salt revealed after run", salt["revealed_at"] >= rep["generated_at"])

    leak = [p.name for p in d.rglob("*") if p.is_file() and p.name in
            ("run.py", "verify.py", "build_seq.py", "learner.py", "world.py", "grammar.py",
             "certificate.py", "oracles.py")]
    ck("source withheld", not leak)
    ck("no engine leak text", not any("from cain.cain2027" in p.read_text(errors="ignore")
                                      for p in d.rglob("*.py")
                                      if p.name != "verify_e339_offline.py"))

    sets = rep["sets"]
    prow, rrow = sets["primary"]["rows"], sets["replication"]["rows"]
    allr = prow + rrow
    ck("cells", len(allr) == 72 and len(prow) == 36 and len(rrow) == 36)
    ck("cell schema", all(set(r) >= {"p1", "anchor", "purchase", "arms"} for r in allr))
    ck("arms complete", all(all(a in r["arms"] for a in ARMS) for r in allr))
    sp, sr, sa = summarize(prow), summarize(rrow), summarize(allr)
    ck("summary primary", sp == rep["summaries"]["primary"])
    ck("summary replication", sr == rep["summaries"]["replication"])
    ck("summary all", sa == rep["summaries"]["all"])
    H, verdict = decide(sa, sr)
    ck("verdict", verdict == rep["verdict"])
    ck("hypotheses", all(H[k] == rep["hypotheses"][k]["verdict"]
                         for k in H if k != "H7_external_review"))
    ck("wrong anchor count", sa["wrong_anchors"] == 24 and sa["correct_anchors"] == 48)
    expected_finding = {
        "cells": sa["cells"], "wrong_anchors": sa["wrong_anchors"],
        "correct_anchors": sa["correct_anchors"],
        "two_decoy_none_wrong_fraction": sa["two_decoy_none_wrong_fraction"],
        "cert_wrong_accepted": sa["arms"]["CERT_P2"]["wrong_accepted"],
        "reid_wrong_accepted": sa["arms"]["REID_ONE"]["wrong_accepted"],
        "cert_false_refusal_fraction": sa["arms"]["CERT_P2"]["false_refusal_fraction"],
        "reid_false_refusal_fraction": sa["arms"]["REID_ONE"]["false_refusal_fraction"],
        "cert_mean_cost": sa["arms"]["CERT_P2"]["mean_cost"],
        "reid_mean_cost": sa["arms"]["REID_ONE"]["mean_cost"],
        "cost_ratio": sa["economics"]["cost_ratio_check_vs_reid"],
        "cert_net_saving": sa["economics"]["cert_net_saving"],
        "reid_net_saving": sa["economics"]["reid_net_saving"],
        "shared_reid_wrong_fraction": sa["arms"]["REID_SHARED"]["wrong_family_fraction"],
    }
    ck("finding", all(rep["finding"][k] == v for k, v in expected_finding.items()))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in report_md)
    ck("acceptance", acc["verdict"] == rep["verdict"]
       and acc["all_pass"] == (rep["verdict"] == "CHEAP_VERIFICATION_DOMINATES"))
    ck("external", ext["status"] == "NOT_OBTAINED")
    ck("deviations recorded", dev.get("deviations") == []
       and "No deviations" in (dev.get("note") or ""))
    ck("model calls zero", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0)
    ck("limits present", len(rep["limits"]) >= 8)

    ch = [json.loads(l) for l in (d / "checkpoints/claim_chain.jsonl").read_text().splitlines()]
    ck("row chain", chain_ok(ch) and len(ch) == len(allr))
    ck("row chain head", ch[-1]["hash"] == rep["checkpoint"]["head"])
    cp = json.loads((d / "checkpoints/claim_chain.json").read_text())
    ck("checkpoint", cp["count"] == len(ch) and cp["head"] == ch[-1]["hash"]
       and cp["mid"] == ch[len(ch) // 2]["hash"])

    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())
