#!/usr/bin/env python3
"""E335 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. The engine source is withheld by the IP rule; the verifier validates the recorded rows
and the decision rule, not the engine implementation.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ARMS = ("NONE", "TRUTH", "P2_ONE", "P2_SHARED", "HALF_TRUTH", "SPOT5")
EX = {"E335_MANIFEST.json", "E335_SIGNED_BODY.json", "E335_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E335_OMEGA_SEAL.json",
      "E335_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):
        return {
            "wrong_accepted": sum(1 for r in wrong if r["arms"][arm]["wrong_family"]),
            "wrong_refused": sum(1 for r in wrong if not r["arms"][arm]["accepted"]),
            "correct_refused": sum(1 for r in good if r["arms"][arm]["false_refusal"]),
            "wrong_family_fraction": _frac(sum(1 for r in wrong if r["arms"][arm]["wrong_family"]), len(wrong)),
            "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)),
            "accepted_fraction": _frac(sum(1 for r in rows if r["arms"][arm]["accepted"]), len(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": sum(1 for r in rows if r["arms"][arm]["accepted"]),
            "wrong_families_bought": sum(1 for r in rows if r["arms"][arm]["wrong_family"]),
            "mean_family_k": _frac(sum(r["arms"][arm]["family_k"] for r in rows), len(rows)),
        }

    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"))
    saved = sum(r["purchase"]["extra_labels"] for r in wrong
                if r["arms"]["P2_ONE"]["accepted"] is False)
    spent = sum(r["arms"]["P2_ONE"]["checked"] for r in rows)
    out["economics"] = {
        "extra_labels_saved_by_refusing_wrong_anchors": saved,
        "verification_rows_spent": spent,
        "net_label_saving": saved - spent,
        "none_total_labels": out["arms"]["NONE"]["total_labels"],
        "p2_one_total_labels": out["arms"]["P2_ONE"]["total_labels"],
        "total_label_fraction_saved": _frac(out["arms"]["NONE"]["total_labels"]
                                            - out["arms"]["P2_ONE"]["total_labels"],
                                            out["arms"]["NONE"]["total_labels"]),
    }
    out["two_decoy_cells"] = sum(1 for r in rows if r["p1"] == "two_decoy3")
    out["spot5_mean_checked"] = _frac(sum(r["arms"]["SPOT5"]["checked"] for r in rows), len(rows))
    return out


def decide(all_s, rep_s, two_decoy_cells):
    def h1(s):
        return (s["two_decoy_none_wrong_fraction"] or 0) >= 0.95

    def h2(s):
        return (s["arms"]["P2_ONE"]["wrong_accepted"] == 0
                and (s["arms"]["P2_ONE"]["refusal_fraction_on_wrong"] or 0) >= 0.95)

    def h3(s):
        return (s["arms"]["P2_ONE"]["false_refusal_fraction"] or 0) <= 0.05

    def h4(s):
        return (s["economics"]["p2_one_total_labels"] < s["economics"]["none_total_labels"]
                and s["economics"]["net_label_saving"] > 0)

    def h5(s):
        return s["arms"]["SPOT5"]["wrong_accepted"] > 0

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

    H = {
        "H1_hazard": "SUPPORTED" if h1(all_s) else "NOT_SUPPORTED",
        "H2_full_independent_catches": "SUPPORTED" if h2(all_s) else "NOT_SUPPORTED",
        "H3_no_false_refusal": "SUPPORTED" if h3(all_s) else "NOT_SUPPORTED",
        "H4_net_label_saving": "SUPPORTED" if h4(all_s) else "NOT_SUPPORTED",
        "H5_partial_unsound": "SUPPORTED" if h5(all_s) else "NOT_SUPPORTED",
        "H6_shared_verifier_fails": "SUPPORTED" if h6(all_s) else "NOT_SUPPORTED",
        "H7_replication": ("SUPPORTED" if (h1(rep_s) and h2(rep_s) and h3(rep_s) and h4(rep_s))
                           else "NOT_SUPPORTED"),
        "H8_external_review": "BLOCKED",
    }
    verdict = ("PRE_PURCHASE_VERIFICATION_SUPPORTED"
               if all(H[k] == "SUPPORTED" for k in H if k != "H8_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 / "E335_MANIFEST.json").read_text())
    pre = json.loads((d / "E335_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E335_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E335_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E335_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E335_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E335_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E335_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E335_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e335.manifest.v1")
    ck("evolution", man.get("evolution") == "E335" and rep.get("evolution") == "E335")
    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
                   and p.name != "E335_TAMPER_RESULTS.json")
    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 / "E335_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 / "E335_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"])

    # engine source must not be published
    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_e335_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, sa["two_decoy_cells"])
    ck("verdict", verdict == rep["verdict"])
    ck("hypotheses", all(H[k] == rep["hypotheses"][k]["verdict"]
                         for k in H if k != "H8_external_review"))
    ck("h1 count", rep["hypotheses"]["H1_hazard"].get("two_decoy_cells") == sa["two_decoy_cells"])
    ck("h5 mean", rep["hypotheses"]["H5_partial_unsound"].get("spot5_mean_checked")
       == sa["spot5_mean_checked"])
    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"],
        "p2_one_wrong_accepted": sa["arms"]["P2_ONE"]["wrong_accepted"],
        "p2_one_false_refusal_fraction": sa["arms"]["P2_ONE"]["false_refusal_fraction"],
        "spot5_wrong_accepted": sa["arms"]["SPOT5"]["wrong_accepted"],
        "p2_shared_wrong_fraction": sa["arms"]["P2_SHARED"]["wrong_family_fraction"],
        "net_label_saving": sa["economics"]["net_label_saving"],
        "verification_rows_spent": sa["economics"]["verification_rows_spent"],
        "labels_saved": sa["economics"]["extra_labels_saved_by_refusing_wrong_anchors"],
        "total_label_fraction_saved": sa["economics"]["total_label_fraction_saved"],
    }
    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"] == "PRE_PURCHASE_VERIFICATION_SUPPORTED"))
    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())
