#!/usr/bin/env python3
"""spend_gate.py — refuse a paid render unless the contract was reviewed first,
and keep a ledger of what was actually spent.

This exists because of a real, expensive mistake: three hero clips were rendered
at 1260 credits each BEFORE the preview contract was built, and one of them was
made worthless minutes later when the style set it was rendered against changed.
That is 1260 credits burned for nothing, and the rule that would have caught it
("preview IS the contract; review before you spend") was being kept in the
agent's head instead of in the tool. Rules in heads do not hold across a long
session. This one is in the tool.

A render is allowed only when ALL of these hold:

  1. `storyboard.html` exists — the contract was generated at all;
  2. it is NEWER than every input it claims to describe (the style draw, the
     composed prompts, and the keyframe being submitted), so a contract cannot be
     approved and then quietly invalidated by a later edit — which is exactly what
     happened;
  3. `storyboard.approved` exists and is newer than `storyboard.html` — a human looked
     at the current contract, not an earlier one.

  4. (2026-08-22) `submit-contract.approved` binds the approval to the BYTES: the sha of
     `submit-contract.json`, and per job the hash of the exact payload the page showed
     (prompt, duration, shape, reference file contents). `lane_render.py` recomputes
     that hash from the payload it is about to send and refuses any job that moved.
     And the approval is the OPERATOR'S act: run from inside an agent session
     (`CLAUDECODE` / `CLAUDE_CODE_ENTRYPOINT` in the environment) or without a
     terminal on stdin, --approve refuses. An agent approving its own contract is
     how two batches of draws went out against prompts nobody had read.

Usage:
  spend_gate.py --build-dir <build/> --label <what> --credits <n> [--input <path> ...]
  spend_gate.py --build-dir <build/> --approve --hash <8 hex> [--allow w05,w06]
                                                     # records review of the CURRENT contract
  spend_gate.py --build-dir <build/> --ledger         # print what has been spent
Exit 0 = cleared (and logged), 4 = refused.
"""
from __future__ import annotations

import argparse
import getpass
import hashlib
import json
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lane_render import APPROVAL_FILE, CONTRACT_FILE, payload_hash  # noqa: E402

LEDGER = "spend-ledger.json"
AGENT_ENV = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")


def sha256_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def approve_contract(build: str, allow: str, want_hash: str) -> None:
    """Write submit-contract.approved, bound to the contract's bytes and its payloads."""
    contract = os.path.join(build, CONTRACT_FILE)
    if not os.path.isfile(contract):
        die(f"nothing to approve — {contract} does not exist. Run preflight_higgs.py first.")
    force = os.environ.get("RAP_APPROVE_FORCE") == "1"
    agent = [k for k in AGENT_ENV if k in os.environ]
    if agent and not force:
        die(f"approval is the operator's act — run this from your own terminal "
            f"({', '.join(agent)} is set: this is an agent session)")
    if not sys.stdin.isatty() and not force:
        die("approval is the operator's act — run this from your own terminal "
            "(stdin is not a TTY)")
    if force:
        print("spend_gate: RAP_APPROVE_FORCE=1 — the operator-terminal check is overridden "
              "and this is being logged", file=sys.stderr)
    sha = sha256_file(contract)
    if not want_hash:
        die(f"--hash is required: the page header prints the contract's 8-char hash "
            f"(this one is {sha[:8]}); passing it back is the proof the page was opened")
    if sha[:8] != want_hash.lower():
        die(f"--hash {want_hash} is not this contract ({sha[:8]}) — the page you looked "
            f"at is not the contract on disk; re-open it")
    doc = json.load(open(contract, encoding="utf-8"))
    jobs, variants = {}, {}
    for w in doc.get("windows", []):
        payload = w.get("payload")
        if not payload:
            die(f"window {w.get('id')} carries no payload — re-run preflight_higgs.py "
                f"(the contract predates the payload-bound approval)")
        try:
            jobs[w["id"]] = payload_hash(payload)
            # A window's variants (the scrub prompt for draw 2) are approved in the SAME
            # act: each is shown on the page under its card, and each hash is bound here.
            for vname, v in (w.get("variants") or {}).items():
                variants.setdefault(w["id"], {})[vname] = payload_hash(v["payload"])
        except FileNotFoundError as exc:
            die(f"window {w['id']}: a reference is missing on disk ({exc}) — nothing approved")
    allowed = [a.strip() for a in allow.split(",") if a.strip()] if allow else list(jobs)
    unknown = [a for a in allowed if a not in jobs]
    if unknown:
        die(f"--allow names jobs not in the contract: {', '.join(unknown)}")
    by = os.environ.get("USER") or getpass.getuser()
    now = time.strftime("%Y-%m-%dT%H:%M:%S%z")
    approval = {"contractSha": sha, "approvedAt": now, "approvedBy": by,
                "allowedJobs": allowed, "jobs": jobs, "variants": variants}
    with open(os.path.join(build, APPROVAL_FILE), "w", encoding="utf-8") as fh:
        json.dump(approval, fh, indent=1)
        fh.write("\n")
    audit = os.path.join(os.path.dirname(os.path.abspath(build)), "project-audit.jsonl")
    with open(audit, "a", encoding="utf-8") as fh:
        fh.write(json.dumps({"at": now, "by": by, "contractSha": sha,
                             "allowedJobs": allowed, "force": force}) + "\n")
    print(f"spend_gate: submit contract {sha[:8]} approved by {by} — "
          f"{len(allowed)} job(s): {', '.join(allowed)}", file=sys.stderr)


