#!/usr/bin/env python3
"""E383-M standalone verifier (stdlib + cryptography): recomputes the hypotheses and verdict from probes."""
from __future__ import annotations

import hashlib, json, sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX = {"E383-M_MANIFEST.json", "E383-M_SIGNED_BODY.json", "E383-M_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E383-M_OMEGA_SEAL.json",
      "E383-M_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 decide(probes):
    by = {p["probe"]: p for p in probes}
    h1, h2, h3 = by["H1_durability"], by["H2_replay"], by["H3_crash_atomicity"]
    h4, h5, h6 = by["H4_adversarial_isolation"], by["H5_revocation_persists"], by["H6_conflict_visibility"]
    H = {
        "H1_durability": {"verdict": "SUPPORTED" if h1["ok"] and h1["chain"] and h1["counts"] == [120, 120, 120] else "NOT_SUPPORTED",
                          "detail": "records, chain and contiguous sequence survive 3 process restarts"},
        "H2_replay": {"verdict": "SUPPORTED" if h2["ok"] and h2["refused"] == h2["attempts"] == 120 else "NOT_SUPPORTED",
                      "detail": "every replayed nonce is refused, including across a restart"},
        "H3_crash_atomicity": {"verdict": "SUPPORTED" if h3["ok"] and h3["after_before"] == h3["before"] and h3["after_after"] == h3["before"] + 1 else "NOT_SUPPORTED",
                               "detail": "a kill before commit leaves no partial row; a kill after commit leaves one complete row and a valid chain"},
        "H4_adversarial_isolation": {"verdict": "SUPPORTED" if h4["ok"] and h4["leaks"] == 0 and h4["probes"] == 1000 else "NOT_SUPPORTED",
                                     "detail": "injection-shaped, wildcard, case, homoglyph and traversal tenant probes return no record"},
        "H5_revocation_persists": {"verdict": "SUPPORTED" if h5["ok"] and h5["refused"] == 20 else "NOT_SUPPORTED",
                                   "detail": "a revoked agent stays revoked after a restart"},
        "H6_conflict_visibility": {"verdict": "SUPPORTED" if h6["ok"] and h6["conflicted"] == 20 and h6["silent_overwrites"] == 0 else "NOT_SUPPORTED",
                                   "detail": "every conflicting claim is visible and grouped; no silent overwrite; memory grants no authority"},
        "H7_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("DURABLE_GOVERNED_MEMORY_VERIFIED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H7_external_review") else "NOT_SUPPORTED")
    return 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 / "E383-M_MANIFEST.json").read_text())
    pre = json.loads((d / "E383-M_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E383-M_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E383-M_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E383-M_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E383-M_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E383-M_DEVIATIONS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e383m.manifest.v1" and rep.get("evolution") == "E383-M")
    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 / "E383-M_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 / "E383-M_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()))
    probes = rep["probes"]
    ck("probes", len(probes) >= 6 and {p["probe"] for p in probes} >= {"H1_durability", "H2_replay", "H3_crash_atomicity",
                                                                      "H4_adversarial_isolation", "H5_revocation_persists", "H6_conflict_visibility"})
    H, verdict = decide(probes)
    ck("verdict", verdict == rep["verdict"] and all(H[k]["verdict"] == rep["hypotheses"][k]["verdict"] for k in H))
    ch = [json.loads(l) for l in (d / "checkpoints/probe_chain.jsonl").read_text().splitlines()]
    prev = "0" * 64
    rec = []
    for r in probes:
        hh = sha((prev + sha(canon(r))).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/probe_chain.json").read_text())
    ck("chain file", cp["count"] == len(ch) and cp["head"] == rec[-1])
    ck("finding", rep["finding"]["headline"]["records"] == 120 and rep["finding"]["headline"]["replay_refused"] == 120
       and rep["finding"]["law"].startswith("a governed shared memory can survive"))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E383-M_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E383-M_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("deviations", isinstance(dev.get("deviations"), list))
    ck("resources", rep["resources"]["model_calls"] == 0)
    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())
