#!/usr/bin/env python3
"""E362-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"
EX = {"E362B_MANIFEST.json", "E362B_SIGNED_BODY.json", "E362B_VERIFICATION_RESULTS.json",
      "E362B_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E362B_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 merkle_root(leaves):
    level = [leaf(x) for x in leaves]
    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(entry_hash, path, root):
    h = leaf(entry_hash)
    for side, s in path:
        h = node(s, h) if side == "L" else node(h, s)
    return h == root


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 / "E362B_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E362B_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E362B_PREREGISTRATION_FREEZE.json").read_text())
    ext = json.loads((d / "E362B_EXTERNAL_REVIEW_STATUS.json").read_text())
    dev = json.loads((d / "E362B_DEVIATIONS.json").read_text())
    led = json.loads((d / "E362B_LEDGER.json").read_text())
    man = json.loads((d / "E362B_MANIFEST.json").read_text())
    checks = []

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

    ck("schema", rep["schema"] == "cain42.e362b.run_report.v1")
    ck("evolution", rep["evolution"] == "E362-B")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E362B_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])

    batches = rep["batches"]
    ck("two batches", len(batches) == 2)
    ck("eight entries", rep["entries"] == 8
       and sum(len(b["entries"]) for b in batches) == 8)

    roots_ok, proofs_ok, receipts_ok, seq_ok = True, True, True, True
    entries_flat = []
    for b in batches:
        chunk = b["entries"]
        entries_flat.extend(chunk)
        root = merkle_root(chunk)
        roots_ok &= (root == b["root"])
        proofs_ok &= (len(b.get("proofs", [])) == len(chunk))
        for j, p in enumerate(b.get("proofs", [])):
            proofs_ok &= (p["entry_hash"] == chunk[j]
                          and p["path"] == [list(x) for x in p["path"]]
                          and verify_inclusion(chunk[j], p["path"], b["root"]))
        if b.get("receipt"):
            v = V.verify_receipt(b["receipt"], pin=b["receipt"]["configuration_hash"],
                                 digest=b["root"])["verdict"]
            receipts_ok &= (v == "NOTARIZED")
        else:
            receipts_ok = False
        seq_ok &= bool(b.get("sequence")) and b.get("http") == 200
    ck("batch roots recomputed", roots_ok)
    ck("all inclusion proofs verify", proofs_ok and rep["batches"][0]["proofs"][0]["verifies"])
    ck("receipts verify offline", receipts_ok)
    ck("anchor sequences", seq_ok and rep["hypotheses"]["H1_batched_anchors"]["anchors"] == 2)
    ck("eight distinct entries", len(set(entries_flat)) == 8)

    # tamper: the recorded proof must NOT verify for a flipped entry hash
    h0 = batches[0]["entries"][0]
    bad = h0[:-1] + ("0" if h0[-1] != "0" else "1")
    ck("tampered entry rejected", verify_inclusion(bad, batches[0]["proofs"][0]["path"],
                                                   batches[0]["root"]) is False and rep["tamper_ok"])

    down = rep["down"]
    ck("anchor down fails closed", down["http"] != 200
       and str(down.get("error", "")).startswith("URLError"))

    prev = ""
    chain_ok = len(led) == 8
    for row in led:
        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
        chain_ok &= (sha(payload.encode()) == row["entry_hash"] and row["prev_hash"] == prev)
        prev = row["entry_hash"]
    ck("ledger chain", chain_ok)
    ck("batches cover the ledger in order", entries_flat == [r["entry_hash"] for r in led])
    ck("no API key in report", "CAIN_API_KEY=" not in (d / "E362B_RUN_REPORT.json").read_text()
       and "cain_free_" not in (d / "E362B_RUN_REPORT.json").read_text())

    H = rep["hypotheses"]
    rec = {
        "H1_batched_anchors": roots_ok and receipts_ok and seq_ok,
        "H2_inclusion_proofs": proofs_ok,
        "H3_tamper_rejected": verify_inclusion(bad, batches[0]["proofs"][0]["path"],
                                               batches[0]["root"]) is False,
        "H4_anchor_down_writes_nothing": down["http"] != 200
        and str(down.get("error", "")).startswith("URLError"),
        "H5_anchor_call_reduction": rep["entries"] == 8
        and rep["hypotheses"]["H1_batched_anchors"]["anchors"] == 2,
    }
    ck("hypotheses recomputed", all(H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED")
                                    for k, v in rec.items()))
    ck("verdict", rep["verdict"] == "BATCHED_ANCHOR_PROOFS"
       and all(H[k]["verdict"] == "SUPPORTED" for k in H if not k.startswith("H6")))
    ck("external blocked", H["H6_external_review"]["verdict"] == "BLOCKED"
       and ext["status"] == "NOT_OBTAINED")
    ck("deviations", isinstance(dev.get("deviations"), list))
    ck("model calls zero", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0)
    ck("limits", len(rep["limits"]) >= 5)

    seqs = [b.get("sequence") for b in batches]
    ck("headline matches", man["headline"].get("sequences") == seqs
       and man["headline"]["verdict"] == rep["verdict"]
       and man["headline"].get("entries") == 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 / "E362B_PUBKEY.pem").read_bytes()) \
            if (d / "E362B_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 / "E362B_PUBLIC_SUMMARY.md").read_text())

    bad_checks = [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_checks)}/{len(checks)} checks passed")
    return 0 if not bad_checks else 1


if __name__ == "__main__":
    sys.exit(main())
