#!/usr/bin/env python3
"""Public record verifier — checks the Undertow track record from OUTSIDE.

    curl -O https://liquilens-undertow.com/verify_public.py
    python3 verify_public.py

No checkout. No keys. No dependencies beyond the Python standard library.
Nothing here trusts this project: every number it prints is recomputed from
published artifacts, and the chain terminates in Bitcoin rather than in our
word.

WHY THIS EXISTS. scripts/verify_record.py is the INSIDE verifier: it reads
data/_pit and proves the whole record to whoever holds it. Since 2026-07-27
the record is box-local and out of git, so a stranger who clones the repo and
runs that script gets "nothing to verify" and an exit code of ZERO — a clean
pass that proved nothing. A verifier that succeeds vacuously is worse than no
verifier, because it converts an absence into a green tick. This script is the
OUTSIDE half, and it fails loudly rather than quietly.

WHAT IT PROVES, and each check is independently meaningful:

  [heads]     every anchored head file still hashes to the sha256 recorded
              for it in anchors.json. An altered head is caught here.
  [binding]   the published record's ledger_root EQUALS the calls-stream head
              inside a Bitcoin-ATTESTED anchor. This is the load-bearing link:
              it ties the tally you are being sold to the exact chain state a
              public blockchain timestamped.
  [count]     the anchored head's call count equals the record's sealed count
              and the number of calls actually published. A deleted loser
              shows up as a mismatch.
  [tally]     hit / miss / void / pending recomputed from the published call
              outcomes, and compared to the advertised record. The hit rate is
              arithmetic you can redo, not a claim.
  [horizons]  every call's created_asof strictly precedes its horizon. A call
              written after its own deadline is caught here.
  [bitcoin]   reports the attesting block and prints the exact OpenTimestamps
              command to verify the proof yourself. If the `ots` client is on
              your PATH the proof is verified inline.

WHAT IT CANNOT PROVE, stated because a verifier that overstates its reach is
the thing it exists to prevent:

  * the per-record hash chain. Only the chain HEAD is published; the
    individual PIT records are not, so this script checks the head's integrity
    and its Bitcoin commitment, not each link beneath it. The inside verifier
    does that half.
  * the post-quantum signatures. The signing root is published, the signatures
    are not.
  * that a call was never written and discarded before publication. Nothing
    in a public record can show you a document that was never published.

THE STRONGEST CHECK IS THE ONE THAT NEEDS TIME. Run with --snapshot to save
today's anchored heads. Run again next month against the same snapshot: if any
previously-attested head has changed, the record was rewritten, and the script
fails. A single run proves internal consistency; two runs a month apart prove
nobody edited history. That is the property a screenshot cannot have.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request

DEFAULT_BASE = "https://api.seiche.info/undertow"
BASE = DEFAULT_BASE
TIMEOUT = 25
UA = "undertow-public-verifier/1.0 (+https://liquilens-undertow.com)"

OK, FAIL, SKIP = "PASS", "FAIL", "SKIP"


class Report:
    """Collects section verdicts. Exit status is derived from these, never
    from how far the script happened to get."""

    def __init__(self) -> None:
        self.rows: list[tuple[str, str, str]] = []

    def add(self, section: str, verdict: str, detail: str = "") -> None:
        self.rows.append((section, verdict, detail))
        mark = {OK: "PASS", FAIL: "FAIL", SKIP: "SKIP"}[verdict]
        print(f"  [{section:<9}] {mark}  {detail}")

    @property
    def failed(self) -> bool:
        return any(v == FAIL for _, v, _ in self.rows)

    @property
    def checked(self) -> int:
        return sum(1 for _, v, _ in self.rows if v != SKIP)


def fetch(path: str, binary: bool = False):
    url = path if path.startswith("http") else f"{BASE}/{path}"
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
        raw = r.read()
    return raw if binary else json.loads(raw.decode())


def sha256_hex(raw: bytes) -> str:
    return hashlib.sha256(raw).hexdigest()


# ---------------------------------------------------------------------------
def check_heads(rep: Report, anchors: list[dict]) -> dict[str, bytes]:
    """Every anchored head must still hash to its recorded sha256."""
    raws: dict[str, bytes] = {}
    for a in anchors:
        name = a.get("file")
        want = a.get("sha256")
        if not name or not want:
            rep.add("heads", FAIL, f"anchor entry missing file/sha256: {a}")
            continue
        try:
            raw = fetch(f"anchors/{name}", binary=True)
        except urllib.error.HTTPError as exc:
            rep.add("heads", FAIL, f"{name} unreachable (HTTP {exc.code})")
            continue
        except (urllib.error.URLError, TimeoutError, OSError) as exc:
            # a network fault is a graded verdict, never a traceback: this
            # script is the stranger-runnable half and must finish its report
            rep.add("heads", FAIL,
                    f"{name} unreachable ({getattr(exc, 'reason', None) or exc})"
                    f" — a head that cannot be fetched cannot be checked")
            continue
        got = sha256_hex(raw)
        if got != want:
            rep.add("heads", FAIL,
                    f"{name} sha256 {got[:16]} != recorded {want[:16]} "
                    f"— the head file changed after it was anchored")
            continue
        raws[name] = raw
        rep.add("heads", OK, f"{name} hashes to {got[:16]}… as recorded")
    return raws


def attested(anchors: list[dict]) -> dict | None:
    """The most recent anchor Bitcoin has actually confirmed. `pending` means
    the proof is submitted but not yet in a block, which is not attestation."""
    conf = [a for a in anchors if a.get("bitcoin_block")]
    return sorted(conf, key=lambda a: a.get("generated_at", ""))[-1] if conf else None


def check_binding(rep: Report, anchor: dict, head: dict, record: dict) -> None:
    """The record's ledger_root must equal the calls head Bitcoin attested."""
    calls = (head.get("streams") or {}).get("calls") or {}
    head_calls = calls.get("head") if isinstance(calls, dict) else calls
    root = record.get("ledger_root")
    if not head_calls or not root:
        rep.add("binding", FAIL, "missing calls head or ledger_root")
        return
    if head_calls != root:
        rep.add("binding", FAIL,
                f"published ledger_root {root[:16]}… != attested calls head "
                f"{head_calls[:16]}… — the record shown is NOT the chain "
                f"Bitcoin timestamped")
        return
    rep.add("binding", OK,
            f"ledger_root {root[:16]}… is the calls head inside the anchor "
            f"attested in Bitcoin block {anchor['bitcoin_block']}")


