#!/usr/bin/env python3
"""E368-A 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 = ("p3_m2_ad", "p5_m3_ad")
MODES = ("INDEP", "COMMON_2", "COMMON_5", "COMMON_10")
SALTS = ("primary", "replication")
EX = {"E368A_MANIFEST.json", "E368A_SIGNED_BODY.json", "E368A_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E368A_OMEGA_SEAL.json",
      "E368A_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(rs, part):
    return {"n": len(rs),
            "verified": sum(1 for r in rs if r[part]["verified"]),
            "false_accept": sum(1 for r in rs if r[part]["false_accept"]),
            "claimed": sum(1 for r in rs if r[part].get("claimed")),
            "attribution_correct": sum(1 for r in rs if r[part].get("attribution_correct")),
            "mean_labels": round(sum(r[part]["labels"] for r in rs) / len(rs), 2) if rs else None}


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


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


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

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

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

    H = {
        "H1_independent_baseline_repairs": {
            "verdict": "SUPPORTED" if all(v(pn, "INDEP") >= 18 and fa(pn, "INDEP") == 0 for pn in PANELS) else "NOT_SUPPORTED",
            "detail": "the E367 A3_1 baseline repairs >=18/24 with 0 false accepts in both lost-quorum panels"},
        "H2_small_common_fault_hurts": {
            "verdict": "SUPPORTED" if all(v(pn, "COMMON_2") <= 12 for pn in PANELS) else "NOT_SUPPORTED",
            "detail": "a 2% common-mode fault reduces repair to <=12/24 in both lost-quorum panels"},
        "H3_common_fault_defeats": {
            "verdict": "SUPPORTED" if all(v(pn, "COMMON_5") <= 4 for pn in PANELS) else "NOT_SUPPORTED",
            "detail": "a 5% common-mode fault reduces repair to <=4/24 in both lost-quorum panels"},
        "H4_larger_fault_stays_defeated": {
            "verdict": "SUPPORTED" if all(v(pn, "COMMON_10") <= 2 for pn in PANELS) else "NOT_SUPPORTED",
            "detail": "a 10% common-mode fault reduces repair to <=2/24 in both lost-quorum panels"},
        "H5_attribution_is_not_the_problem": {
            "verdict": "SUPPORTED" if all(p[pn]["COMMON_5"]["repair"]["attribution_correct"] >= 18
                                          and v(pn, "COMMON_5") <= 4 for pn in PANELS) else "NOT_SUPPORTED",
            "detail": "under a 5% common fault attribution still identifies the data colluders in >=18/24, yet repair fails <=4/24: the surviving honest oracles are corrupted"},
        "H6_replication": {
            "verdict": ("SUPPORTED" if (q[PANELS[0]]["INDEP"]["repair"]["verified"] >= 9
                                        and q[PANELS[1]]["INDEP"]["repair"]["verified"] >= 9
                                        and q[PANELS[0]]["COMMON_5"]["repair"]["verified"] <= 2
                                        and q[PANELS[1]]["COMMON_5"]["repair"]["verified"] <= 2) else "NOT_SUPPORTED"),
            "detail": "the replication salt repeats H1 and H3 at >=9/12 or <=2/12"},
        "H7_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("COMMON_MODE_LIMIT_CONFIRMED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H7_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 / "E368A_MANIFEST.json").read_text())
    pre = json.loads((d / "E368A_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E368A_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E368A_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E368A_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E368A_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E368A_DEVIATIONS.json").read_text())
    raw = json.loads((d / "E368A_RAW_ROWS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e368a.manifest.v1" and rep.get("evolution") == "E368-A")
    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 / "E368A_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 / "E368A_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) == 192 and len(raw) == 192)
    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 / "E368A_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E368A_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"] == "a common-mode fault is invisible to every layer; stacked quorums do not buy independence")
    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())
