#!/usr/bin/env python3
"""E342-R standalone offline 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"
REGIMES = ("PERSISTENT", "INTERMITTENT", "MOSTLY_HONEST")
ARMS = ("SINGLE", "BLIND_3", "HEALTH_4_3", "HEALTH_8_3")
MAX_ATTEMPTS = 3
EX = {"E342R_MANIFEST.json", "E342R_SIGNED_BODY.json", "E342R_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E342R_OMEGA_SEAL.json",
      "E342R_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):
    out = {"cells": len(rows), "anomalies": sum(1 for r in rows if r.get("anomaly")),
           "wrong_families": 0}
    max_attempts = 0
    for reg in REGIMES:
        out[reg] = {}
        for arm in ARMS:
            vals = [r["regimes"][reg][arm] for r in rows]
            dets = sum(v["detections"] for v in vals)
            caps = sum(v["captured_attempts"] for v in vals)
            max_attempts = max(max_attempts, max((v["attempts"] for v in vals), default=0))
            out[reg][arm] = {
                "success_fraction": _frac(sum(1 for v in vals if v["success"]), len(vals)),
                "wrong_family": sum(1 for v in vals if v["wrong_family"]),
                "mean_labels": _frac(sum(v["labels"] for v in vals), len(vals)),
                "mean_purchase_labels": _frac(sum(v["purchase_labels"] for v in vals), len(vals)),
                "mean_probe_labels": _frac(sum(v["probe_labels"] for v in vals), len(vals)),
                "mean_attempts": _frac(sum(v["attempts"] for v in vals), len(vals)),
                "mean_purchases": _frac(sum(v["purchases"] for v in vals), len(vals)),
                "total_labels": sum(v["labels"] for v in vals),
            }
            if arm.startswith("HEALTH"):
                out[reg][arm]["detections"] = dets
                out[reg][arm]["captured_attempts"] = caps
                out[reg][arm]["detection_fraction"] = _frac(dets, caps)
    out["max_attempts"] = max_attempts
    out["wrong_families"] = sum(1 for r in rows for reg in REGIMES for arm in ARMS
                                if r["regimes"][reg][arm]["wrong_family"])
    p = out["PERSISTENT"]
    m = out["MOSTLY_HONEST"]
    out["economics"] = {
        "persistent_blind_labels": p["BLIND_3"]["mean_labels"],
        "persistent_health4_labels": p["HEALTH_4_3"]["mean_labels"],
        "persistent_health8_labels": p["HEALTH_8_3"]["mean_labels"],
        "persistent_saving4": _frac(p["BLIND_3"]["mean_labels"] - p["HEALTH_4_3"]["mean_labels"],
                                    p["BLIND_3"]["mean_labels"]),
        "persistent_saving8": _frac(p["BLIND_3"]["mean_labels"] - p["HEALTH_8_3"]["mean_labels"],
                                    p["BLIND_3"]["mean_labels"]),
        "mostly_blind_labels": m["BLIND_3"]["mean_labels"],
        "mostly_health4_labels": m["HEALTH_4_3"]["mean_labels"],
        "mostly_health8_labels": m["HEALTH_8_3"]["mean_labels"],
        "mostly_extra4": _frac(m["HEALTH_4_3"]["mean_labels"] - m["BLIND_3"]["mean_labels"],
                              m["BLIND_3"]["mean_labels"]),
        "mostly_extra8": _frac(m["HEALTH_8_3"]["mean_labels"] - m["BLIND_3"]["mean_labels"],
                              m["BLIND_3"]["mean_labels"]),
        "health8_detection_persistent": p["HEALTH_8_3"].get("detection_fraction"),
        "health4_detection_persistent": p["HEALTH_4_3"].get("detection_fraction"),
    }
    return out


def h1_rep(s):
    return (max(s["PERSISTENT"][a]["success_fraction"] or 0 for a in ARMS) <= 0.05
            and (s["economics"]["persistent_saving4"] or 0) >= 0.10)


def h2_rep(s):
    i = s["INTERMITTENT"]
    return ((i["BLIND_3"]["success_fraction"] or 0) - (i["SINGLE"]["success_fraction"] or 0) >= 0.30
            and (i["HEALTH_8_3"]["success_fraction"] or 0) >= (i["BLIND_3"]["success_fraction"] or 0) - 0.05)


def h3a_rep(s):
    return (s["economics"]["persistent_saving4"] or 0) >= 0.10


def h3b_rep(s):
    return (s["economics"]["mostly_extra4"] or 0) >= 0.03


def decide(s, rep):
    H = {
        "H1_persistent_fails_and_probes_help": (
            "SUPPORTED" if (h1_rep(s) and (s["economics"]["health4_detection_persistent"] or 0) >= 0.40)
            else "NOT_SUPPORTED"),
        "H2_retry_raises_availability": "SUPPORTED" if h2_rep(s) else "NOT_SUPPORTED",
        "H3a_probe_saves_when_capture_persists": "SUPPORTED" if h3a_rep(s) else "NOT_SUPPORTED",
        "H3b_probe_costs_when_capture_is_rare": "SUPPORTED" if h3b_rep(s) else "NOT_SUPPORTED",
        "H4_no_wrong_family": "SUPPORTED" if s["wrong_families"] == 0 else "NOT_SUPPORTED",
        "H5_attempts_bounded": "SUPPORTED" if (s["max_attempts"] or 0) <= MAX_ATTEMPTS else "NOT_SUPPORTED",
        "H6_replication": ("SUPPORTED" if (h1_rep(rep) and h2_rep(rep) and h3a_rep(rep)
                                           and h3b_rep(rep)) else "NOT_SUPPORTED"),
        "H7_external_review": "BLOCKED",
    }
    verdict = ("RETRY_POLICY_FRONTIER_MAPPED"
               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 / "E342R_MANIFEST.json").read_text())
    pre = json.loads((d / "E342R_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E342R_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E342R_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E342R_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E342R_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E342R_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E342R_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E342R_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e342r.manifest.v1")
    ck("evolution", man.get("evolution") == "E342-R" and rep.get("evolution") == "E342-R")
    ck("status", man.get("status") == S and rep.get("status") == S)
    ck("designation", pre.get("evolution") == "E342-R" and "E342-R" in (pre.get("designation") or ""))
    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 / "E342R_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 / "E342R_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_e342r_offline.py"))

    sets = rep["sets"]
    prow, rrow = sets["primary"]["rows"], sets["replication"]["rows"]
    allr = prow + rrow
    ck("cells", len(allr) == 24 and len(prow) == 12 and len(rrow) == 12)
    ck("cell schema", all(set(r) >= {"anchor", "regimes"} for r in allr))
    ck("regimes complete", all(all(reg in r["regimes"] for reg in REGIMES) for r in allr))
    ck("arms complete", all(all(arm in r["regimes"][reg] for reg in REGIMES for arm 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("no anomalies", sa["anomalies"] == 0)
    expected_finding = {
        "cells": sa["cells"], "anomalies": sa["anomalies"],
        "persistent_max_success": max(sa["PERSISTENT"][a]["success_fraction"] or 0 for a in ARMS),
        "persistent_blind_labels": sa["economics"]["persistent_blind_labels"],
        "persistent_health4_labels": sa["economics"]["persistent_health4_labels"],
        "persistent_health8_labels": sa["economics"]["persistent_health8_labels"],
        "persistent_saving4": sa["economics"]["persistent_saving4"],
        "persistent_saving8": sa["economics"]["persistent_saving8"],
        "health4_detection": sa["economics"]["health4_detection_persistent"],
        "health8_detection": sa["economics"]["health8_detection_persistent"],
        "intermittent_single": sa["INTERMITTENT"]["SINGLE"]["success_fraction"],
        "intermittent_blind3": sa["INTERMITTENT"]["BLIND_3"]["success_fraction"],
        "intermittent_health8": sa["INTERMITTENT"]["HEALTH_8_3"]["success_fraction"],
        "mostly_blind_labels": sa["economics"]["mostly_blind_labels"],
        "mostly_health4_labels": sa["economics"]["mostly_health4_labels"],
        "mostly_health8_labels": sa["economics"]["mostly_health8_labels"],
        "mostly_extra4": sa["economics"]["mostly_extra4"],
        "mostly_extra8": sa["economics"]["mostly_extra8"],
        "wrong_families": sa["wrong_families"],
    }
    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"] == "RETRY_POLICY_FRONTIER_MAPPED"))
    ck("external", ext["status"] == "NOT_OBTAINED")
    ck("deviations recorded", dev.get("deviations") == [])
    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())
