#!/usr/bin/env python3
"""E373-D standalone offline verifier (stdlib + cryptography + the published QaaS verifier)."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
SCHEMA = "cain42.jit.batch_statement.v1"
EX = {"E373D_MANIFEST.json", "E373D_SIGNED_BODY.json", "E373D_VERIFICATION_RESULTS.json",
      "E373D_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E373D_OMEGA_SEAL.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 leaf(h):
    return sha(("leaf|" + h).encode())


def node(l, r):
    return sha(("node|" + l + r).encode())


def verify_inclusion(commitment, path, root):
    h = leaf(commitment)
    for side, s in path:
        h = node(s, h) if side == "L" else node(h, s)
    return h == root


def commitment(row):
    doc = {"schema": SCHEMA, "statement_hash": row["statement_hash"],
           "principal": row["principal"], "revocation_epoch": float(row["revocation_epoch"]),
           "not_after": float(row["not_after"]), "approvers": json.loads(row["approvers"]),
           "reason": row["reason"], "ticket": row["ticket"],
           "policy_hash": row["policy_hash"] or ""}
    return sha(canon(doc))


def chain_ok(rows):
    prev = ""
    for row in rows:
        base = "|".join([prev, row["statement_hash"], row["principal"],
                         repr(float(row["revocation_epoch"])), repr(float(row["not_after"])),
                         row["approvers"], row["reason"], row["ticket"]])
        payload = ("v2|" + base + "|" + row["policy_hash"]) if row["policy_hash"] else base
        if sha(payload.encode()) != row["entry_hash"] or row["prev_hash"] != prev:
            return False
        prev = row["entry_hash"]
    return True


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 main() -> int:
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    sys.path.insert(0, str(d))
    import verify_qaas_receipt as V
    rep = json.loads((d / "E373D_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E373D_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E373D_PREREGISTRATION_FREEZE.json").read_text())
    ext = json.loads((d / "E373D_EXTERNAL_REVIEW_STATUS.json").read_text())
    dev = json.loads((d / "E373D_DEVIATIONS.json").read_text())
    man = json.loads((d / "E373D_MANIFEST.json").read_text())
    checks = []

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

    ck("schema", rep["schema"] == "cain42.e373d.run_report.v1")
    ck("evolution", rep["evolution"] == "E373-D")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E373D_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])
    arms = {a["name"]: a for a in rep["arms"]}
    ck("three arms", set(arms) == {"cross4", "down", "optout"})
    A, C, D = arms["cross4"], arms["down"], arms["optout"]

    accepted = [r for r in A["results"] if not r.get("_refused")]
    batches = A["queue"]["batches"]
    pids = {p.split(":")[0] for p in A["queue"]["processes"]}
    ck("cross accepted", len(accepted) == 8 and len(A["rows"]) == 8)
    ck("two batches of four", len(batches) == 2 and all(b["n"] == 4 for b in batches))
    ck("two processes", len(pids) >= 2)
    ck("cross chain", chain_ok(A["rows"]))
    proofs = 0
    for row in A["rows"]:
        if row.get("batch_root"):
            proofs += 1 if verify_inclusion(commitment(row), json.loads(row["batch_proof"]),
                                            row["batch_root"]) else 0
    ck("eight proofs", proofs == 8)
    receipts = [r for r in accepted if r.get("anchor_receipt")]
    vals = [V.verify_receipt(r["anchor_receipt"], pin=r["anchor_receipt"]["configuration_hash"],
                             digest=r["batch_root"])["verdict"] for r in receipts]
    ck("eight receipts offline", len(vals) == 8 and all(v == "NOTARIZED" for v in vals))
    ck("two distinct roots", len({r["batch_root"] for r in receipts}) == 2)
    sync = all(r.get("anchor_sequence") is not None and r.get("anchor_finished_at")
               and r.get("accepted_at") and r["anchor_finished_at"] <= r["accepted_at"]
               for r in accepted)
    ck("synchronous order", sync)
    ck("down fails closed", len(C["rows"]) == 0 and C["queue"]["done"] == 0
       and C["queue"]["error"] == 4
       and all(str(r.get("_refused", "")).startswith("ANCHOR_FAILED") for r in C["results"]))
    opt = [r for r in D["results"] if not r.get("_refused")]
    opt_seqs = {r["anchor_sequence"] for r in D["rows"] if r["anchor_sequence"] is not None}
    ck("optout per entry", len(opt) == 2 and len(opt_seqs) == 2 and chain_ok(D["rows"]))
    ck("no duplicate commitment", len({r["statement_hash"] for r in A["rows"]}) == 8)

    H = rep["hypotheses"]
    rec = {
        "H1_cross_process_batches": (len(accepted) == 8 and len(batches) == 2
                                     and all(b["n"] == 4 for b in batches) and chain_ok(A["rows"])),
        "H2_proofs_and_receipts": (proofs == 8 and len(vals) == 8
                                   and all(v == "NOTARIZED" for v in vals)
                                   and len({r["batch_root"] for r in receipts}) == 2),
        "H3_cross_process_chain_and_order": chain_ok(A["rows"]) and sync,
        "H4_anchor_down_fails_closed": (len(C["rows"]) == 0 and C["queue"]["done"] == 0
                                        and C["queue"]["error"] == 4
                                        and all(str(r.get("_refused", "")).startswith("ANCHOR_FAILED")
                                                for r in C["results"])),
        "H5_optout_per_entry": len(opt) == 2 and len(opt_seqs) == 2 and chain_ok(D["rows"]),
        "H6_no_duplicate_commitment": len({r["statement_hash"] for r in A["rows"]}) == 8,
    }
    for k, v in rec.items():
        ck("hypothesis " + k, H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("verdict", rep["verdict"] == "CROSS_PROCESS_BATCH_ANCHOR_SUPPORTED"
       and all(H[k]["verdict"] == "SUPPORTED" for k in H if not k.startswith("H7")))
    ck("external blocked", H["H7_external_review"]["verdict"] == "BLOCKED"
       and ext["status"] == "NOT_OBTAINED")
    ck("deviation D1 recorded", any(x.get("id") == "D1" for x in dev["deviations"]))
    ck("model calls zero", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0 and rep["resources"]["hosts"] == 1)
    ck("live notarizations", rep["resources"]["live_notarizations"] == 4)
    ck("limits", len(rep["limits"]) == 6)
    ck("queue mode documented", "BEGIN IMMEDIATE" in pre["design"]["queue"])

    ck("headline matches", man["headline"]["verdict"] == rep["verdict"]
       and man["headline"]["accepted"] == 8)
    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 not p.name.endswith(("-wal", "-shm")))
    ck("manifest files", man["files"] == {str(p.relative_to(d)): sha(p.read_bytes())
                                         for p in files})
    ck("merkle root", man["merkle_root"] == merkle(files))
    try:
        from cryptography.hazmat.primitives import serialization
        pk = serialization.load_pem_public_key((d / "E373D_PUBKEY.pem").read_bytes()) \
            if (d / "E373D_PUBKEY.pem").exists() else None
        if pk is None:
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
            pk = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
        pk.verify(bytes.fromhex(man["signature"]),
                  canon({k: v for k, v in man.items() if k != "signature"}))
        ck("manifest signature", True)
    except Exception as e:  # noqa: BLE001
        ck(f"manifest signature ({type(e).__name__})", False)

    ck("receipt verifiers shipped", (d / "verify_qaas_receipt.py").exists()
       and (d / "verify_pbft_qc_bundle.py").exists())
    ck("status in public summary", S in (d / "E373D_PUBLIC_SUMMARY.md").read_text())
    ck("no API key", "CAIN_API_KEY=" not in (d / "E373D_RUN_REPORT.json").read_text())

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