#!/usr/bin/env python3
"""paid_take.py — ONE window of a rap plan on the paid Higgsfield API pool.

The free lane (`lane_render.py`, the cloaked app session) is the default and stays it.
This is the paid door for a window the free lane cannot land: the same prompt, the same
references and the same duration the driver would send, submitted through the official
`higgsfield` CLI (`generate cost` → `generate create` → `generate get`) on the API pool —
a separate slot from the app's single free one, so it never blocks a running free pass.

What it is NOT: a batch. One window per call. The explore supervisor re-offers pending
jobs and would re-buy a batch every pass; this script buys exactly one take and stops.

The gates, in this order, every one before `create`:
  1. `higgsfield` on PATH and `account status --json` authenticated (balance read);
  2. the operator's approval covers THIS window's current payload hash — the same
     `approval_gate` the free driver runs (prompt + duration + shape + reference BYTES),
     from `spend_gate.py --approve`, which refuses inside an agent session;
  3. the DONOR is bound separately: `payload_hash` does not cover `motionReferencePath`,
     so the donor's sha256 is printed on the contract line and a donor newer than the
     approved contract refuses a paid submit (the "contract newer than its inputs" rule);
  4. `--cost-only` or `--confirm-spend`;
  5. `generate cost` ≤ `--max-credits` (the CLI validates every param there too);
  6. an accepted clip already on disk refuses without `--replace`.

`generate cost` UPLOADS the references (there is no `upload delete`) — a quote is a
mutation, and this script says so every time it quotes. The voice rides the AUDIO channel
(the engine's `_extract_audio_track`): the black-frame video route drew six moderation
refusals on one window that went through first time as audio. The donor rides
`--video-references`. Duration must already be a whole second (make_plan pads to whole
seconds; a fractional plan is refused, never rounded — the model fills the whole clip).

After `create`: the job id goes to `<queueDir>/<id>-paid-job.json` (its OWN record —
the free driver's `<id>-live-job.json` recovery polls through the cloak engine and must
never see a CLI job), the clip is polled, downloaded to `superseded/<id>-draw<N>-paid.mp4`,
judged by `lane_render.judge_landed` (the same whisper-vs-slice verdict) and moved to
`clips/<id>.mp4` only when it passes. Every step is a `lane-render.log` line in the
driver's own shape, so draws_review / sync_review read a paid take like any other. The
actual debit is read back from `account transactions` and matched exactly like the
Cinema adapter does (one negative row, ±10 s); unmatched is recorded as null, never a
guess.

Usage:
  paid_take.py --plan build/plan.json --window w05 (--cost-only | --confirm-spend)
               [--model seedance_2_5] [--resolution 480p|720p|1080p] [--max-credits 60]
               [--replace] [--higgsfield-bin higgsfield]
`--cost-only` writes NOTHING into the project (no log line, no record): it is safe to run
against a live film mid-render. `seconds` may be a float with an integer value (5.0) —
make_plan writes those; only a true fraction (7.5) is refused.

Exit 0 clip judged and kept (or --cost-only printed its quote) · 2 bad inputs ·
     3 refused (no approval / donor moved / over budget / not on PATH / not logged in /
     clip already on disk) · 4 the provider failed or the clip was judged unfit (parked).
"""
from __future__ import annotations

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

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

import lane_render  # noqa: E402
from lane_render import (  # noqa: E402
    APPROVAL_FILE, CONTRACT_FILE, approval_gate, build_payload_doc, clip_path,
    judge_landed, payload_hash, prepare, say,
)
import preflight_higgs  # noqa: E402

ROUTE = "higgsfield-cli"
DEFAULT_MODEL = "seedance_2_5"
DEFAULT_MAX_CREDITS = 60.0
POLL_INTERVAL_S = 20
POLL_TIMEOUT_S = 1800
SPEND_MATCH_WINDOW_S = 10          # mirrors HIGGSFIELD_COST_MATCH_WINDOW_MS in the Cinema adapter
LEDGER = "spend-ledger.json"       # spend_gate.LEDGER — the same file, the same row shape


class Refused(Exception):
    """A gate said no. Carries the exit code the caller reports."""
    def __init__(self, msg: str, code: int = 3):
        super().__init__(msg)
        self.code = code


