#!/usr/bin/env python3
"""explore_queue.py — the free-lane plan VALIDATOR and provenance writer.

History, because the name still says "queue": this began as a supervisor over
`vclaw video batch-submit` / `batch-monitor`. That transport is gone — `batch-submit`
now compiles into the durable cinema queue and writes no `batch-queue.json`, and
`batch-monitor` is deprecated (#498) — and the rap lane never reached the free engine
through it anyway (`submitBatch` bypassed the adapter; two films died at that stage).
Rendering is `lane_render.py`, which drives the adapter's own SUBMIT/POLL contract
through the shared lane (`make-rap-mv.sh --from render-all`). What survives here is
what the lane still leans on:

  * `load_plan` — the plan.json contract and every guard it grew: the route must
    PROVE its free engine (`free_engine_available`), a synced window needs a voiceRef,
    no keyframe references, one video reference, aspect declared. `lane_render`,
    `make_broll_plan` and `preflight_higgs` import it rather than re-implementing it.
  * `build_manifest` — plan → the batch-manifest shape the TS layer understands
    (kept for the reference/paid paths that still read it).
  * `write_provenance` — `provenance.json` {realpath(clip): {jobId, window, styleId,
    synced, voiceRef, clip, submittedAt}}, consumed by index_library.py /
    select_cut.py so `synced` stays CARRIED rather than guessed from the picture.
  * `repo_root` — the checkout this script belongs to (a snapshot copy resolves to
    itself; see rap-avatar-runner-snapshot.test.ts).

`plan.json` (skill-authored; this schema is the contract):

    {
      "schemaVersion": 1,
      "lane": "explore",                  // names build/queue/<lane>/
      "route": "seedance-direct",         // default AND the only free value
      "aspect": "9:16",                   // REQUIRED — no default
      "resolution": "720p",               // optional (720p | 1080p)
      "seconds": 10,                      // optional per-plan default duration
      "projectDir": "/abs/projects/<slug>",   // optional; used to derive queueDir
      "queueDir": "/abs/.../build/queue/explore",  // optional; --out wins
      "workspaceRoot": "/abs/videoclaw",  // optional
      "identityRef": "/abs/portrait.png", // optional plan-wide default
      "jobs": [
        {"id": "w05", "prompt": "...", "window": 5, "styleId": "neon-rain",
         "seconds": 9.4, "synced": true,
         "identityRef": "/abs/portrait.png",       // the FACE (image)
         "voiceRef": "/abs/voice/w05.mp4"}         // black-frame + track (video)
      ]
    }

Both refs are split by EXTENSION downstream: the still becomes the image reference
and the `.mp4` the video/audio one — the whole free-lip-sync trick. They must never
be `keyframe`, which would open the clip on the still.

Usage (validation only — nothing here submits, polls or spends):
  explore_queue.py --plan <plan.json> [--out <dir>]
      Validate the plan, compile the manifest, prove the free engine, print a JSON
      summary and the render command. Exit 0 valid · 2 refused.

To render:  make-rap-mv.sh <pack> <slug> --from render-all   (lane_render.py)
To see what landed / is rendering:  render_board.py, needs_report.py
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import sys
import time
from datetime import datetime, timezone

PROVENANCE_FILE = "provenance.json"
MANIFEST_FILE = "batch-manifest.json"
# Legacy queue state. Only queue dirs written by the retired batch transport have one;
# write_provenance still reads it when present so an old dir keeps its real submit times.
QUEUE_STATE_FILE = "batch-queue.json"

# The Runway account is suspended, so seedance-direct through the VENDORED
# Higgsfield engine is the free lane now. "Free" is CONDITIONAL there in a way it
# never was for Runway: resolveAdapterCommand only routes seedance-direct to the
# in-tree engine when it is bootstrapped. Since 2026-09-16 an unbootstrapped engine
# REFUSES (execution_blocked_by_readiness) instead of falling through to the PAID
# native transport, which needs VCLAW_SEEDANCE_DIRECT_NATIVE=1 — but a shell that
# HAS that flag set still reaches the paid transport, and lane_render re-draws a
# refused window, so running there would re-buy the film draw by draw. The route is
# not trusted by name, it is proven free before anything renders (see
# free_engine_available).
DEFAULT_ROUTE = "seedance-direct"
# RUNWAY IS GONE (removed 2026-08-15). The account was suspended on 2026-08-10 and
# every path here refused it by name anyway; what remained were its ASSUMPTIONS, and
# those were still doing damage. The clip-length cap in make_plan.py was Runway's 10s
# explore limit applied to every route, so a film on Higgsfield seedance_2_5 — which
# the engine's own table gives (4, 20) — was refused above 10s. On a 112-second song
# that is fourteen renders instead of six on a single-slot lane.
#
# Removing it also makes this guard STRICTER rather than looser: seedance-direct must
# PROVE its free engine, and everything else is refused as paid. There is no longer a
# route that is free by name.
ROUTES = ("dreamina-useapi", "seedance-direct")
# Real routes this lane does not drive — distinct from a typo, and from a
# route that is merely paid. Flow/Veo has its own submit path (native-veo / flow-r2v)
# and does not go through the explore queue at all.
ELSEWHERE_ROUTES = {
    "veo-useapi": "Flow/Veo renders through its own path (native-veo, flow-r2v), "
                  "not through this lane's plan",
    "higgsfield-cli": "the PAID Higgsfield API pool is driven one window at a time by "
                      "paid_take.py (PAID_WINDOWS in the pack, inside render-all), never by "
                      "lane_render — keep the plan on seedance-direct",
    "reapi-seedance": "Seedance 2.5 via reAPI is the OTHER paid door: one window at a time by "
                      "paid_take.py --route reapi-seedance (PAID_ROUTE=reapi-seedance + "
                      "PAID_WINDOWS in the pack), never by lane_render — keep the plan on "
                      "seedance-direct",
}
ASPECTS = ("16:9", "9:16", "1:1")
RESOLUTIONS = ("720p", "1080p")
# Mirrors the transport's own classifyReferences(). Kept in sync deliberately:
# the split is by extension there, so a ref whose extension we misread here is a
# ref that silently lands in the wrong provider slot.
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
VIDEO_EXT = {".mp4", ".mov", ".webm", ".avi", ".mkv"}


def now_iso() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat()


def log(msg: str) -> None:
    print(f"[{time.strftime('%H:%M:%S')}] explore_queue: {msg}", file=sys.stderr, flush=True)


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


def repo_root() -> str:
    # skills/rap-avatar-mv/scripts/this.py -> repo root
    return os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def explicit_paid_seedance_transport(env: dict | None = None) -> bool:
    """Has someone explicitly chosen the PAID Seedance API?

    Mirrors explicitPaidSeedanceTransport in src/video/execution-adapter.ts,
    including its falsey spellings. Plain truthiness is wrong here: "0" is truthy
    in Python, so `VCLAW_SEEDANCE_DIRECT_NATIVE=0` would read as free on the TS
    side and as paid here — the direction that buys the batch.
    """
    env = os.environ if env is None else env
    value = (env.get("VCLAW_SEEDANCE_DIRECT_NATIVE") or "").strip().lower()
    return value not in ("", "0", "false", "no", "off")


def free_engine_available(env: dict | None = None) -> tuple[bool, str]:
    """Is seedance-direct going to resolve to the FREE in-tree engine?

    Mirrors hasFreeInTreeSeedanceEngine in src/video/execution-adapter.ts. Kept in
    step by hand, deliberately: getting this wrong means a re-offer pass buys the
    whole batch again, so it fails closed and says which piece is missing.
    """
    env = os.environ if env is None else env
    if explicit_paid_seedance_transport(env):
        return False, ("VCLAW_SEEDANCE_DIRECT_NATIVE is set, which selects the PAID "
                       "native transport")
    engine = os.path.join(repo_root(), "engines", "seedance-direct")
    venv = os.path.join(engine, ".venv", "bin", "python")
    profile = env.get("HIGGS_VCLAW_PROFILE") or os.path.join(engine, ".cloak-profile")
    if not os.path.exists(venv):
        return False, f"the engine venv is missing ({venv}) — run its bootstrap.sh"
    if not os.path.exists(profile):
        return False, f"the browser profile is missing ({profile}) — run its bootstrap.sh"
    return True, ""


def is_url(ref: str) -> bool:
    return ref.startswith("http://") or ref.startswith("https://")


def ref_kind(ref: str) -> str:
    # Unknown extensions count as images, exactly as classifyReferences does, so the
    # budget checked here is the budget the transport will actually apply.
    ext = os.path.splitext(ref.split("?")[0])[1].lower()
    return "video" if ext in VIDEO_EXT else "image"


# --------------------------------------------------------------------------
# plan.json -> the repo's batch manifest
# --------------------------------------------------------------------------

def load_plan(path: str) -> dict:
    if not os.path.isfile(path):
        die(f"plan not found: {path}")
    try:
        plan = json.load(open(path, encoding="utf-8"))
    except Exception as exc:
        die(f"plan is not valid JSON ({path}): {exc}")
    if not isinstance(plan, dict):
        die(f"plan must be a JSON object: {path}")
    if plan.get("schemaVersion") != 1:
        die(f"plan schemaVersion must be 1, got: {json.dumps(plan.get('schemaVersion'))}")

    route = plan.get("route", DEFAULT_ROUTE)
    if route in ELSEWHERE_ROUTES:
        # A real route, driven by a different door. Worth its own message because
        # `veo-useapi` is the documented DEFAULT route for every other lane in this
        # repo, so an operator setting it here is following the house rule, not
        # making a typo — and "must be one of ..." reads like their route was
        # misspelt rather than deliberately out of scope.
        die(f"route {route!r} is real, but this lane cannot drive it: "
            f"{ELSEWHERE_ROUTES[route]}\n"
            "  The rap lane renders and re-draws windows on a free route. "
            "Set ROUTE=\"seedance-direct\" in the pack for this lane.")
    if route not in ROUTES:
        die(f"plan route must be one of {', '.join(ROUTES)}, got: {json.dumps(route)}")
    # FREE ROUTE ONLY, and this is a credit guard, not a preference. lane_render
    # re-draws a refused or parked window (moderation is random, so up to MAX_DRAWS per
    # window), which is only safe on a route where a draw costs nothing. A paid route
    # under the same loop buys every draw. So the route must PROVE it is free.
    if route == "seedance-direct":
        ok, why = free_engine_available()
        if not ok:
            die(f"route 'seedance-direct' would NOT use the free Higgsfield engine: {why}.\n"
                "  It would fall through to the PAID native transport, and the lane re-draws "
                "windows — so every draw would be bought. Bootstrap the engine "
                "(engines/seedance-direct/bootstrap.sh, then import_cookies.py), or take a "
                "paid window deliberately through paid_take.py (PAID_WINDOWS in the pack).")
    else:
        # No route is free by name any more. seedance-direct proves its engine above;
        # everything else is paid, and the lane re-draws windows.
        die(f"route {route!r} is a PAID route and this lane only renders on free routes: "
            "its re-draws would buy every attempt. Take a paid window deliberately through "
            "paid_take.py (PAID_WINDOWS in the pack), or queue it with `vclaw video cinema-work "
            "--confirm-spend`.")

    # aspect is REQUIRED and has no default here. Defaulting it would re-create the
    # exact silent failure this script exists to prevent, one level up.
    aspect = plan.get("aspect")
    if aspect not in ASPECTS:
        die("plan must declare \"aspect\" (one of " + ", ".join(ASPECTS) + ") — it is the "
            "film's aspect and there is NO safe default: the batch layer falls back to "
            "16:9, so a 9:16 film that omits it gets landscape clips after hours of queueing")
    resolution = plan.get("resolution", "720p")
    if resolution not in RESOLUTIONS:
        die(f"plan resolution must be one of {', '.join(RESOLUTIONS)}, got: {json.dumps(resolution)}")

    jobs = plan.get("jobs")
    if not isinstance(jobs, list) or not jobs:
        die("plan requires a non-empty \"jobs\" array")

    plan_ref = plan.get("identityRef")
    seen: set[str] = set()
    for index, job in enumerate(jobs):
        if not isinstance(job, dict):
            die(f"plan job {index} must be an object")
        jid = job.get("id")
        if not isinstance(jid, str) or not jid.strip():
            die(f"plan job {index} requires a non-empty string \"id\"")
        # The id becomes clips/<id>.mp4 on disk, so refuse anything that would
        # escape the queue dir or produce a path the downstream index cannot match.
        if not all(c.isalnum() or c in "._-" for c in jid) or jid.startswith("."):
            die(f"plan job \"{jid}\": id must be [A-Za-z0-9._-] (it becomes clips/<id>.mp4)")
        if jid in seen:
            die(f"plan has a duplicate job id: \"{jid}\"")
        seen.add(jid)
        if not isinstance(job.get("prompt"), str) or not job["prompt"].strip():
            die(f"plan job \"{jid}\" requires a non-empty string \"prompt\"")
        if "keyframe" in job:
            die(f"plan job \"{jid}\" sets \"keyframe\": this lane cites the identity still as a "
                "REFERENCE, never as the first frame. buildBatchPayload prioritises characterRefs "
                "and would drop the keyframe silently — remove it, or use identityRef.")
        seconds = job.get("seconds", plan.get("seconds"))
        if seconds is not None and not (isinstance(seconds, (int, float)) and seconds > 0):
            die(f"plan job \"{jid}\" seconds must be a positive number when present")

        refs = []
        identity = job.get("identityRef", plan_ref)
        if identity is not None:
            if not isinstance(identity, str) or not identity.strip():
                die(f"plan job \"{jid}\" identityRef must be a non-empty string when present")
            refs.append(identity)
        # A `both` window carries a second STILL. It is an image, so the one-video
        # guard below is unaffected; but a second face with no first is a plan error.
        identity2 = job.get("identityRef2")
        if identity2 is not None:
            if not isinstance(identity2, str) or not identity2.strip():
                die(f"plan job \"{jid}\" identityRef2 must be a non-empty string when present")
            if identity is None:
                die(f"plan job \"{jid}\" has identityRef2 but no identityRef — the second "
                    "performer's still cannot be the only face")
            refs.append(identity2)
        identity3 = job.get("identityRef3")
        if identity3 is not None:
            if not isinstance(identity3, str) or not identity3.strip():
                die(f"plan job \"{jid}\" identityRef3 must be a non-empty string when present")
            if identity2 is None:
                die(f"plan job \"{jid}\" has identityRef3 but no identityRef2")
            refs.append(identity3)
        voice = job.get("voiceRef")
        if voice is not None:
            if not isinstance(voice, str) or not voice.strip():
                die(f"plan job \"{jid}\" voiceRef must be a non-empty string when present")
            refs.append(voice)
        for ref in refs:
            if not is_url(ref) and not os.path.isfile(ref):
                die(f"plan job \"{jid}\": reference not found on disk: {ref}")
        # THE MOTION DONOR is its own field (never a reference path): a second video in
        # referencePaths would silently drop the voice. It needs a voice to be a clock for.
        motion = job.get("motionRef")
        if motion is not None:
            if not isinstance(motion, str) or not motion.strip():
                die(f"plan job \"{jid}\" motionRef must be a non-empty string when present")
            if not os.path.isfile(motion):
                die(f"plan job \"{jid}\": motion reference not found on disk: {motion}")
            if voice is None:
                die(f"plan job \"{jid}\" has a motionRef but no voiceRef — a donor with no clock")
        videos = [r for r in refs if ref_kind(r) == "video"]
        images = [r for r in refs if ref_kind(r) == "image"]
        # The provider body carries ONE video reference. A second is not
        # rejected — it is silently dropped, which on a lip-sync job means the clip
        # renders against the wrong track and only check_sync.py ever notices.
        if len(videos) > 1:
            die(f"plan job \"{jid}\" has {len(videos)} video references; the provider body carries "
                "exactly one (videoAssetId) and drops the rest silently")
        if videos and not images:
            die(f"plan job \"{jid}\" has a voice video but no identity still — that renders a "
                "stranger's face mouthing your track. Give it an identityRef.")
        if job.get("synced") and not voice:
            die(f"plan job \"{jid}\" claims synced: true with no voiceRef. `synced` is CARRIED "
                "into provenance.json and believed downstream; a clip with no voice reference "
                "cannot be synced to its bar.")
    return {"schemaVersion": 1, "route": route, "aspect": aspect, "resolution": resolution,
            "jobs": jobs, "seconds": plan.get("seconds"), "identityRef": plan_ref,
            "verifyWords": plan.get("verifyWords", True),
            # Preflight must compare each voice slice with its actual source.
            # Dropping these fields made stem slices fall back to the full mix,
            # falsely failing the slice check despite unchanged timings.
            "voiceSource": plan.get("voiceSource"), "voiceWav": plan.get("voiceWav"),
            "pronouns": plan.get("pronouns"),
            "lane": plan.get("lane", "explore"), "queueDir": plan.get("queueDir"),
            "projectDir": plan.get("projectDir"), "workspaceRoot": plan.get("workspaceRoot")}


def build_manifest(plan: dict) -> dict:
    """plan.json -> the batch-queue manifest the TS layer already understands.

    The one translation that matters: identity still + voice video both go into
    `characterRefs`, never `keyframe`. characterRefs are delivered with
    `referenceRole: 'character'` and are never used as the first frame.
    """
    default_seconds = plan.get("seconds") if isinstance(plan.get("seconds"), (int, float)) else 10
    jobs = []
    for job in plan["jobs"]:
        refs = []
        identity = job.get("identityRef", plan.get("identityRef"))
        if identity:
            refs.append(identity)
        if job.get("identityRef2"):
            refs.append(job["identityRef2"])
        if job.get("identityRef3"):
            refs.append(job["identityRef3"])
        if job.get("voiceRef"):
            refs.append(job["voiceRef"])
        entry = {"id": job["id"], "prompt": job["prompt"]}
        if refs:
            entry["characterRefs"] = refs
        seconds = job.get("seconds")
        if isinstance(seconds, (int, float)):
            entry["seconds"] = seconds
        jobs.append(entry)
    return {
        "schemaVersion": 1,
        "route": plan["route"],
        "defaults": {"seconds": default_seconds,
                     "aspectRatio": plan["aspect"],
                     "resolution": plan["resolution"]},
        "jobs": jobs,
    }


# --------------------------------------------------------------------------
# preconditions
# --------------------------------------------------------------------------

# --------------------------------------------------------------------------
# provenance
# --------------------------------------------------------------------------

def write_provenance(out_dir: str, plan: dict) -> None:
    """{realpath(clip): {jobId, window, styleId, synced, voiceRef, clip, submittedAt}}.

    This is what lets `synced` be CARRIED to the cut instead of inferred from the
    picture — an open mouth in a contact strip proves nothing about WHICH words it
    is forming.

    KEYED BY REALPATH OF THE CLIP, not by job id: index_library.py finds a clip on
    disk and has only its path to look up with — it never sees the queue's job ids.
    realpath on both sides so a symlinked queue dir (/tmp -> /private/tmp on macOS)
    cannot make the two spellings of the same file miss each other. The clip does not
    exist yet at submit time, which is fine — realpath does not require existence, and
    the landed file arrives at exactly this path (clipPathForJob).

    `voiceRef` is a BOOL by consumer contract — "did this render carry a voice
    reference at all", which is the half select_cut.py tests. The path is kept
    alongside as `voiceRefPath` so the audit trail is not lost.

    submittedAt comes from the queue state (the real submit time), and an existing
    entry's submittedAt is never overwritten.
    """
    state = read_json(os.path.join(out_dir, QUEUE_STATE_FILE))
    submitted = {}
    if isinstance(state, dict):
        for job in state.get("jobs", []):
            if isinstance(job, dict) and isinstance(job.get("id"), str):
                submitted[job["id"]] = job.get("submittedAt")
    path = os.path.join(out_dir, PROVENANCE_FILE)
    existing = read_json(path)
    record = existing if isinstance(existing, dict) else {}
    for job in plan["jobs"]:
        jid = job["id"]
        clip = os.path.realpath(os.path.join(out_dir, "clips", f"{jid}.mp4"))
        prior = record.get(clip) if isinstance(record.get(clip), dict) else {}
        record[clip] = {
            "jobId": jid,
            "window": job.get("window"),
            "styleId": job.get("styleId"),
            "synced": bool(job.get("synced")),
            "voiceRef": bool(job.get("voiceRef")),
            "voiceRefPath": job.get("voiceRef"),
            "clip": clip,
            "submittedAt": prior.get("submittedAt") or submitted.get(jid),
            # the content key a landed clip is pinned to (lane_render.stale_prompt). STAMPED
            # ONLY WHEN THIS JOB WAS (RE)SUBMITTED: this writer runs for EVERY job in the
            # plan at the end of EVERY pass, so a re-plan that rewrote a prompt used to
            # re-stamp clips that never rendered under it — and the next pass parked three
            # good cutaways as "rendered from an older prompt" (Baby Nimbooda, 2026-09-05,
            # twice). A record keeps its sha until a NEW submission replaces the clip.
            "promptSha": (prior.get("promptSha")
                          if prior.get("promptSha") and prior.get("submittedAt") == submitted.get(jid)
                          else hashlib.sha256((job.get("prompt") or "").encode("utf-8")).hexdigest()[:12]),
        }
        if job.get("identityRef2"):
            record[clip]["identityRef2"] = job["identityRef2"]
        if job.get("identityRef3"):
            record[clip]["identityRef3"] = job["identityRef3"]
    with open(path, "w", encoding="utf-8") as handle:
        json.dump(record, handle, indent=2)
        handle.write("\n")


def validate(plan_path: str, out: str | None) -> dict:
    """The old supervisor's preconditions, minus the transport: a plan that passes here
    is one lane_render will accept. Refuses (exit 2) on the same faults it always did."""
    plan = load_plan(plan_path)
    out_dir = out or plan.get("queueDir") or (
        os.path.join(plan["projectDir"], "build", "queue", plan["lane"]) if plan.get("projectDir") else None)
    if not out_dir:
        die("no queue dir: pass --out, or give the plan a \"queueDir\" or \"projectDir\"")
    manifest = build_manifest(plan)
    # Re-assert the aspect on the COMPILED manifest, not just the plan: it is the value
    # the provider sees, and one edit of build_manifest away from the 16:9 default.
    got = (manifest.get("defaults") or {}).get("aspectRatio")
    if got != plan["aspect"]:
        die(f"compiled manifest defaults.aspectRatio is {got!r} but the film's aspect is "
            f"{plan['aspect']!r} — refusing a plan that would render the wrong shape")
    free, why = free_engine_available()
    return {
        "ok": True,
        "plan": os.path.abspath(plan_path),
        "queueDir": os.path.abspath(out_dir),
        "route": plan["route"],
        "aspect": plan["aspect"],
        "resolution": plan.get("resolution"),
        "jobs": len(plan["jobs"]),
        "synced": sum(1 for j in plan["jobs"] if j.get("synced")),
        "freeEngine": {"available": free, "detail": why},
        "render": "make-rap-mv.sh <pack> <slug> --from render-all  (lane_render.py drives the adapter "
                  "through the shared lane; this script validates, it does not submit)",
    }


def main() -> None:
    ap = argparse.ArgumentParser(
        description="validate a free-lane plan.json (the plan contract lane_render renders from); "
                    "nothing here submits, polls or spends")
    ap.add_argument("--plan", help="skill-authored plan.json (see the module docstring)")
    ap.add_argument("--out", help="queue dir; defaults to the plan's queueDir/projectDir")
    ap.add_argument("--status", action="store_true",
                    help="RETIRED: the batch queue this polled no longer exists; use render_board.py / "
                         "needs_report.py for what landed and what is still rendering")
    args = ap.parse_args()
    if args.status:
        die("--status is retired: the batch-monitor queue it read is gone (batch-submit compiles into "
            "the cinema queue; batch-monitor is deprecated). For the lane's state run "
            "render_board.py or needs_report.py; lane_render.py writes the per-window verdicts.")
    if not args.plan:
        die("nothing to do: pass --plan <plan.json>")
    print(json.dumps(validate(args.plan, args.out), indent=2))
    raise SystemExit(0)


if __name__ == "__main__":
    main()
