#!/usr/bin/env python3
"""reapi_take.py — ONE window of a rap plan on Seedance 2.5 via reAPI (the second paid door).

Reached as `paid_take.py --route reapi-seedance`; never called by the free driver or the
explore supervisor. The shape is paid_take.py's Higgsfield-CLI door, kept deliberately:
one window per call, the operator's approval must cover THIS payload hash (the same
`approval_gate` the free driver runs), `--cost-only | --confirm-spend`, a quote BEFORE the
create, the same judge (`judge_landed`), the same `<id>-paid-job.json` record, the same
lane-render.log line and the same spend ledger. What differs:

  * the provider is vclaw's own `reapi-seedance` transport — `dist/cli/provider-adapter.js
    --route reapi-seedance` on the stdin SUBMIT/POLL contract `lane_render.submit()` already
    speaks — reached through the treg catalog on TREG_TOKEN (`VCLAW_REAPI_SEEDANCE_VIA=treg`);
  * the quote is `dist/cli/reapi-quote-adapter.js`, treg's live per-second table for the
    catalog row, in USD (480p ≈ $0.12/s, 720p ≈ $0.27/s, 1080p ≈ $0.46/s; 4 s minimum);
  * the voice rides `audio_urls` as an EXTRACTED audio track (free), never the black-frame
    video (which reAPI would bill on top of the output); the motion donor DOES ride
    `video_urls` and the quote prices its length on top — the contract line says so;
  * the plan's citations are rewritten for reAPI's grammar: `@IMG_N` / `<<<image_N>>>` →
    `@imageN`, `<<<audio_1>>>` → `@audio1`, `<<<video_1>>>` → `@video1`;
  * the ledger row is in USD (the label says so), and `--max-usd` is the cap;
  * `--sung-only` renders the SUNG span, not the window: the head silence is cut off the
    audio, the render is the shortest whole second that holds the singing, the prompt says
    so (sung_only.py). The take is a VARIANT on the contract page (`sungOnly`), hashed into
    the same approval; the door refuses unless its own re-derivation hashes the same. The
    rendered clip is padded back to WINDOW shape (first frame held for the cut head) before
    the judge and before it lands, so the judge and the cutter see what they always see.

Gates, in order, every one before a create: `VCLAW_REAPI_SEEDANCE_VIA=treg` + `TREG_TOKEN`
in the environment; a built `dist/`; the approval covers this window's current payload
hash; the donor is not newer than the approved contract; an accepted clip on disk refuses
without `--replace`; the quote ≤ `--max-usd` and ≤ the treg balance.

Exit codes as paid_take.py: 0 kept (or --cost-only printed its quote) · 2 bad inputs ·
3 refused · 4 provider failed / clip judged unfit (parked).
"""
from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import sys
import time

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

import lane_render  # noqa: E402
import sung_only  # noqa: E402
from lane_render import (  # noqa: E402
    CONTRACT_FILE, NEEDS_FOR_SHAPE, VOICE_MIN_MEAN_DB, approval_gate, build_payload_doc, clip_mean_db,
    clip_path, judge_landed, payload_hash, resolve_main, say,
)

ROUTE = "reapi-seedance"
DEFAULT_MAX_USD = 2.0
POLL_INTERVAL_S = 10          # reAPI: poll every 10 s, polling is free
POLL_TIMEOUT_S = 1800
ZERO_HASH = "sha256:" + "0" * 64
ONE_HASH = "sha256:" + "1" * 64


class Refused(Exception):
    def __init__(self, msg: str, code: int = 3):
        super().__init__(msg)
        self.code = code


# --------------------------------------------------------------------------
# prompt grammar
# --------------------------------------------------------------------------

def reapi_prompt(prompt: str) -> str:
    """The plan's citations in reAPI's `@imageN / @audioN / @videoN` grammar.

    The free driver's plan cites the portrait as `@IMG_1` (a second still `@IMG_2`), the
    voice as `<<<audio_1>>>` and a donor as `<<<video_1>>>` (engines/seedance-direct
    compiles those). reAPI names references positionally in send order — images, then
    videos, then audio — so the numbers carry over as they are.
    """
    out = re.sub(r"@IMG_(\d+)", lambda m: f"@image{m.group(1)}", prompt)
    out = re.sub(r"<<<image_(\d+)>>>", lambda m: f"@image{m.group(1)}", out)
    out = re.sub(r"(?:<<<audio_(\d+)>>>|@AUD_(\d+))", lambda m: f"@audio{m.group(1) or m.group(2)}", out)
    out = re.sub(r"(?:<<<video_(\d+)>>>|@VID_(\d+))", lambda m: f"@video{m.group(1) or m.group(2)}", out)
    return out


