#!/usr/bin/env python3
"""E368-B 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 = {"E368B_MANIFEST.json", "E368B_SIGNED_BODY.json", "E368B_VERIFICATION_RESULTS.json",
      "E368B_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E368B_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 root_of(leaves):
    level = [leaf(x) for x in leaves]
    if not level:
        return sha(b"")
    while len(level) > 1:
        nxt = []
        for i in range(0, len(level), 2):
            nxt.append(node(level[i], level[i + 1]) if i + 1 < len(level) else level[i])
        level = nxt
    return level[0]


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 / "E368B_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E368B_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E368B_PREREGISTRATION_FREEZE.json").read_text())
    ext = json.loads((d / "E368B_EXTERNAL_REVIEW_STATUS.json").read_text())
    dev = json.loads((d / "E368B_DEVIATIONS.json").read_text())
    man = json.loads((d / "E368B_MANIFEST.json").read_text())
    checks = []

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

    ck("schema", rep["schema"] == "cain42.e368b.run_report.v1")
    ck("evolution", rep["evolution"] == "E368-B")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E368B_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])
    arms = {a["name"]: a for a in rep["arms"]}
    ck("four arms", set(arms) == {"batch4", "early", "down", "optout"})
    A, B, C, D = arms["batch4"], arms["early"], arms["down"], arms["optout"]

    def arm_proofs(arm):
        n = 0
        for row in arm["rows"]:
            if row.get("batch_root"):
                n += 1 if verify_inclusion(commitment(row), json.loads(row["batch_proof"]),
                                           row["batch_root"]) else 0
        return n

    roots_a = {r["batch_root"] for r in A["rows"] if r.get("batch_root")}
    roots_b = {r["batch_root"] for r in B["rows"] if r.get("batch_root")}
    proofs_a, proofs_b = arm_proofs(A), arm_proofs(B)
    ck("batch4 rows", A["accepted"] == 8 and len(A["rows"]) == 8 and A["anchors"] == 2)
    ck("batch4 two roots of four", len(roots_a) == 2
       and all(r["batch_size"] == 4 for r in A["rows"]))
    ck("batch4 proofs", proofs_a == 8)
    ck("early rows", B["accepted"] == 3 and B["anchors"] == 1 and len(roots_b) == 1)
    ck("early proofs", proofs_b == 3)
    ck("chains", chain_ok(A["rows"]) and chain_ok(B["rows"]) and chain_ok(D["rows"]))
    ck("anchor down", len(C["refused"]) == 4 and C["rows"] == []
       and all(str(x).startswith("ANCHOR_FAILED") for x in C["refused"]))
    opt_seqs = {r["anchor_sequence"] for r in D["rows"] if r["anchor_sequence"] is not None}
    ck("optout per entry", D["accepted"] == 2 and len(opt_seqs) == 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 arm in (A, B) for r in arm["results"] if not r.get("_refused"))
    ck("synchronous order", sync)

    receipts = [r for arm in (A, B, D) for r in arm["receipts"]]
    verdicts = [V.verify_receipt(r["receipt"], pin=r["receipt"]["configuration_hash"],
                                 digest=r["digest"])["verdict"] for r in receipts]
    distinct = {r["digest"] for r in receipts}
    ck("all receipts offline", len(verdicts) == 13 and all(v == "NOTARIZED" for v in verdicts))
    ck("five distinct commitments", len(distinct) == 5)

    H = rep["hypotheses"]
    rec = {
        "H1_batch_coverage": (A["accepted"] == 8 and len(roots_a) == 2 and A["anchors"] == 2
                              and chain_ok(A["rows"])),
        "H2_proofs_and_receipts": proofs_a + proofs_b == 11 and len(receipts) == 13
        and all(v == "NOTARIZED" for v in verdicts) and len(distinct) == 5,
        "H3_synchronous_order": sync,
        "H4_anchor_down_fails_closed": (len(C["refused"]) == 4 and C["rows"] == []
                                        and all(str(x).startswith("ANCHOR_FAILED") for x in C["refused"])),
        "H5_early_flush": B["accepted"] == 3 and len(roots_b) == 1 and proofs_b == 3
        and chain_ok(B["rows"]),
        "H6_optout_per_entry": D["accepted"] == 2 and len(opt_seqs) == 2 and chain_ok(D["rows"]),
    }
    for k, v in rec.items():
        ck("hypothesis " + k, H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("verdict", rep["verdict"] == "SYNCHRONOUS_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("deviations recorded", {"D1", "D2", "D3"} <= {x["id"] 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)
    all_seqs = {r["anchor_sequence"] for arm in (A, B, D) for r in arm["results"]
                if r.get("anchor_sequence") is not None}
    ck("live notarizations recomputed", len(all_seqs) == 5
       and rep["resources"]["live_notarizations"] == len(all_seqs))
    ck("limits", len(rep["limits"]) == 6)
    ck("anchor retry documented", "3 attempts" in pre["design"]["anchor_retry"])

    ck("headline matches", man["headline"]["verdict"] == rep["verdict"]
       and man["headline"]["accepted"] == 8 and man["headline"]["anchors"] == 2)
    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 / "E368B_PUBKEY.pem").read_bytes()) \
            if (d / "E368B_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 / "E368B_PUBLIC_SUMMARY.md").read_text())
    ck("no API key", "CAIN_API_KEY=" not in (d / "E368B_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())