# --------------------------------------------------------------------------
# the CLI, one thin layer — every call is a subprocess, every answer parsed JSON
# --------------------------------------------------------------------------

class HiggsfieldCli:
    def __init__(self, binary: str):
        self.binary = binary

    def run(self, args: list[str], timeout: int = 600) -> subprocess.CompletedProcess:
        return subprocess.run([self.binary, *args], capture_output=True, text=True, timeout=timeout)

    def json(self, args: list[str], what: str, timeout: int = 600):
        proc = self.run(args, timeout=timeout)
        if proc.returncode != 0:
            err = (proc.stderr or proc.stdout or "").strip()
            raise Refused(f"{what}: higgsfield exited {proc.returncode}: {err[:400]}", 4 if what.startswith("generate") else 3)
        try:
            return json.loads(proc.stdout)
        except ValueError as exc:
            raise Refused(f"{what}: higgsfield printed no JSON ({exc}): {proc.stdout[:200]!r}", 4)


def generation_argv(operation: str, model: str, params: list[str]) -> list[str]:
    """`generate cost|create <model> <params...> --json` — the Cinema adapter's shape."""
    return ["generate", operation, model, *params, "--json"]


def cli_params(prompt: str, seconds: int, resolution: str, aspect: str, voice: bool,
               images: list[str], videos: list[str], audios: list[str]) -> list[str]:
    """The `--param value` list, in a FIXED order, identical for cost and create."""
    params = ["--prompt", prompt, "--duration", str(seconds), "--resolution", resolution,
              "--aspect_ratio", aspect, "--mode", "omni_reference"]
    if voice:
        params += ["--generate_audio", "true"]
    for path in images:
        params += ["--image-references", path]
    for path in videos:
        params += ["--video-references", path]
    for path in audios:
        params += ["--audio-references", path]
    return params


def create_job_id(response) -> str | None:
    """`["<uuid>"]`, `[{id}]` or `{id|job_id|jobId}`; two ids or none → None (mirrors
    higgsfieldCreateJobId — an ambiguous create is recorded, never retried)."""
    if isinstance(response, list):
        if len(response) != 1:
            return None
        only = response[0]
        if isinstance(only, str):
            return only.strip() or None
        return create_job_id(only) if isinstance(only, dict) else None
    if not isinstance(response, dict):
        return None
    for key in ("id", "job_id", "jobId"):
        value = response.get(key)
        if isinstance(value, str) and value.strip():
            return value
    return None


def job_state(raw: str) -> str:
    s = (raw or "").lower().replace("-", "_").replace(" ", "_")
    if s in ("completed", "complete", "succeeded", "success", "done"):
        return "completed"
    if s in ("failed", "error", "cancelled", "canceled", "nsfw", "moderated", "rejected"):
        return "failed"
    return "pending"


def result_url(doc: dict) -> str | None:
    for key in ("result_url", "resultUrl", "outputUrl", "output_url", "url"):
        value = doc.get(key)
        if isinstance(value, str) and re.match(r"^(https?:|file:|data:)", value, re.I):
            return value
    for key in ("output", "result"):
        nested = doc.get(key)
        if isinstance(nested, dict):
            found = result_url(nested)
            if found:
                return found
    for key in ("outputs", "results", "media", "videos"):
        items = doc.get(key)
        if isinstance(items, list):
            for item in items:
                if isinstance(item, str) and re.match(r"^(https?:|file:)", item, re.I):
                    return item
                if isinstance(item, dict):
                    found = result_url(item)
                    if found:
                        return found
    return None


def _parse_iso(value: str) -> float | None:
    try:
        return time.mktime(time.strptime(value[:19], "%Y-%m-%dT%H:%M:%S")) if value else None
    except ValueError:
        return None


def match_spend(job: dict, transactions: list[dict]) -> tuple[float | None, int]:
    """The one `spend` row for this job: same display_name, within ±10 s of the job's
    created_at, a finite credit (a DEBIT IS NEGATIVE — the magnitude is the cost).
    Exactly one candidate or nothing; never a guess (mirrors matchHiggsfieldSpend)."""
    at = _parse_iso(str(job.get("created_at") or ""))
    if at is None:
        return None, 0
    found = []
    for row in transactions:
        if row.get("action") != "spend" or row.get("display_name") != job.get("display_name"):
            continue
        rat = _parse_iso(str(row.get("created_at") or ""))
        credits = row.get("credits")
        if rat is None or not isinstance(credits, (int, float)):
            continue
        if abs(rat - at) <= SPEND_MATCH_WINDOW_S:
            found.append(abs(float(credits)))
    if len(found) != 1:
        return None, len(found)
    return found[0], 1