# --------------------------------------------------------------------------
# the contract
# --------------------------------------------------------------------------

def extract_audio(voice_video: str, out_wav: str) -> str:
    """The voice slice's audio track as a wav (the free driver ships it as a black-frame mp4)."""
    proc = subprocess.run(
        ["ffmpeg", "-y", "-v", "error", "-i", voice_video, "-vn", "-acodec", "pcm_s16le",
         "-ar", "44100", "-ac", "1", out_wav],
        capture_output=True, text=True,
    )
    if proc.returncode != 0 or not os.path.isfile(out_wav):
        raise Refused(f"the voice slice's audio could not be extracted ({proc.stderr.strip()[-200:] or 'ffmpeg missing?'}) — "
                      "the voice rides audio_urls on this route; nothing is sent as a black-frame video instead", 2)
    return out_wav


def sha256_file(path: str) -> str:
    import hashlib
    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:
    seconds = float(value)
    if seconds != int(seconds):
        raise Refused(f"the plan's duration {value!r} is not a whole second — reAPI renders whole seconds "
                      "only and bills the whole clip; re-plan, never round here", 2)
    return int(seconds)


def submit_payload(plan: dict, work: str, profile: dict, prompt: str, images: list[str],
                   audios: list[str], donor: str | None, seconds: int) -> dict:
    """The SUBMIT body for `provider-adapter.js --route reapi-seedance`: a VideoExecutionPayload
    with ONE task. It carries NO `action` field — the built-in adapter (and
    engines/seedance-direct/adapter.py) treat an explicit one as unknown and refuse; only
    poll/cancel/lookup name themselves. The first paid take went out with `action: "submit"`
    and was refused before the provider saw it (2026-09-21) — the door's offline stub had
    accepted anything, so the real adapter is what the test feeds now."""
    return {
        "projectSlug": plan["slug"],
        "routeId": ROUTE,
        "workspaceRoot": plan["workspaceRoot"],
        "outputDir": work,
        "productionMode": "storyboard",
        "operationKind": "image-to-video" if images else "text-to-video",
        "executionProfile": profile,
        "generatedAt": time.strftime("%Y-%m-%dT%H:%M:%S"),
        "promptGuidance": [],
        "tasks": [{
            "sceneIndex": 0,
            "prompt": prompt,
            "inputKind": "image" if images else "text",
            "referencePaths": images + audios,
            "sourceAssetIds": [], "backendHints": [], "characters": [],
            "durationSeconds": seconds,
            **({"referenceRole": "character"} if images else {}),
            **({"motionReferencePath": donor} if donor else {}),
        }],
    }


AUDIO_EXTS = (".wav", ".mp3", ".m4a", ".flac", ".aac", ".ogg")