def check_count(rep: Report, head: dict, record: dict) -> None:
    calls = (head.get("streams") or {}).get("calls") or {}
    n_head = calls.get("n") if isinstance(calls, dict) else None
    n_rec = record.get("n_sealed")
    n_pub = len(record.get("recent") or [])
    if n_head is None:
        rep.add("count", SKIP, "anchored head carries no call count")
        return
    if not (n_head == n_rec == n_pub):
        rep.add("count", FAIL,
                f"anchored head says {n_head} calls, record says {n_rec}, "
                f"{n_pub} published — a call is missing from one of them")
        return
    rep.add("count", OK, f"{n_head} calls in the anchored chain, the record "
                         f"and the published list alike")


def check_tally(rep: Report, record: dict) -> None:
    """Recompute the advertised hit rate from the published outcomes."""
    calls = record.get("recent") or []
    if not calls:
        rep.add("tally", FAIL, "no calls published — nothing to recompute")
        return
    per: dict[str, dict[str, int]] = {}
    for c in calls:
        a = per.setdefault(c.get("author", "?"),
                           {"hit": 0, "miss": 0, "void": 0, "pending": 0})
        o = (c.get("outcome") or "PENDING").upper()
        key = {"HIT": "hit", "MISS": "miss", "VOID": "void"}.get(o, "pending")
        a[key] += 1

    claimed = {a.get("author"): a for a in
               ((record.get("record") or {}).get("authors") or [])}
    if not claimed:
        rep.add("tally", FAIL, "record advertises no author tally")
        return
    for author, mine in sorted(per.items()):
        theirs = claimed.get(author)
        if theirs is None:
            rep.add("tally", FAIL, f"author {author!r} published but absent "
                                   f"from the advertised record")
            continue
        decided = mine["hit"] + mine["miss"]
        rate = round(mine["hit"] / decided, 4) if decided else None
        bad = []
        for k in ("hit", "miss", "void", "pending"):
            if theirs.get(k) != mine[k]:
                bad.append(f"{k} advertised {theirs.get(k)} vs published {mine[k]}")
        if theirs.get("decided") != decided:
            bad.append(f"decided advertised {theirs.get('decided')} vs {decided}")
        if rate is not None and theirs.get("hit_rate") is not None:
            if abs(float(theirs["hit_rate"]) - rate) > 5e-4:
                bad.append(f"hit_rate advertised {theirs['hit_rate']} vs "
                           f"recomputed {rate}")
        if bad:
            rep.add("tally", FAIL, f"{author}: " + "; ".join(bad))
        else:
            rep.add("tally", OK,
                    f"{author}: {mine['hit']} hit / {mine['miss']} miss"
                    + (f" / {mine['void']} void" if mine["void"] else "")
                    + (f" / {mine['pending']} pending" if mine["pending"] else "")
                    + (f" = {rate}" if rate is not None else "")
                    + " — recomputed from the published calls")