# --------------------------------------------------------------------------
# the contract for one window
# --------------------------------------------------------------------------

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 whole_seconds(value) -> int:
    """The CLI's `duration` is an integer. A fractional plan is refused, not rounded:
    rounding up hands the model a clip longer than its voice slice, and the model fills
    the whole clip (render length = sung length)."""
    if isinstance(value, bool) or value is None:
        raise Refused(f"the window has no seconds ({value!r})", 2)
    if isinstance(value, int):
        return value
    if isinstance(value, float) and value.is_integer():
        return int(value)
    raise Refused(f"the window's seconds is {value!r}, not a whole number — the CLI takes an "
                  "integer duration and rounding would hand the model a clip longer than its "
                  "voice slice; re-plan with whole seconds (make_plan pads to whole seconds)", 2)


def compiled_prompt(adapter, payload: dict) -> str:
    """The prompt as the engine cites it (<<<image_N>>> / <<<video_1>>> / <<<audio_1>>>) —
    from the adapter's own builders, through preflight's provider_body. No adapter →
    refused: a paraphrased citation is exactly the kind of drift the contract forbids."""
    body = preflight_higgs.provider_body(adapter, payload)
    if not body:
        raise Refused("engines/seedance-direct/adapter.py could not be imported — the compiled "
                      "prompt (the media citations) comes from its builders and nothing else", 2)
    return body["body"]["params"]["prompt"]


def build_contract(plan: dict, job: dict, adapter, tmp_dir: str, resolution: str | None) -> dict:
    """Everything the CLI will be given, from the driver's own payload."""
    jid = job["id"]
    work = os.path.join(plan["queueDir"], "work", jid)
    payload = build_payload_doc(plan, job, work)
    task = payload["tasks"][0]
    profile = payload["executionProfile"]
    seconds = whole_seconds(task.get("durationSeconds"))
    refs = list(task.get("referencePaths") or [])
    voice = os.path.abspath(job["voiceRef"]) if job.get("voiceRef") else None
    images = [p for p in refs if os.path.abspath(p) != voice]
    audios: list[str] = []
    if job.get("voiceRef"):
        track = adapter._extract_audio_track(os.path.abspath(job["voiceRef"]), tmp_dir)
        if not track:
            raise Refused("the voice slice's audio could not be extracted (ffmpeg missing?) — the "
                          "voice rides the AUDIO channel on this route; nothing is sent as a "
                          "black-frame video instead", 2)
        audios.append(track)
    videos = [os.path.abspath(job["motionRef"])] if job.get("motionRef") else []
    prompt = compiled_prompt(adapter, payload)
    params = cli_params(prompt, seconds, resolution or profile["resolution"], profile["aspectRatio"],
                        bool(job.get("voiceRef")), images, videos, audios)
    return {
        "payload": payload,
        "payloadHash": payload_hash(payload),
        "params": params,
        "seconds": seconds,
        "images": images,
        "videos": videos,
        "audios": audios,
        "donorSha": sha256_file(videos[0]) if videos else None,
        "prompt": prompt,
    }


def donor_is_newer_than_contract(build: str, donor: str | None) -> bool:
    if not donor:
        return False
    contract = os.path.join(build, CONTRACT_FILE)
    if not os.path.isfile(contract):
        return True
    return os.path.getmtime(donor) > os.path.getmtime(contract)


def next_draw(plan: dict, jid: str) -> int:
    superseded = os.path.join(plan["queueDir"], "superseded")
    if not os.path.isdir(superseded):
        return 1
    n = 0
    for name in os.listdir(superseded):
        m = re.match(rf"{re.escape(jid)}-draw(\d+)-paid", name)
        if m:
            n = max(n, int(m.group(1)))
    return n + 1


def download(url: str, dest: str) -> None:
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    if url.startswith("file://"):
        shutil.copyfile(url[len("file://"):], dest)
        return
    with urllib.request.urlopen(url, timeout=600) as resp, open(dest, "wb") as fh:  # noqa: S310
        shutil.copyfileobj(resp, fh)