def build_contract(plan: dict, job: dict, tmp_dir: str, resolution: str | None, sung_only_take: bool = False) -> dict:
    """Everything the transport will be given, derived from the driver's own approved payload."""
    jid = job["id"]
    work = os.path.join(plan["queueDir"], "work", jid)
    approved = build_payload_doc(plan, job, work)          # what the base approval hash binds to
    # THE PAGE IS THE CONTRACT. The approved doc carries the plan's resolution and the hash
    # covers it; an override that differs would submit at a resolution nobody approved.
    approved_res = approved["executionProfile"].get("resolution")
    if resolution and resolution != approved_res:
        raise Refused(f"--resolution {resolution} differs from the approved contract's {approved_res} — the "
                      "resolution is part of the approval hash; set it in the pack, rebuild the page and re-approve", 2)
    # The transport and the quote adapter read VCLAW_REAPI_SEEDANCE_RESOLUTION AHEAD of the
    # profile: an inherited probe-tier export would render at a tier nobody approved while
    # the contract print still showed the approved one. Same rule, same refusal.
    ambient = (os.environ.get("VCLAW_REAPI_SEEDANCE_RESOLUTION") or "").strip()
    if ambient and ambient != approved_res:
        raise Refused(f"VCLAW_REAPI_SEEDANCE_RESOLUTION={ambient} is set in the environment and differs from the approved "
                      f"contract's {approved_res} — the transport would honour it over the page; unset it (or set it "
                      f"to {approved_res}) and run again", 2)
    take: dict | None = None
    if sung_only_take:
        try:
            d = sung_only.derive(plan, job)
            wav = sung_only.build_sung_audio(os.path.abspath(job["voiceRef"]), sung_only.audio_path(job), d["t0"], d["seconds"])
        except sung_only.NotApplicable as exc:
            raise Refused(f"--sung-only does not apply: {exc}", 2)
        doc = build_payload_doc(plan, sung_only.derived_job(job, wav, d), work)
        want = ((plan.get("_variants") or {}).get(jid) or {}).get(sung_only.SUNG_ONLY) or {}
        if not want.get("hash"):
            raise Refused("the approval does not cover a sung-only take of this window (no `sungOnly` variant was "
                          f"approved) — rebuild the contract page (preflight_higgs.py --route {ROUTE}) and approve it "
                          "from your terminal", 3)
        if want["hash"] != payload_hash(doc):
            raise Refused(f"the approved sung-only take (payload {want['hash'][:8]}) is not what this door would send now "
                          f"({payload_hash(doc)[:8]}): the prompt, the length or the cut audio's bytes moved — rebuild the "
                          "contract page and re-approve", 3)
        take = {**d, "audio": wav, "variantHash": payload_hash(doc)}
    else:
        doc = approved
    task = doc["tasks"][0]
    profile = dict(doc["executionProfile"])
    seconds = whole_seconds(task.get("durationSeconds"))
    voice = os.path.abspath(take["audio"] if take else job["voiceRef"]) if (take or job.get("voiceRef")) else None
    images = [p for p in task.get("referencePaths") or [] if os.path.abspath(p) != voice]
    audios: list[str] = []
    if voice:
        # An audio voiceRef (the sung-only wav) is sent AS IS: the bytes the transport hosts
        # are the bytes the approval hashed. Only a black-frame mp4 is extracted.
        audios.append(voice if voice.lower().endswith(AUDIO_EXTS)
                      else extract_audio(voice, os.path.join(tmp_dir, f"{jid}-voice.wav")))
    donor = os.path.abspath(job["motionRef"]) if job.get("motionRef") else None
    payload = submit_payload(plan, work, profile, reapi_prompt(task["prompt"]), images, audios, donor, seconds)
    return {
        "approved": doc,
        "baseHash": payload_hash(approved),
        "payloadHash": payload_hash(doc),
        "payload": payload,
        "seconds": seconds,
        "images": images,
        "videos": [donor] if donor else [],
        "audios": audios,
        "donorSha": sha256_file(donor) if donor else None,
        "prompt": payload["tasks"][0]["prompt"],
        "take": take,
    }


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 print_contract(jid: str, contract: dict, quote: dict | None) -> None:
    print("\n===== PAID TAKE CONTRACT (reAPI) =====")
    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]}   (BILLED on top of the output)" if contract["donorSha"] else ""))
    print(f"audio      {', '.join(contract['audios']) or '(none)'}   (free)")
    print(f"seconds    {contract['seconds']}   resolution {contract['payload']['executionProfile']['resolution']}")
    take = contract.get("take")
    if take:
        print(f"take       sung-only · {take['seconds']} s of a {take['windowSeconds']:g} s window · head cut {take['t0']:.2f} s"
              f" · tail {take['tail']:.2f} s · variant {take['variantHash'][:8]}")
        for change in take["changes"]:
            print(f"           - {change}")
    print(f"prompt     {contract['prompt'][:160]}{'…' if len(contract['prompt']) > 160 else ''}")
    if quote:
        schema = quote.get("parameterSchema", {})
        rows = "; ".join(f"{r['billableSeconds']} billable s at ${r['usdPerSecond']}/s"
                         for r in schema.get("x-videoclaw-reapi-price-rows", []))
        print(f"quote      ${quote['unitCost']['amount']:.3f} USD  (treg table "
              f"{schema.get('x-videoclaw-treg-table', {}).get('checked')}; {rows})")
        print(f"balance    ${quote['balance']['observed']['amount']:.2f} USD on treg")
    print("======================================\n")


# --------------------------------------------------------------------------
# the provider: vclaw's own transport, on the adapter contract
# --------------------------------------------------------------------------