def check_horizons(rep: Report, record: dict) -> None:
    """A call must be written before its own deadline."""
    bad = []
    for c in record.get("recent") or []:
        made, hz = c.get("created_asof"), c.get("horizon")
        if not made or not hz:
            bad.append(f"{c.get('call_label','?')}: missing created_asof/horizon")
        elif made >= hz:
            bad.append(f"{c.get('call_label','?')}: created {made} is not "
                       f"before horizon {hz}")
    if bad:
        rep.add("horizons", FAIL, "; ".join(bad))
    else:
        n = len(record.get("recent") or [])
        rep.add("horizons", OK,
                f"all {n} calls were written before their own horizon")


def check_bitcoin(rep: Report, anchor: dict) -> None:
    """Bitcoin attestation, in two honest tiers.

    TIER 1, no Bitcoin node required. `ots info` reads the proof itself and
    reveals (a) the file sha256 the proof commits to and (b) every
    BitcoinBlockHeaderAttestation block height inside it. If the proof commits
    to the head file we fetched, and names the block anchors.json claims, then
    the claim is internally consistent and you can read the block's timestamp
    off any public explorer.

    TIER 2 needs a node. Full `ots verify` additionally checks that the block's
    merkle root really is on the Bitcoin chain. Without a node it CANNOT run,
    and an inability to check here is reported as exactly that — never as a
    failed proof. Conflating "I could not check" with "it is false" is the
    error this whole verifier exists to avoid.
    """
    name = anchor.get("file")
    claimed = anchor.get("bitcoin_block")
    head_url = f"{BASE}/anchors/{name}"
    proof_url = f"{head_url}.ots"
    explorer = f"https://mempool.space/block/{claimed}" if claimed else ""

    ots = shutil.which("ots")
    if not ots:
        rep.add("bitcoin", SKIP,
                f"claims Bitcoin block {claimed}; no `ots` client here, so the "
                f"proof was NOT read. To check it yourself:\n"
                f"                 pip install opentimestamps-client\n"
                f"                 curl -O {head_url} && curl -O {proof_url}\n"
                f"                 ots info {name}.ots      # no node needed\n"
                f"                 ots verify {name}.ots    # needs a node")
        return

    tmp = tempfile.mkdtemp(prefix="undertow-ots-")
    try:
        # Fetch failures are labelled as fetch failures. They used to fall
        # into the generic handler below and read "ots could not run", which
        # blames the reader's tooling for the mirror's absence.
        try:
            for url, fn in ((head_url, name), (proof_url, name + ".ots")):
                with open(os.path.join(tmp, fn), "wb") as fh:
                    fh.write(fetch(url, binary=True))
        except urllib.error.HTTPError as exc:
            rep.add("bitcoin", FAIL,
                    f"{getattr(exc, 'url', None) or name} unreachable "
                    f"(HTTP {exc.code}) — anchors.json names a proof the "
                    f"mirror does not serve")
            return
        except (urllib.error.URLError, TimeoutError, OSError) as exc:
            rep.add("bitcoin", FAIL,
                    f"head/proof could not be fetched "
                    f"({getattr(exc, 'reason', None) or exc}) — a fetch "
                    f"failure, not an ots failure; the proof was NOT read")
            return

        info = subprocess.run([ots, "info", name + ".ots"], cwd=tmp,
                              capture_output=True, text=True, timeout=120)
        text = info.stdout + info.stderr

        m = re.search(r"File sha256 hash:\s*([0-9a-f]{64})", text)
        proof_file_hash = m.group(1) if m else None
        blocks = sorted({int(b) for b in
                         re.findall(r"BitcoinBlockHeaderAttestation\((\d+)\)", text)})

        if not proof_file_hash:
            rep.add("bitcoin", FAIL, "ots info did not report a file hash")
            return
        if proof_file_hash != anchor.get("sha256"):
            rep.add("bitcoin", FAIL,
                    f"the proof commits to {proof_file_hash[:16]}… but the "
                    f"anchored head is {str(anchor.get('sha256'))[:16]}… — the "
                    f"proof is for a DIFFERENT file")
            return
        if not blocks:
            rep.add("bitcoin", SKIP,
                    "the proof carries only pending calendar attestations; it "
                    "is submitted but not yet in a Bitcoin block")
            return
        if claimed is not None and claimed not in blocks:
            rep.add("bitcoin", FAIL,
                    f"anchors.json claims block {claimed} but the proof "
                    f"attests {blocks} — the claimed block is not in the proof")
            return

        rep.add("bitcoin", OK,
                f"the proof commits to this exact head file and attests "
                f"Bitcoin block(s) {blocks}; earliest {blocks[0]}. "
                f"Read its timestamp at https://mempool.space/block/{blocks[0]}")

        ver = subprocess.run([ots, "verify", name + ".ots"], cwd=tmp,
                             capture_output=True, text=True, timeout=180)
        vt = (ver.stdout + ver.stderr).strip()
        if "Success!" in vt or "attests existence" in vt:
            rep.add("bitcoin+", OK,
                    "full ots verify confirmed the proof against a Bitcoin node")
        elif "Could not connect to Bitcoin node" in vt or "Cookie file" in vt:
            rep.add("bitcoin+", SKIP,
                    "full merkle verification needs a local Bitcoin node, which "
                    "is not available here. This is an inability to check, NOT "
                    "a failed proof — tier 1 above already passed offline.")
        else:
            rep.add("bitcoin+", FAIL, f"ots verify rejected the proof: {vt[:200]}")
    except Exception as exc:                                # noqa: BLE001
        rep.add("bitcoin", SKIP, f"ots could not run: {exc}")
    finally:
        shutil.rmtree(tmp, ignore_errors=True)