def write_record(plan: dict, jid: str, fields: dict) -> str:
    path = os.path.join(plan["queueDir"], f"{jid}-paid-job.json")
    rec = {}
    if os.path.isfile(path):
        try:
            rec = json.load(open(path, encoding="utf-8"))
        except (OSError, ValueError):
            rec = {}
    rec.update(fields)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(rec, fh, indent=1)
    return path


def ledger_append(build: str, label: str, credits: float | None, note: str | None) -> None:
    """The lane's spend ledger (spend_gate.py's file and row shape). spend_gate's own
    `--credits` path is a pre-spend GATE on the storyboard contract; by the time a
    paid take has completed the money is spent, so the row is written here directly,
    in the same shape `spend_gate.py --ledger` prints."""
    path = os.path.join(build, LEDGER)
    entries = {"spends": []}
    if os.path.isfile(path):
        try:
            entries = json.load(open(path, encoding="utf-8"))
        except (OSError, ValueError):
            entries = {"spends": []}
    row = {"at": time.strftime("%Y-%m-%d %H:%M:%S"), "label": label,
           "credits": credits if credits is not None else 0.0, "route": ROUTE}
    if credits is None:
        row["actualCredits"] = None
    if note:
        row["note"] = note
    entries.setdefault("spends", []).append(row)
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(entries, fh, indent=2)
        fh.write("\n")


# --------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------

def print_contract(jid: str, argv: list[str], contract: dict, balance, credits=None) -> None:
    print("\n===== PAID TAKE CONTRACT =====")
    print(f"window     {jid}   route {ROUTE}   payload {contract['payloadHash'][:8]}")
    print(f"images     {', '.join(contract['images']) or '(none)'}")
    print(f"video      {', '.join(contract['videos']) or '(none)'}"
          + (f"   sha256 {contract['donorSha'][:12]}" if contract["donorSha"] else ""))
    print(f"audio      {', '.join(contract['audios']) or '(none)'}")
    print(f"seconds    {contract['seconds']}")
    print("argv       higgsfield " + " ".join(json.dumps(a) if " " in a else a for a in argv))
    if balance is not None:
        print(f"balance    {balance} credits")
    if credits is not None:
        print(f"quote      {credits} credits (generate cost — the references were UPLOADED to quote it)")
    print("==============================\n")


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0])
    ap.add_argument("--plan", required=True)
    ap.add_argument("--window", required=True, help="one job id, e.g. w05")
    ap.add_argument("--cost-only", action="store_true", help="quote (uploads the references), submit nothing")
    ap.add_argument("--confirm-spend", action="store_true", help="submit ONE paid take after the quote")
    ap.add_argument("--model", default=DEFAULT_MODEL)
    ap.add_argument("--resolution", default="", help="override the plan's resolution (480p|720p|1080p)")
    ap.add_argument("--max-credits", type=float, default=DEFAULT_MAX_CREDITS)
    ap.add_argument("--replace", action="store_true", help="park the accepted clip on disk and buy a new take")
    ap.add_argument("--higgsfield-bin", default=os.environ.get("HIGGSFIELD_BIN", "higgsfield"))
    ap.add_argument("--poll-interval", type=int, default=POLL_INTERVAL_S)
    ap.add_argument("--poll-timeout", type=int, default=POLL_TIMEOUT_S)
    args = ap.parse_args(argv)

    if args.cost_only == args.confirm_spend:
        print("paid_take: give exactly one of --cost-only or --confirm-spend", file=sys.stderr)
        return 2
    if args.resolution and args.resolution not in ("480p", "720p", "1080p"):
        print(f"paid_take: --resolution must be 480p, 720p or 1080p, got {args.resolution!r}", file=sys.stderr)
        return 2

    plan = prepare(args.plan)
    build = os.path.join(plan["projectDir"], "build")
    # --cost-only WRITES NOTHING into the project: no log line, no record, no directory.
    # It is the probe an operator runs against a live film mid-render; the only trace
    # it leaves is on the provider (the references it uploads to quote). The log opens
    # for a paid submit only.
    if args.confirm_spend:
        lane_render._LOG = os.path.join(build, "lane-render.log")
        os.makedirs(build, exist_ok=True)
    jobs = [j for j in plan["jobs"] if j.get("id") == args.window]
    if len(jobs) != 1:
        print(f"paid_take: window {args.window!r} is not in the plan "
              f"({', '.join(j.get('id', '?') for j in plan['jobs'])})", file=sys.stderr)
        return 2
    job = jobs[0]
    jid = job["id"]

    tmp_dir = tempfile.mkdtemp(prefix=f"paid-take-{jid}-")
    try:
        return _run(args, plan, job, build, tmp_dir)
    except Refused as exc:
        say(f"{jid}: REFUSED — {exc} (paid {ROUTE})")
        return exc.code
    finally:
        shutil.rmtree(tmp_dir, ignore_errors=True)