class Adapters:
    def __init__(self, main: str):
        self.node = os.environ.get("NODE_BIN", "node")
        self.provider = os.path.join(main, "dist", "cli", "provider-adapter.js")
        self.quote = os.path.join(main, "dist", "cli", "reapi-quote-adapter.js")
        for path in (self.provider, self.quote):
            if not os.path.isfile(path):
                raise Refused(f"no built adapter at {path} — run npm run build", 3)

    def _run(self, argv: list[str], payload: dict, what: str, env: dict | None = None) -> dict:
        proc = subprocess.run([self.node, *argv], input=json.dumps(payload), capture_output=True,
                              text=True, env=env or os.environ.copy())
        if proc.returncode != 0:
            raise Refused(f"{what}: exited {proc.returncode}: {(proc.stderr or proc.stdout).strip()[-400:]}", 4 if what == "submit" else 3)
        try:
            return json.loads(proc.stdout[proc.stdout.index("{"):])
        except (ValueError, json.JSONDecodeError):
            raise Refused(f"{what}: printed no JSON: {proc.stdout[:200]!r}", 4)

    def quote_usd(self, contract: dict, env: dict) -> dict:
        body = {"action": "quote", "taskId": "paid-take", "routeId": ROUTE, "payload": contract["payload"],
                "providerArgumentsHash": ZERO_HASH, "sourceHashes": [], "adapterCommandHash": ONE_HASH}
        return self._run([self.quote], body, "quote", env)

    def submit(self, payload: dict, env: dict) -> dict:
        return self._run([self.provider, "--route", ROUTE], payload, "submit", env)

    def poll(self, plan: dict, work: str, job_id: str, env: dict) -> dict:
        return self._run([self.provider, "--route", ROUTE],
                         {"action": "poll", "projectSlug": plan["slug"], "routeId": ROUTE, "externalJobId": job_id,
                          "outputDir": work, "workspaceRoot": plan["workspaceRoot"]}, "poll", env)


def treg_env(resolution: str | None) -> dict:
    env = os.environ.copy()
    via = (env.get("VCLAW_REAPI_SEEDANCE_VIA") or "").strip().lower()
    if via != "treg":
        raise Refused("this door quotes and renders on the treg credential path only: export "
                      "VCLAW_REAPI_SEEDANCE_VIA=treg and TREG_TOKEN (the direct reAPI key has no machine-readable "
                      "rate card, so it cannot be quoted before the spend)", 3)
    if not (env.get("TREG_TOKEN") or "").strip():
        raise Refused("TREG_TOKEN is not set — `treg login` (or `treg login --token` for an agent) and export it", 3)
    if resolution:
        env["VCLAW_REAPI_SEEDANCE_RESOLUTION"] = resolution
    return env


# --------------------------------------------------------------------------
# the run (called by paid_take.py --route reapi-seedance)
# --------------------------------------------------------------------------