def die(msg: str, code: int = 4) -> None:
    print(f"spend_gate: {msg}", file=sys.stderr)
    raise SystemExit(code)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--build-dir", required=True)
    ap.add_argument("--label", default="")
    ap.add_argument("--credits", type=float, default=0.0)
    ap.add_argument("--input", action="append", default=[])
    ap.add_argument("--approve", action="store_true")
    ap.add_argument("--allow", default="", help="comma-separated job ids (default: every "
                    "window in the contract)")
    ap.add_argument("--hash", default="", help="first 8 hex chars of the contract sha, as "
                    "printed in the page header")
    ap.add_argument("--ledger", action="store_true")
    args = ap.parse_args()

    b = args.build_dir
    preview = os.path.join(b, "storyboard.html")
    approved = os.path.join(b, "storyboard.approved")
    ledger_path = os.path.join(b, LEDGER)

    if args.ledger:
        if not os.path.isfile(ledger_path):
            print("spend_gate: nothing spent yet", file=sys.stderr)
            return
        entries = json.load(open(ledger_path, encoding="utf-8"))["spends"]
        total = sum(e["credits"] for e in entries)
        for e in entries:
            print(f"  {e['at']}  {e['credits']:>8.0f}  {e['label']}")
        print(f"  {'':>21}{total:>8.0f}  TOTAL", file=sys.stderr)
        return

    if args.approve:
        if not os.path.isfile(preview):
            die(f"nothing to approve — {preview} does not exist. Run compose_prompts.py first.")
        # The payload-bound approval FIRST: it refuses without writing anything, so a
        # refused --approve leaves neither file behind.
        approve_contract(b, args.allow, args.hash)
        with open(approved, "w", encoding="utf-8") as fh:
            fh.write(f"approved {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
        print(f"spend_gate: contract approved ({preview})", file=sys.stderr)
        return

    if not os.path.isfile(preview):
        die("REFUSED — no preview contract. Build it first:\n"
            "  compose_prompts.py --styles <styles.json> --drawn <styles-drawn.json> "
            f"--out-dir '{b}' --keyframe-dir <references/>\n"
            "then open it, then --approve. Never spend on an unreviewed setup.")

    p_mtime = os.path.getmtime(preview)
    stale = [i for i in args.input if os.path.isfile(i) and os.path.getmtime(i) > p_mtime]
    if stale:
        die("REFUSED — the contract is STALE. These changed after storyboard.html was built:\n" +
            "".join(f"    {s}\n" for s in stale) +
            "  Re-run compose_prompts.py and re-approve. This is the exact failure that\n"
            "  wasted a paid render: a clip bought against a style set that then changed.")

    if not os.path.isfile(approved):
        die(f"REFUSED — contract not approved. Open {preview}, then:\n"
            f"  spend_gate.py --build-dir '{b}' --approve")
    if os.path.getmtime(approved) < p_mtime:
        die("REFUSED — the approval predates the current contract. Re-open storyboard.html "
            "and re-approve.")
    # The per-window contract, when there is one, must be approved AS IT IS. lane_render
    # refuses without this too; checking here keeps the runner's gate message the one
    # the operator sees, instead of a FATAL from the driver a stage later.
    contract = os.path.join(b, CONTRACT_FILE)
    bound = os.path.join(b, APPROVAL_FILE)
    if os.path.isfile(contract):
        if not os.path.isfile(bound):
            die(f"REFUSED — the per-window submit contract is not approved. Open "
                f"{os.path.join(b, 'submit-contract.html')}, then from YOUR terminal:\n"
                f"  spend_gate.py --build-dir '{b}' --approve --hash <8 hex from the page>")
        try:
            bound_sha = json.load(open(bound, encoding="utf-8")).get("contractSha")
        except (OSError, ValueError):
            bound_sha = None
        if bound_sha != sha256_file(contract):
            die("REFUSED — the submit contract changed since it was approved. Re-open "
                "submit-contract.html and re-approve with its new hash.")

    entries = {"spends": []}
    if os.path.isfile(ledger_path):
        entries = json.load(open(ledger_path, encoding="utf-8"))
    entries["spends"].append({
        "at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "label": args.label or "(unlabelled)",
        "credits": args.credits,
    })
    with open(ledger_path, "w", encoding="utf-8") as fh:
        json.dump(entries, fh, indent=2)
        fh.write("\n")
    total = sum(e["credits"] for e in entries["spends"])
    print(f"spend_gate: cleared '{args.label}' ({args.credits:g} cr) — "
          f"{total:g} cr spent on this film so far", file=sys.stderr)


if __name__ == "__main__":
    main()