def check_snapshot(rep: Report, path: str, anchors: list[dict],
                   raws: dict[str, bytes]) -> None:
    """The check that needs time: has any previously-seen head changed?"""
    now = {a["file"]: a["sha256"] for a in anchors
           if a.get("file") and a.get("sha256")}
    if not os.path.exists(path):
        with open(path, "w") as fh:
            json.dump(now, fh, indent=1, sort_keys=True)
        rep.add("history", SKIP,
                f"snapshot written to {path} ({len(now)} heads). Re-run in a "
                f"week or a month: if a head recorded today has changed by "
                f"then, history was rewritten and this section will FAIL.")
        return
    with open(path) as fh:
        before = json.load(fh)
    changed = [f for f, h in before.items() if f in now and now[f] != h]
    if changed:
        rep.add("history", FAIL,
                f"{len(changed)} previously-anchored head(s) CHANGED since "
                f"the snapshot: {', '.join(changed)} — the record was rewritten")
        return
    kept = [f for f in before if f in now]
    dropped = [f for f in before if f not in now]
    detail = f"{len(kept)} head(s) unchanged since {path}"
    if dropped:
        detail += (f"; {len(dropped)} no longer listed "
                   f"({', '.join(dropped[:3])}) — rotation is expected, "
                   f"but a head that vanishes cannot be re-checked")
    rep.add("history", OK, detail)
    with open(path, "w") as fh:
        json.dump({**before, **now}, fh, indent=1, sort_keys=True)


# ---------------------------------------------------------------------------
def main(argv: list[str] | None = None) -> int:
    global BASE
    ap = argparse.ArgumentParser(
        description="Verify the Undertow published track record from outside.")
    ap.add_argument("--base", default=DEFAULT_BASE,
                    help="public mirror base URL")
    ap.add_argument("--snapshot", metavar="FILE",
                    help="path to a local snapshot of anchored heads; enables "
                         "the rewrite check across runs")
    args = ap.parse_args(argv)
    BASE = args.base.rstrip("/")

    print(f"Undertow public record verifier — {BASE}")
    print("nothing below trusts this project; every figure is recomputed\n")
    rep = Report()

    try:
        anchors = (fetch("anchors.json") or {}).get("anchors") or []
        record = fetch("sealed_calls.json")
    except Exception as exc:                                # noqa: BLE001
        print(f"  [fetch    ] FAIL  cannot reach the public mirror: {exc}")
        print("\nVERDICT: FAIL — the record could not be fetched.")
        return 2

    if not anchors:
        rep.add("heads", FAIL, "anchors.json lists no anchors")
    else:
        raws = check_heads(rep, anchors)

    a = attested(anchors) if anchors else None
    if a is None:
        rep.add("binding", FAIL,
                "no anchor is confirmed in a Bitcoin block yet (all pending) "
                "— the record is not yet independently timestamped")
    else:
        head = json.loads(raws[a["file"]].decode()) if a["file"] in raws else None
        if head is None:
            rep.add("binding", FAIL, "attested head file could not be read")
        else:
            check_binding(rep, a, head, record)
            check_count(rep, head, record)

    check_tally(rep, record)
    check_horizons(rep, record)
    if a is not None:
        check_bitcoin(rep, a)
    if args.snapshot and anchors:
        check_snapshot(rep, args.snapshot, anchors, {})

    print()
    if rep.checked == 0:
        print("VERDICT: FAIL — nothing could be verified. An absence of "
              "evidence is not a pass.")
        return 2
    if rep.failed:
        print(f"VERDICT: FAIL — {sum(1 for _, v, _ in rep.rows if v == FAIL)} "
              f"section(s) failed.")
        return 1
    print(f"VERDICT: PASS — {rep.checked} section(s) verified.")
    print("\nWhat this does NOT prove: the per-record chain beneath the "
          "published head, the post-quantum signatures, or that a call was "
          "never written and discarded before publication. Run with "
          "--snapshot and come back later; a head that changes is the one "
          "thing a rewritten record cannot hide.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
