#!/usr/bin/env python3
"""E374-L 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 = {"E374L_MANIFEST.json", "E374L_SIGNED_BODY.json", "E374L_VERIFICATION_RESULTS.json",
      "E374L_TAMPER_RESULTS.json", "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E374L_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 / "E374L_RUN_REPORT.json").read_text())
    pre = json.loads((d / "E374L_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E374L_PREREGISTRATION_FREEZE.json").read_text())
    ext = json.loads((d / "E374L_EXTERNAL_REVIEW_STATUS.json").read_text())
    dev = json.loads((d / "E374L_DEVIATIONS.json").read_text())
    q = json.loads((d / "E374L_QUEUE_ROWS.json").read_text())["arms"]
    man = json.loads((d / "E374L_MANIFEST.json").read_text())
    checks = []

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

    ck("schema", rep["schema"] == "cain42.e374l.run_report.v1")
    ck("evolution", rep["evolution"] == "E374-L")
    ck("status line", rep["status"] == S)
    ck("prereg hash", sha((d / "E374L_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])
    arms = {a["name"]: a for a in rep["arms"]}
    ck("three arms", set(arms) == {"reclaim", "anchor_crash", "lease_hold"})

    def check_arm(name, expect_reclaimed):
        a = arms[name]
        accepted = [r for r in a["results"] if not r.get("_refused")]
        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
        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]
        qr = q[name]
        done = [x for x in qr if x["state"] == "done"]
        reclaimed = sum(1 for x in done if int(x.get("attempts") or 0) > 1)
        max_att = max([int(x.get("attempts") or 0) for x in done], default=0)
        batches = {x["batch_id"] for x in done}
        ok = (a["accepted"] == 8 and len(a["rows"]) == 8 and a["roots"] == 2
              and proofs == 8 and a["chain"] and chain_ok(a["rows"]) and len(receipts) == 8
              and all(v == "NOTARIZED" for v in vals)
              and len({r["statement_hash"] for r in a["rows"]}) == 8
              and len(done) == 8 and len(batches) == 2
              and reclaimed == expect_reclaimed
              and a.get("reclaimed_rows") == reclaimed
              and a.get("max_attempts") == max_att
              and a.get("max_attempts") == (2 if expect_reclaimed else 1))
        ck(f"arm {name}", ok)
        return {"proofs": proofs, "reclaimed": reclaimed, "max": max_att}

    rr = check_arm("reclaim", 4)
    rx = check_arm("anchor_crash", 4)
    rh = check_arm("lease_hold", 0)

    H = rep["hypotheses"]
    rec = {
        "H1_claim_reclaim": (arms["reclaim"]["accepted"] == 8 and arms["reclaim"]["roots"] == 2
                             and rr["reclaimed"] == 4 and rr["max"] == 2),
        "H2_anchor_crash_reclaim": (arms["anchor_crash"]["accepted"] == 8
                                    and arms["anchor_crash"]["roots"] == 2
                                    and rx["reclaimed"] == 4 and rx["max"] == 2
                                    and arms["anchor_crash"]["receipts"]["verified"] == 8),
        "H3_lease_hold": (arms["lease_hold"]["accepted"] == 8
                          and arms["lease_hold"]["roots"] == 2 and rh["reclaimed"] == 0
                          and rh["max"] == 1),
        "H4_no_second_commitment": all(arms[n]["roots"] == 2 and len(q[n]) == 8
                                       for n in ("reclaim", "anchor_crash", "lease_hold")),
        "H5_attempts_bounded": (rr["max"] == 2 and rx["max"] == 2 and rh["max"] == 1),
        "H6_receipts_offline": all(arms[n]["receipts"]["verified"] == 8
                                   for n in ("reclaim", "anchor_crash", "lease_hold")),
    }
    for k, v in rec.items():
        ck("hypothesis " + k, H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ck("verdict", rep["verdict"] == "LEASED_QUEUE_CRASH_RECOVERY_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"] == 6)
    ck("limits", len(rep["limits"]) == 6)
    ck("fault hook documented", "CAIN_JIT_BATCH_FAULT" in pre["design"]["fault"])

    ck("headline matches", man["headline"]["verdict"] == rep["verdict"])
    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 / "E374L_PUBKEY.pem").read_bytes()) \
            if (d / "E374L_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 / "E374L_PUBLIC_SUMMARY.md").read_text())
    ck("no API key", "CAIN_API_KEY=" not in (d / "E374L_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())