def _run(args, plan: dict, job: dict, build: str, tmp_dir: str) -> int:
    jid = job["id"]
    dest = clip_path(plan, job)

    # 1. the binary and the login
    binary = shutil.which(args.higgsfield_bin)
    if not binary:
        raise Refused(f"`{args.higgsfield_bin}` is not on PATH — install the official Higgsfield CLI "
                      "or pass --higgsfield-bin", 3)
    cli = HiggsfieldCli(binary)
    account = cli.json(["account", "status", "--json"], "account status")
    if not isinstance(account, dict) or not isinstance(account.get("credits"), (int, float)):
        raise Refused("`higgsfield account status --json` did not report a credit balance — log in "
                      "with `higgsfield auth login` first", 3)
    balance = account["credits"]

    # 2. the operator's approval covers THIS payload (the free driver's own gate)
    kept, refused = approval_gate(build, [(plan, job)])
    if refused or not kept:
        raise Refused("the approval does not cover this window as it is now — re-run preflight "
                      "and approve from your terminal", 3)

    adapter = preflight_higgs.load_adapter()
    if adapter is None:
        raise Refused("engines/seedance-direct/adapter.py could not be imported; the voice track and "
                      "the media citations come from its builders", 2)
    contract = build_contract(plan, job, adapter, tmp_dir, args.resolution or None)

    # 3. the donor is bound here, because payload_hash does not cover it
    if contract["videos"] and donor_is_newer_than_contract(build, contract["videos"][0]):
        msg = (f"the donor {os.path.basename(contract['videos'][0])} is NEWER than the approved "
               f"{CONTRACT_FILE} — the approval never saw this donor (payload_hash does not cover "
               "motionReferencePath); re-run preflight and re-approve")
        if args.confirm_spend:
            raise Refused(msg, 3)
        say(f"{jid}: WARNING — {msg} (quoting anyway; a paid submit would refuse)")

    # 6. (checked before the quote so a refused take uploads nothing) a take already accepted
    if os.path.exists(dest) and not args.replace:
        raise Refused(f"an accepted clip is already on disk ({dest}) — pass --replace to park it and "
                      "buy another take", 3)

    # 5. the quote — the CLI validates every param here and uploads the references
    cost_argv = generation_argv("cost", args.model, contract["params"])
    quote = cli.json(cost_argv, "generate cost")
    credits = quote.get("credits") if isinstance(quote, dict) else None
    if not isinstance(credits, (int, float)):
        raise Refused(f"`generate cost` answered without a credits figure: {json.dumps(quote)[:200]}", 4)
    credits = float(credits)
    print_contract(jid, cost_argv, contract, balance, credits)
    say(f"{jid}: quoted {credits:g} cr on {ROUTE} ({args.model}, {contract['seconds']} s, "
        f"payload {contract['payloadHash'][:8]}, references uploaded by the quote)")
    if credits > args.max_credits:
        raise Refused(f"the quote ({credits:g} cr) is over --max-credits ({args.max_credits:g}); "
                      "nothing submitted", 3)
    if credits > balance:
        raise Refused(f"the quote ({credits:g} cr) exceeds the balance ({balance}); nothing submitted", 3)
    if args.cost_only:
        say(f"{jid}: --cost-only — nothing submitted (the references were uploaded to quote)")
        return 0

    # the submit: byte-identical params to the quote
    draw = next_draw(plan, jid)
    create_argv = generation_argv("create", args.model, contract["params"])
    if create_argv[3:-1] != cost_argv[3:-1]:
        raise Refused("the create params drifted from the quoted params — nothing submitted", 4)
    response = cli.json(create_argv, "generate create")
    job_id = create_job_id(response)
    submitted_at = time.strftime("%Y-%m-%dT%H:%M:%S")
    record = write_record(plan, jid, {
        "state": "accepted-by-provider" if job_id else "unknown-submission",
        "providerJobId": job_id, "route": ROUTE, "model": args.model, "draw": draw,
        "payloadHash": contract["payloadHash"], "donorSha": contract["donorSha"],
        "quotedCredits": credits, "submittedAt": submitted_at, "createResponse": response,
    })
    if not job_id:
        say(f"{jid}: create returned no single job id ({json.dumps(response)[:160]}) — recorded as an "
            f"UNKNOWN submission in {record}; it is NOT retried (a create may have happened)")
        return 4
    say(f"{jid}: ACCEPTED job={job_id} task=paid (draw {draw}) — paid {ROUTE} {credits:g} cr")

    # poll
    deadline = time.time() + args.poll_timeout
    doc: dict = {}
    while True:
        doc = cli.json(["generate", "get", job_id, "--json"], "generate get")
        if not isinstance(doc, dict):
            raise Refused(f"`generate get {job_id}` answered with no object", 4)
        state = job_state(str(doc.get("status") or ""))
        if state != "pending":
            break
        if time.time() >= deadline:
            write_record(plan, jid, {"state": "timed-out", "lastStatus": doc.get("status")})
            say(f"{jid}: job {job_id} still {doc.get('status')} after {args.poll_timeout} s — left "
                f"running; re-run reads {os.path.basename(record)} (nothing re-bought)")
            return 4
        time.sleep(args.poll_interval)
    say(f"{jid}: job {job_id} -> {doc.get('status')}")

    # the actual debit, read back — never assumed
    actual, candidates = None, 0
    try:
        tx = cli.json(["account", "transactions", "--size", "50", "--json"], "account transactions")
        items = tx.get("items") if isinstance(tx, dict) else None
        actual, candidates = match_spend(doc, items or [])
    except Refused as exc:
        say(f"{jid}: transactions unreadable ({exc}) — actual cost recorded as unknown")
    note = None if actual is not None else f"not found in transactions ({candidates} candidate(s))"
    ledger_append(build, f"{jid} paid take ({ROUTE} {args.model}, quoted {credits:g} cr)", actual, note)
    write_record(plan, jid, {"state": state, "actualCredits": actual, "actualCreditsNote": note,
                             "completedAt": time.strftime("%Y-%m-%dT%H:%M:%S")})

    if state == "failed":
        say(f"{jid}: the provider ended job {job_id} as {doc.get('status')} — paid take draw {draw} "
            f"produced nothing (actual debit: {actual if actual is not None else 'unknown'})")
        return 4

    url = result_url(doc)
    if not url:
        say(f"{jid}: completed but no result url in the job record — see {record}")
        return 4
    superseded = os.path.join(plan["queueDir"], "superseded")
    parked = os.path.join(superseded, f"{jid}-draw{draw}-paid.mp4")
    download(url, parked)
    write_record(plan, jid, {"clip": parked})

    # judge with the driver's own judge, land only on a pass
    verdict = judge_landed(plan, job, parked)
    if verdict.get("ok"):
        if os.path.exists(dest):
            os.replace(dest, os.path.join(superseded, f"{jid}-prev-{int(time.time())}-replaced-by-paid.mp4"))
        os.makedirs(os.path.dirname(dest), exist_ok=True)
        shutil.move(parked, dest)
        needs = "slide" if verdict.get("borderline") else "ok"
        write_record(plan, jid, {"clip": dest, "verdict": verdict.get("why"), "needs": needs,
                                 "borderline": bool(verdict.get("borderline"))})
        if verdict.get("borderline"):
            say(f"{jid}: BORDERLINE keep — {verdict.get('why')}")
        say(f"{jid}: -> {dest}  ({verdict.get('why')}) — paid {ROUTE}, "
            f"{actual if actual is not None else 'unknown'} cr")
        return 0
    write_record(plan, jid, {"verdict": verdict.get("why"), "shape": verdict.get("shape"),
                             "needs": verdict.get("needs") or "rerender:redraw"})
    say(f"{jid}: REJECTED draw {draw} — {verdict.get('why')}. (paid {ROUTE}; parked at {parked})")
    return 4


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