def run(args, plan: dict, job: dict, build: str, tmp_dir: str, *, next_draw, write_record, ledger_append) -> int:
    jid = job["id"]
    dest = clip_path(plan, job)
    env = treg_env(args.resolution or None)
    adapters = Adapters(resolve_main())

    # 1. the operator's approval covers THIS payload (the free driver's own gate)
    kept, refused = approval_gate(build, [(plan, job)], ROUTE)
    if refused or not kept:
        raise Refused("the approval does not cover this window as it is now — re-run preflight for THIS "
                      f"door (preflight_higgs.py --route {ROUTE}) and approve from your terminal", 3)
    contract = build_contract(plan, job, tmp_dir, args.resolution or None, bool(getattr(args, "sung_only", False)))

    # 2. 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 {CONTRACT_FILE} — "
               "the approval never saw this donor; 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)")

    # 3. an accepted take already on disk
    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)

    # 4. the quote — treg's live table + balance; nothing is uploaded to quote
    quote = adapters.quote_usd(contract, env)
    usd = float(quote["unitCost"]["amount"])
    balance = float(quote["balance"]["observed"]["amount"])
    print_contract(jid, contract, quote)
    say(f"{jid}: quoted ${usd:.3f} USD on {ROUTE} ({contract['seconds']} s at "
        f"{contract['payload']['executionProfile']['resolution']}, payload {contract['payloadHash'][:8]})")
    if usd > args.max_usd:
        raise Refused(f"the quote (${usd:.3f}) is over --max-usd ({args.max_usd:g}); nothing submitted", 3)
    if usd > balance:
        raise Refused(f"the quote (${usd:.3f}) exceeds the treg balance (${balance:.2f}); nothing submitted "
                      "(`treg topup` is the operator's call)", 3)
    if args.cost_only:
        say(f"{jid}: --cost-only — nothing submitted, nothing hosted")
        return 0

    # 5. the submit: the transport hosts the references and posts ONE task
    draw = next_draw(plan, jid)
    work = contract["payload"]["outputDir"]
    os.makedirs(work, exist_ok=True)
    for name in os.listdir(work):
        if name.endswith(".mp4"):
            os.replace(os.path.join(work, name), os.path.join(work, f"{name}.stale-{int(time.time())}"))
    reply = adapters.submit(contract["payload"], env)
    job_id = reply.get("externalJobId")
    raw = reply.get("rawResult") or {}
    # A create whose answer was lost comes back as a RETURNED job (the transport
    # never throws one away), so a job id here is not proof the task exists: the
    # scene indexes in `ambiguousScenes` may be running and billing, and reAPI
    # publishes no way to look them up. Neither claim the money nor poll a scene
    # that can only ever be pending.
    ambiguous = raw.get("ambiguousScenes") or []
    scenes_out = raw.get("submittedScenes") or [{}]
    first_scene = scenes_out[0]
    lost = next((s for s in scenes_out if s.get("sceneIndex") in ambiguous), first_scene) if ambiguous else first_scene
    submitted_at = time.strftime("%Y-%m-%dT%H:%M:%S")
    record = write_record(plan, jid, {
        "state": "accepted-by-provider" if job_id and not ambiguous else "unknown-submission",
        "providerJobId": job_id, "route": ROUTE, "draw": draw, "payloadHash": contract["payloadHash"],
        "donorSha": contract["donorSha"], "quotedUsd": usd, "submittedAt": submitted_at,
        "taskId": first_scene.get("taskId"),
        "warnings": raw.get("warnings") or [],
        **({"ambiguousScenes": ambiguous, "intentAt": lost.get("intentAt")} if ambiguous else {}),
        **({"sungOnly": {k: contract["take"][k] for k in ("t0", "t1", "sung", "seconds", "tail", "windowSeconds",
                                                          "audio", "variantHash", "changes")}}
           if contract.get("take") else {}),
    })
    if ambiguous:
        say(f"{jid}: SUBMISSION UNKNOWN — scene(s) {ambiguous} may exist and may be billing on {ROUTE}; "
            f"NOT retried, not polled. See {record}.")
        for warning in raw.get("warnings") or []:
            say(f"{jid}: transport: {warning}")
        return 4
    if not job_id:
        say(f"{jid}: submit returned no job id ({json.dumps(reply)[:160]}) — recorded as an UNKNOWN submission "
            f"in {record}; it is NOT retried (a task may have been created)")
        return 4
    say(f"{jid}: ACCEPTED job={job_id} (draw {draw}) — paid {ROUTE} ${usd:.3f}")
    for warning in raw.get("warnings") or []:
        say(f"{jid}: transport: {warning}")

    # 6. poll — the transport downloads the clip into `work` itself
    deadline = time.time() + args.poll_timeout
    while True:
        polled = adapters.poll(plan, work, job_id, env)
        if polled.get("status") in ("completed", "failed"):
            break
        if time.time() >= deadline:
            write_record(plan, jid, {"state": "timed-out"})
            say(f"{jid}: job {job_id} still pending after {args.poll_timeout} s — left running; re-run reads "
                f"{os.path.basename(record)} (nothing re-bought; `vclaw video execute-abandon` stops the wait)")
            return 4
        time.sleep(args.poll_interval)
    actual = (polled.get("actualCost") or {}).get("amount")
    note = None if actual is not None else "the provider reported no settled credits"
    ledger_append(build, f"{jid} paid take ({ROUTE}, quoted ${usd:.3f} USD, unit USD)", actual, note, route=ROUTE)
    write_record(plan, jid, {"state": polled.get("status"), "actualUsd": actual, "actualUsdNote": note,
                             "issues": polled.get("issues") or [], "completedAt": time.strftime("%Y-%m-%dT%H:%M:%S")})
    if polled.get("status") == "failed":
        # "refunded" is only true when the PROVIDER ended it. A scene abandoned
        # (or left ambiguous) also reads as failed here, and that task may still
        # be running and billing — saying refunded would be a false money claim.
        issues = polled.get("issues") or []
        abandoned = any("abandon" in str(i).lower() or "may be billing" in str(i).lower() for i in issues)
        settled = ("actual: unknown, and NOT refunded: the task was abandoned or its create answer was lost, "
                   "so it may still be running and billing") if abandoned else \
                  f"refunded by reAPI; actual: {actual if actual is not None else 'unknown'}"
        say(f"{jid}: the provider ended job {job_id} as failed — {'; '.join(str(i) for i in issues)[:300]} ({settled})")
        return 4
    outputs = [o for o in polled.get("outputs") or [] if o.get("kind") == "video"]
    if not outputs or not os.path.isfile(outputs[0].get("path", "")):
        say(f"{jid}: completed but no clip on disk — see {record}")
        return 4

    # 7. judge with the driver's own judge; keep on the driver's own rule
    superseded = os.path.join(plan["queueDir"], "superseded")
    os.makedirs(superseded, exist_ok=True)
    parked = os.path.join(superseded, f"{jid}-draw{draw}-paid-reapi.mp4")
    take = contract.get("take")
    raw_db = None
    if take:
        # The provider rendered the sung span only. Back to WINDOW shape before anything
        # reads it: the judge assumes clip t=0 is slice t=0 and the cutter assumes the
        # window's length. The raw clip stays beside it.
        raw_clip = os.path.join(superseded, f"{jid}-draw{draw}-paid-reapi-raw.mp4")
        shutil.move(outputs[0]["path"], raw_clip)
        raw_db = clip_mean_db(raw_clip)
        try:
            sung_only.pad_to_window(raw_clip, parked, take["t0"], take["windowSeconds"])
        except sung_only.NotApplicable as exc:
            write_record(plan, jid, {"clip": raw_clip, "state": "unpadded", "padError": str(exc)})
            say(f"{jid}: the sung-only take rendered but could not be padded to window shape — {exc} "
                f"(raw clip kept at {raw_clip}; nothing landed)")
            return 4
        write_record(plan, jid, {"clip": parked, "rawClip": raw_clip, "rawMeanDb": raw_db})
    else:
        shutil.move(outputs[0]["path"], parked)
        write_record(plan, jid, {"clip": parked})
    verdict = judge_landed(plan, job, parked)
    shape = verdict.get("shape")
    # A take that landed with a repairable SHAPE is kept and repaired in `slide` (a slide, a
    # cover, a retime), as lane_render.verify_landed keeps it — the same prompt drawn again
    # fails the same way, and this draw was paid for. ONE deliberate difference from that
    # rule: a "silent" take is NOT kept here. verify_landed keeps it with needs
    # rerender:redraw for the free lane's own resume pass to redraw; on a paid door a redraw
    # is money, so the clip is parked and the operator decides.
    silent_by_padding = bool(take and shape == "silent" and raw_db is not None and raw_db >= VOICE_MIN_MEAN_DB)
    keep = bool(verdict.get("ok")) or (shape in NEEDS_FOR_SHAPE and shape != "silent")
    if keep:
        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)
        # The judge's own `needs` wins when it names one (a straight-line "rhythm" is `slide`
        # for rate_fit, not a resplit) — the same precedence lane_render's render path uses.
        needs = (("ok" if not verdict.get("borderline") else "slide") if verdict.get("ok")
                 else (verdict.get("needs") or NEEDS_FOR_SHAPE[shape]))
        write_record(plan, jid, {"clip": dest, "verdict": verdict.get("why"), "needs": needs, "shape": shape,
                                 "borderline": bool(verdict.get("borderline"))})
        if verdict.get("borderline"):
            say(f"{jid}: BORDERLINE keep — {verdict.get('why')}")
        if not verdict.get("ok"):
            say(f"{jid}: KEPT WITH A SHAPE ({shape} → {needs}) — {verdict.get('why')}")
        cost = f"${actual:.3f}" if actual is not None else "cost unknown"
        say(f"{jid}: -> {dest}  ({verdict.get('why')}) — paid {ROUTE}, {cost}")
        return 0
    write_record(plan, jid, {"verdict": verdict.get("why"), "shape": shape,
                             "needs": "listen" if silent_by_padding else (verdict.get("needs") or "rerender:redraw"),
                             **({"silentByPadding": True, "rawMeanDb": raw_db} if silent_by_padding else {})})
    if silent_by_padding:
        say(f"{jid}: the padded take reads 'silent' but the RAW clip's voice is {raw_db:.1f} dB (floor "
            f"{VOICE_MIN_MEAN_DB:g}) — a padding artefact, not a redraw: listen to {os.path.basename(parked)}")
    say(f"{jid}: REJECTED draw {draw} — {verdict.get('why')}. (paid {ROUTE}; parked at {parked})")
    return 4


if __name__ == "__main__":
    print("reapi_take.py is reached through `paid_take.py --route reapi-seedance`", file=sys.stderr)
    raise SystemExit(2)
