#!/usr/bin/env python3
"""preflight_higgs.py — the contract for a Higgsfield batch, per WINDOW, before any spend.

WHY THIS EXISTS. Every guard this lane needed already existed in explore_queue.py
— including the one that matters most:

    plan job "w13" claims synced: true with no voiceRef.

w13 shipped at 0.00 lip-sync anyway, because the Higgsfield submits were made by
hand through the MCP and never went past that validator. Re-sent later WITH the
vocal attached it scored 0.96. The gate was written, and bypassed.

So this runs the same `load_plan` and refuses the same things, then emits the
exact per-window submit contract. `storyboard.html` is one card per STYLE — on a
25-window film that is 7 prompts approved and 25 jobs submitted. This is one card
per WINDOW, showing what will ACTUALLY go:

  * the payload — `lane_render.build_payload_doc`, the same function the driver
    calls, so the card and the submit cannot diverge;
  * the provider body — the adapter's own pure builders (`split_references`,
    `build_media_entries`, `compile_media_citations`, `build_params`,
    `submit_body`), with the upload slots marked as such. This is where the
    `<<<image_N>>>` / `<<<audio_1>>>` tokens, the model, `generate_audio` and
    the duration clamp come from, and the page shows them rather than a label;
  * the sung lines under the window (from build/vocal-brief.json), who sings
    them and how, with the OTHER performer's lines marked "lips closed, listening";
  * each reference with its pixel size and sha256[:8]; the slice, playable, with
    a "slice verified @ <startSec>s · corr <x>" badge from the same correlation
    `check_sync` uses — because a slice that kept its NAME across a re-plan and
    not its audio once drove a window 12 seconds off (the cache was keyed on
    duration).

The page header prints the contract's sha256[:8]. `spend_gate.py --approve --hash
<that>` binds the approval to these bytes and to each window's payload hash;
`lane_render.py` recomputes the hash from the payload it is about to send and
refuses any job that moved.

WHAT IT ALSO CHECKS, which the free lane does not need — THE CITATION. `defects.md`
records a render lost to this: substituting the plan's inline `@IMG_1`/`@VID_1` for
`<<<image_1>>>`/`<<<video_1>>>` buries the citation at character 1161, inside a
wardrobe description, and the voice is ignored — sync 0.261 against 0.901 for the
same window cited properly. Keep the inline marker; the adapter appends the
trailing one.

(An earlier version of this page labelled every card `mode omni_reference`. Nothing
sends that: the adapter's `submit_body` carries `params.model = "default"` — a MODE,
distinct from the model in the URL — and references ride in `medias[]`. The label
is gone; the body is shown instead.)

Usage:
  preflight_higgs.py --plan build/plan.json [--broll build/broll-plan.json]
                     [--vocal-brief build/vocal-brief.json] [--song build/hook.wav]
                     [--pronouns "he|she"] [--out build/submit-contract.json]
                     [--html build/submit-contract.html]
Exit 0 = every window may be submitted · 2 = the plan is not submittable.
"""
import argparse
import hashlib
import html
import importlib.util
import json
import os
import re
import struct
import subprocess
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import explore_queue as eq  # noqa: E402  (same directory, deliberately shared)
from lane_nav import inject_nav  # noqa: E402
from lane_page import page as shell  # noqa: E402

CONTRACT_CSS = """.hdr{background:#161a21;border:1px solid #262c36;border-radius:8px;padding:10px 14px;margin:0 0 18px;font-size:13px}
.hdr code{font-size:13px} .hdr .sha{color:#7ee2a8;font-weight:700;font-size:16px}
article{border-top:1px solid #222831;padding:18px 0}
h2{font-size:17px;margin:0 0 6px}
.meta{color:#9aa0a6;font-size:12.5px;margin-bottom:8px}
.refs{display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap;margin:6px 0 10px}
figure.ref{margin:0;font-size:12px} figure.ref b{display:block;margin-bottom:4px}
figure.ref img{height:170px;border-radius:6px;display:block}
figure.ref audio{display:block;width:320px} figure.ref figcaption{font-size:11px;color:#9aa0a6}
figure.ref figcaption code{font-size:10.5px;color:#9aa0a6}
pre.params{font-size:11px;color:#9aa0a6}
details{margin-top:8px} summary{cursor:pointer;color:#8ab4f8;font-size:12.5px}
table.sung{border-collapse:collapse;font-size:12.5px;margin:6px 0 4px}
table.sung td,table.sung th{padding:2px 10px 2px 0;text-align:left;vertical-align:top}
table.sung th{color:#9aa0a6;font-weight:600} table.sung tr.other td{color:#9aa0a6;font-style:italic}
.b{font-size:11px;font-weight:700;padding:2px 8px;border-radius:99px;background:#242a34;
color:#9aa0a6;vertical-align:middle} .b.sync{background:#16351f;color:#7ee2a8} .b.have{background:#1d3b2a;color:#8fe0a6;border-color:#2f6a45}
.b.ok{background:#16351f;color:#7ee2a8} .b.bad{background:#3a1717;color:#f28b82}
.b.warn{background:#3a2e12;color:#fdd663}
"""
from lane_render import build_payload_doc, payload_hash, prepare  # noqa: E402

# The trailing citation. The INLINE @IMG_1/@VID_1 markers stay exactly as make_plan
# wrote them — see the docstring.
VIDEO_TOKEN = "<<<video_1>>>"
AUDIO_TOKEN = "<<<audio_1>>>"
UPLOAD_SLOT = "<uploaded at submit>"


def check_citation(job: dict) -> list[str]:
    """Problems with how this job's prompt cites its references.

    make_plan writes the INLINE citations (`@IMG_1`, `@VID_1`) into the prose. The
    trailing `<<<audio_1>>>` is a submit-time token appended by the adapter, not
    stored in the plan — so its absence here is normal and is not what this checks.
    """
    prompt = job.get("prompt", "") or ""
    jid = job.get("id")
    problems = []
    if job.get("voiceRef") and "<<<audio_1>>>" not in prompt and "@VID_1" not in prompt:
        problems.append(
            f"{jid}: carries a voiceRef but the prompt never cites @VID_1. An "
            "attached-but-uncited media is accepted and IGNORED by the server, "
            "which looks exactly like a render that came back unsynced.")
    # TWO SPELLINGS OF THE SAME CITATION. make_plan writes `@IMG_1`; a hand-authored
    # plan (film #3's 20 Hanuman shots, written in the ai-film-director's direct-paste
    # form) writes `@image1` — which is the adapter's own documented syntax and is
    # compiled inline to <<<image_1>>> (compile_media_citations). Both bind the still;
    # refusing one of them refused all 20 shots for a spelling (2026-09-05).
    def cites(n: int) -> bool:
        return f"@IMG_{n}" in prompt or re.search(rf"(?<![A-Za-z0-9_])@image{n}(?!\d)", prompt, re.I) is not None
    if (job.get("identityRef") or job.get("_planIdentity")) and not cites(1):
        problems.append(f"{jid}: carries an identity still but never cites @IMG_1 (or @image1).")
    if job.get("identityRef2") and not cites(2):
        problems.append(f"{jid}: carries a second performer's still but never cites @IMG_2 (or @image2).")
    if job.get("identityRef3") and not cites(3):
        problems.append(f"{jid}: carries a third still (the second performer's portrait) but never cites @IMG_3 (or @image3).")
    if job.get("motionRef") and "@video1" not in prompt and "<<<video_1>>>" not in prompt:
        problems.append(f"{jid}: carries a motion donor but never cites @video1 — an uncited media is "
                        "accepted and IGNORED, and the take would copy no moves.")
    for bad, good in (("<<<image_1>>>", "@IMG_1"), ("<<<video_1>>>", "@VID_1")):
        if bad in prompt and good not in prompt:
            problems.append(
                f"{jid}: the inline {good} citation was replaced by {bad}. That buries "
                "the reference mid-prompt and the voice is ignored — measured at 0.261 "
                f"sync against 0.901 for the same window cited inline. Keep {good} "
                "where make_plan put it.")
    return problems


def submit_prompt(job: dict) -> str:
    """The prompt as the ADAPTER will cite it: the plan's prose plus the trailing token.

    Appended, never substituted. The inline @VID_1 stays where it is. (Kept for the
    card's fallback when the adapter cannot be imported; the real compiled prompt comes
    from the adapter's own `compile_media_citations`.)
    """
    prompt = (job.get("prompt", "") or "").rstrip()
    if not job.get("voiceRef"):
        return prompt
    if VIDEO_TOKEN in prompt or AUDIO_TOKEN in prompt:
        return prompt
    return f"{prompt} {AUDIO_TOKEN}"


# --------------------------------------------------------------------------
# the provider body, from the adapter's own builders
# --------------------------------------------------------------------------

def load_adapter():
    """engines/seedance-direct/adapter.py, imported for its PURE builders only.

    It is stdlib-only at import and performs no I/O until an action runs, so this
    is safe from the system python. Returns None (the card then says so) rather than
    failing the preflight — a missing engine is reported by lane_render, not here.
    """
    path = os.path.join(eq.repo_root(), "engines", "seedance-direct", "adapter.py")
    if not os.path.isfile(path):
        return None
    try:
        spec = importlib.util.spec_from_file_location("seedance_direct_adapter", path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
    except Exception:                       # noqa: BLE001 — the page degrades, never dies
        return None
    for name in ("split_references", "build_media_entries", "compile_media_citations",
                 "citation_tokens_for_medias", "build_params", "submit_body"):
        if not hasattr(mod, name):
            return None
    return mod


def provider_body(adapter, payload: dict) -> dict | None:
    """What action_submit would POST for this payload, with upload slots marked.

    Mirrors action_submit's sequence (adapter.py ~1500-1640): split the voice from
    the stills by referenceRole, build the media entries per role, cite every media
    in the prompt, pick the i2v model when any reference is attached, then
    build_params + submit_body. The media `data` objects are what the upload returns
    at submit time, so they are placeholders here — everything else is the real body.
    """
    if adapter is None:
        return None
    task = payload["tasks"][0]
    profile = payload["executionProfile"]
    stills, voices, _warn = adapter.split_references(
        task.get("referencePaths") or [], task.get("referenceRole"))
    medias = [{"role": "image", "data": {"type": "media_input", "url": UPLOAD_SLOT,
                                          "id": UPLOAD_SLOT, "source": os.path.basename(p)}}
              for p in stills]
    voice_medias = [{"type": "audio_input", "id": UPLOAD_SLOT,
                     "source": os.path.basename(p)} for p in voices]
    if task.get("motionReferencePath"):
        # action_submit inserts the donor BEFORE the voice so it cites <<<video_1>>>
        voice_medias.insert(0, {"type": "video_input", "id": UPLOAD_SLOT,
                                "source": os.path.basename(task["motionReferencePath"])})
    prompt = task.get("prompt") or ""
    model = None
    if voice_medias:
        entries, tokens = adapter.build_media_entries(videos=voice_medias)
        medias = medias + entries
        prompt = adapter.cite_in_prompt(prompt, tokens)
        model = adapter.MODEL_I2V
    if stills:
        model = adapter.MODEL_I2V
    prompt = adapter.compile_media_citations(prompt, adapter.citation_tokens_for_medias(medias))
    params = adapter.build_params(profile, prompt, task.get("durationSeconds"),
                                  medias=medias, model=model)
    body = adapter.submit_body(params)
    return {"endpoint": f"/jobs/v2/{params['model']}", "body": body}


# --------------------------------------------------------------------------
# the evidence on each card
# --------------------------------------------------------------------------

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 image_size(path: str) -> str:
    """WxH from the file header (PNG/JPEG), else ffprobe, else 'unmeasured'."""
    try:
        with open(path, "rb") as fh:
            head = fh.read(32)
            if head[:8] == b"\x89PNG\r\n\x1a\n":
                w, h = struct.unpack(">II", head[16:24])
                return f"{w}x{h}"
            if head[:2] == b"\xff\xd8":
                fh.seek(2)
                while True:
                    marker = fh.read(2)
                    if len(marker) < 2 or marker[0] != 0xFF:
                        break
                    if marker[1] in (0xC0, 0xC1, 0xC2):
                        fh.read(3)
                        h, w = struct.unpack(">HH", fh.read(4))
                        return f"{w}x{h}"
                    seg = fh.read(2)
                    if len(seg) < 2:
                        break
                    fh.seek(struct.unpack(">H", seg)[0] - 2, 1)
    except OSError:
        return "unmeasured"
    try:
        r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
                            "-show_entries", "stream=width,height", "-of", "csv=p=0", path],
                           capture_output=True, text=True, timeout=20)
        w, h = r.stdout.strip().split(",")[:2]
        return f"{w}x{h}"
    except Exception:                       # noqa: BLE001
        return "unmeasured"


def slice_badge(song: str | None, voice: str | None, start, seconds, mute_head: float = 0.0,
                mute_tail: float = 0.0) -> dict | None:
    """'slice verified @ <start>s · corr <x>' — the slice against the song at the window.

    This is the check that would have caught voice/w08.mp4: it correlated 1.00 with
    the song at 94.5 s and −0.04 at its planned 81.84 s, and every gate downstream
    measured the render against the wrong slice.
    """
    if not (song and voice and os.path.isfile(song) and os.path.isfile(voice)):
        return None
    if not isinstance(start, (int, float)) or not seconds:
        return None
    try:
        # ONE implementation, shared with plan_coherence #11 — including its rule that
        # the mute's own fade is not part of the comparison. This function used to
        # carry its own copy of the arithmetic and went on warning about a slice
        # #11 had just passed (baby-nimbooda w10, 2026-09-03).
        from plan_coherence import slice_offset_against_window
        corr, off = slice_offset_against_window(song, voice, float(start), float(seconds),
                                                mute_head, mute_tail)
    except Exception as exc:                # noqa: BLE001
        return {"corr": None, "offsetMs": None, "note": f"unmeasured ({exc})"}
    return {"corr": round(float(corr), 3), "offsetMs": int(off),
            "ok": float(corr) >= 0.95 and abs(int(off)) <= 80}


def load_brief(path: str | None) -> dict:
    if not path or not os.path.isfile(path):
        return {}
    try:
        doc = json.load(open(path, encoding="utf-8"))
    except (OSError, ValueError):
        return {}
    return {w.get("id"): w for w in doc.get("windows", []) if isinstance(w, dict)}


def gender_of(performer, pronouns: str) -> str | None:
    """The window's performer as the brief names voices — mirrors make_plan."""
    prons = [x.strip() or "he" for x in (pronouns or "he|she").split("|")]
    if performer == "both":
        return "both"
    idx = 1 if performer == "b" else 0
    pron = prons[idx] if len(prons) > idx else "he"
    return "female" if pron == "she" else "male" if pron == "he" else "lead"


def sung_lines(job: dict, brief_w: dict | None, pronouns: str) -> list[dict]:
    """Window-relative spans with who/how, and whether THIS performer mouths them."""
    src = (job.get("vocal") or {}).get("spans") or (brief_w or {}).get("spans") or []
    mine = gender_of(job.get("performer", "a"), pronouns)
    out = []
    for sp in src:
        who = sp.get("who")
        other = mine not in ("both", None) and who in ("male", "female") and who != mine
        # SAY WHAT THE PROMPT SAYS. This column read "mouths it" for a span the prompt
        # directs as lips-closed (a previous line's tail) and for the silent partner in a
        # two-face window — the operator read it and asked why (2026-08-23).
        if sp.get("partialHead"):
            label = "lips closed — the previous line's tail"
        elif sp.get("partialTail"):
            label = "continues in the next window — the shot ends as it begins"
        elif mine == "both" and who == "male":
            label = "only HIS mouth; hers closed"
        elif mine == "both" and who == "female":
            label = "only HER mouth; his closed"
        elif mine == "both":
            label = "both mouths"
        elif other:
            label = "lips closed, listening"
        else:
            label = "mouths it"
        out.append({"start": sp.get("start"), "end": sp.get("end"), "text": sp.get("text"),
                    "who": who, "how": sp.get("how"), "performer": label})
    return out


# --------------------------------------------------------------------------

def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--broll", help="broll-plan.json — its jobs ride the same approval")
    ap.add_argument("--vocal-brief", help="default <plan dir>/vocal-brief.json when present")
    ap.add_argument("--song", help="hook.wav for the slice badge; default <plan dir>/hook.wav")
    ap.add_argument("--styles", default="",
                    help="the styles register — a style's `setAlt` is the scrub variant's set")
    ap.add_argument("--pronouns", default=os.environ.get("PRONOUNS", "he|she"),
                    help="per performer (he|she), as make_plan takes them")
    ap.add_argument("--out", help="default <plan dir>/submit-contract.json")
    ap.add_argument("--html", help="default <plan dir>/submit-contract.html")
    ap.add_argument("--slice-check", default="", help="slice-check.json from slice_check.py: per-window "
                    "'heard' verdicts, shown as a badge on each card")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    base = os.path.dirname(os.path.abspath(args.plan))
    # The same validator the free lane uses (through lane_render.prepare, which adds the
    # slug/queueDir fields the payload needs). Route is checked there.
    plans = [prepare(args.plan)]
    if args.broll:
        plans.append(prepare(args.broll))
    plan = plans[0]
    brief = load_brief(args.vocal_brief or os.path.join(base, "vocal-brief.json"))
    song = args.song or os.path.join(base, "hook.wav")
    adapter = load_adapter()
    styles_by_id: dict = {}
    if args.styles and os.path.isfile(args.styles):
        try:
            styles_by_id = {s["id"]: s for s in json.load(open(args.styles, encoding="utf-8")).get("styles", [])}
        except (OSError, ValueError, KeyError):
            styles_by_id = {}
    from prompt_variants import scrub_set_clause

    problems: list[str] = []
    # THE STEM THE SLICES WERE CUT FROM MUST HAVE PASSED ITS CHECK. Under VOICE_SOURCE=stem
    # every voice slice is cut from build/stems/vocals.wav; stem_check.py measured it at the
    # stem stage and wrote stems/stem-check.json. A report that FAILED refuses the contract
    # (the slices sing to a bad stem); a missing or stale report is a warning, not a
    # refusal — a film separated before the gate existed still has its slices, and the
    # next stem stage writes the report (measure what runs, without breaking a live film).
    stem_jobs = [j for p in plans for j in p["jobs"]
                 if j.get("voiceRef") and (j.get("voiceSource") or p.get("voiceSource")) == "stem"]
    if stem_jobs:
        stem_path = os.path.join(base, "stems", "vocals.wav")
        report_path = os.path.join(base, "stems", "stem-check.json")
        report = None
        if os.path.isfile(report_path):
            try:
                report = json.load(open(report_path, encoding="utf-8"))
            except ValueError:
                report = None
        if report is None:
            print(f"preflight_higgs: WARNING — {len(stem_jobs)} slice(s) are cut from the vocal stem but "
                  f"stems/stem-check.json is not on disk; re-run the stem stage to measure it", file=sys.stderr)
        elif os.path.isfile(stem_path) and report.get("stemSha") and report["stemSha"] != sha256_file(stem_path):
            print("preflight_higgs: WARNING — stems/stem-check.json describes a different stem than the one on disk "
                  "(re-run the stem stage)", file=sys.stderr)
        elif report.get("passedAll") is False:
            failed = ", ".join(c["name"] for c in report.get("checks", []) if not c.get("passed"))
            problems.append(f"the vocal stem the slices are cut from FAILED its quality check ({failed}) — "
                            f"see stems/stem-check.json; re-separate it or set VOICE_SOURCE=mix")
    windows = []
    for pi, p in enumerate(plans):
        for job in p["jobs"]:
            identity = job.get("identityRef") or p.get("identityRef")
            problems.extend(check_citation({**job, "_planIdentity": identity}))
            work = os.path.join(p["queueDir"], "work", job["id"])
            try:
                payload = build_payload_doc(p, job, work)
            except FileNotFoundError as exc:
                problems.append(str(exc))
                continue
            task = payload["tasks"][0]
            refs = []
            for r in task["referencePaths"]:
                refs.append({"path": r, "sha256": sha256_file(r)[:8],
                             "kind": "voice" if r == os.path.abspath(job.get("voiceRef") or "") else "image",
                             "size": image_size(r) if not r.endswith((".mp4", ".wav", ".m4a")) else None})
            if task.get("motionReferencePath"):
                mr = task["motionReferencePath"]
                refs.append({"path": mr, "sha256": sha256_file(mr)[:8], "kind": "motion", "size": None})
            seconds = task["durationSeconds"]
            w = {
                "id": job["id"],
                "window": job.get("window"),
                "plan": "broll" if pi else "windows",
                "kind": job.get("kind") or ("broll" if pi else "phrase"),
                "section": job.get("section"),
                "styleId": job.get("styleId"),
                "startSec": job.get("startSec"),
                "endSec": (round(float(job["startSec"]) + float(seconds), 3)
                           if isinstance(job.get("startSec"), (int, float)) and seconds else None),
                "trimStartSec": job.get("trimStartSec"),
                "tailSec": job.get("tailSec"),
                "headSpill": job.get("headSpill"),
                "seconds": seconds,
                "synced": bool(job.get("synced")),
                "deferred": bool(job.get("deferred")),
                "aspect": p["aspect"],
                "resolution": p["resolution"],
                "identityRef": identity,
                "voiceRef": job.get("voiceRef"),
                "prompt": submit_prompt(job),
                "payload": payload,
                "payloadHash": payload_hash(payload),
                "references": refs,
                "sung": sung_lines(job, brief.get(job["id"]), args.pronouns),
                # ALREADY HAVE IT. A clip placed by the inventory pass (or landed by an
                # earlier run) means this card is not a render request: the driver will
                # re-verify the clip on disk and skip the lane. The operator sees that
                # on the contract instead of approving a job that never submits.
                "onDisk": _on_disk(p, job),
                # The slice is checked against what it was CUT FROM (plan.voiceWav: the mix
                # or the vocal stem), so a stem slice is not marked stale for lacking the bed.
                "voiceSource": (job.get("voiceSource") or p.get("voiceSource") or "mix") if job.get("voiceRef") else None,
                "sliceCheck": slice_badge(next((x for x in (job.get("voiceWav"), p.get("voiceWav"))
                                                if x and os.path.isfile(x)), song),
                                          job.get("voiceRef"), job.get("startSec"), seconds,
                                          float(job.get("muteHeadSec") or 0.0), float(job.get("muteTailSec") or 0.0)),
                "muteHeadSec": job.get("muteHeadSec"),
                "muteTailSec": job.get("muteTailSec"),
                **({"shotRef": job["shotRef"]} if job.get("shotRef") else {}),
            }
            body = provider_body(adapter, payload)
            w["params"] = body
            if body:
                w["prompt"] = body["body"]["params"]["prompt"]
            # THE SCRUB VARIANT — the one change draw 2 may make after a moderation
            # refusal (prompt_variants.py). Built here, shown under the card, hashed
            # into the same approval, so the driver swaps it in without a second act.
            if pi == 0 and job.get("prompt"):
                scrub, changes = scrub_set_clause(job["prompt"], styles_by_id.get(job.get("styleId")))
                if changes:
                    try:
                        vpayload = build_payload_doc(p, {**job, "prompt": scrub}, work)
                        w["variants"] = {"scrub": {"prompt": scrub, "changes": changes,
                                                   "payload": vpayload, "payloadHash": payload_hash(vpayload)}}
                    except FileNotFoundError:
                        pass
            # Only present on a two-performer plan, so a solo contract is unchanged.
            for key in ("identityRef2", "performer"):
                if job.get(key):
                    w[key] = job[key]
            windows.append(w)

    if problems:
        print("preflight_higgs: REFUSED — these windows are not submittable:",
              file=sys.stderr)
        for pr in problems:
            print(f"  {pr}", file=sys.stderr)
        print("  nothing was written.", file=sys.stderr)
        raise SystemExit(2)

    out = args.out or os.path.join(base, "submit-contract.json")
    n_broll = sum(1 for w in windows if w["plan"] == "broll")
    doc = {
        "schemaVersion": 2,
        "aspect": plan["aspect"],
        "resolution": plan["resolution"],
        "planPath": os.path.abspath(args.plan),
        "planMtime": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(os.path.getmtime(args.plan))),
        "adapter": "engines/seedance-direct/adapter.py" if adapter else None,
        "windows": windows,
    }
    # STABLE KEY ORDER: the approval binds to this file's sha, so two runs over the same
    # plan must produce the same bytes. (No timestamp inside — generated time is on the
    # page, not in the contract.)
    with open(out, "w", encoding="utf-8") as fh:
        json.dump(doc, fh, indent=2, sort_keys=True, ensure_ascii=False)
        fh.write("\n")
    sha = sha256_file(out)

    if args.slice_check and os.path.isfile(args.slice_check):
        heard = {r["id"]: r for r in json.load(open(args.slice_check, encoding="utf-8")).get("windows", [])}
        for w in doc["windows"]:
            if w["id"] in heard:
                w["heard"] = heard[w["id"]]
    html_path = args.html or os.path.join(base, "submit-contract.html")
    write_html(html_path, doc, sha, n_broll)

    synced = sum(1 for w in windows if w["synced"])
    bad_slices = [w["id"] for w in windows if (w.get("sliceCheck") or {}).get("ok") is False]
    if args.json:
        print(json.dumps({"windows": len(windows), "synced": synced, "out": out,
                          "contractSha": sha, "badSlices": bad_slices}, indent=2))
    else:
        print(f"preflight_higgs: {len(windows)} job(s) submittable · {synced} synced "
              f"· contract {sha[:8]}")
        print(f"  contract: {out}")
        print(f"  review:   {html_path}")
        if bad_slices:
            print(f"  WARNING: slice does not match the song at its window for "
                  f"{', '.join(bad_slices)} — rebuild before approving (plan_coherence #11)")


def _on_disk(plan: dict, job: dict) -> dict | None:
    queue = plan.get("queueDir") or ""
    clip = os.path.join(queue, "clips", f"{job['id']}.mp4")
    if not os.path.isfile(clip):
        return None
    note = os.path.join(queue, f"{job['id']}-reused.json")
    if os.path.isfile(note):
        try:
            rec = json.load(open(note, encoding="utf-8"))
            return {"clip": clip, "reusedFrom": rec.get("from"), "why": rec.get("why"),
                    "forced": bool(rec.get("forced"))}
        except (OSError, ValueError):
            pass
    return {"clip": clip, "reusedFrom": None, "why": "landed by an earlier run"}


def write_html(path: str, doc: dict, sha: str, n_broll: int) -> None:  # noqa: C901
    """One card per window: what will actually be sent, not a paraphrase."""
    n_win = len(doc["windows"]) - n_broll
    cards = []
    for w in doc["windows"]:
        # THE CONTRACT SHOWS THE REFERENCES, NOT THEIR PATHS. "Preview is the contract"
        # means the operator sees the face(s) and hears the slice that will be sent,
        # beside the prompt — a path is a paraphrase. (Operator, 2026-08-22: "for each
        # prompt the storyboard should have the image and audio file".)
        figs = []
        for i, r in enumerate(w.get("references", []), 1):
            src = html.escape("file://" + r["path"])
            if r["kind"] == "image":
                label = f"image {i}"
                tag = f'<img src="{src}" alt="{label}">'
                meta = f'{html.escape(str(r.get("size") or "unmeasured"))} · sha {r["sha256"]}'
                sr = w.get("shotRef") or {}
                if i == 1 and sr.get("srcFrame"):
                    # The keyframe came from THIS frame of the reference film: show the pair.
                    tag = (f'<img src="{html.escape("file://" + sr["srcFrame"])}" alt="source frame">'
                           f'<figcaption>source frame @ {sr.get("srcAt")}s · shot {sr.get("shotIndex")} '
                           f'{sr.get("shotStart")}–{sr.get("shotEnd")}s ({int(100 * float(sr.get("coverage") or 0))}% of the singing)</figcaption>'
                           + tag)
                    label = "image 1 — the shot's keyframe"
            elif r["kind"] == "motion":
                label = "motion donor (@video1, mute)"
                tag = f'<video muted controls preload="metadata" src="{src}"></video>'
                meta = f'sha {r["sha256"]}'
            else:
                label = "voice slice" + (f' · {html.escape(str(w.get("voiceSource")).upper())}'
                                         if w.get("voiceSource") else "")
                tag = f'<audio controls preload="none" src="{src}"></audio>'
                sc = w.get("sliceCheck")
                if sc and sc.get("corr") is not None:
                    cls = "ok" if sc.get("ok") else "bad"
                    meta = (f'<span class="b {cls}">slice verified @ {w.get("startSec")}s · '
                            f'corr {sc["corr"]:.2f} @ {sc["offsetMs"]:+d}ms</span> · sha {r["sha256"]}')
                else:
                    meta = f'<span class="b">slice unverified{(" — " + html.escape(sc["note"])) if sc else ""}</span> · sha {r["sha256"]}'
            figs.append(f'<figure class="ref"><b>{label}</b>{tag}'
                        f'<figcaption>{meta}<br><code>{html.escape(r["path"])}</code></figcaption></figure>')
        refs = '<div class="refs">' + "".join(figs) + "</div>"
        badge = ('<span class="b sync">lip-synced</span>' if w["synced"]
                 else '<span class="b">no vocal — shot only, no audio generated</span>')
        if w.get("deferred"):
            badge += ' <span class="b">DEFERRED — approved now, rendered only when the NEEDS report asks</span>'
        if w.get("performer"):
            badge += f' <span class="b">performer {html.escape(str(w["performer"]))}</span>'
        if (w.get("shotRef") or {}).get("moves"):
            badge += f' <span class="b">moves: {html.escape(str(w["shotRef"]["moves"]))}</span>'
        if w.get("muteHeadSec"):
            badge += (f' <span class="b">reference SILENT for its first {float(w["muteHeadSec"]):.1f}s — '
                      f'nothing to sing before this face\'s first word</span>')
        if w.get("heard"):
            h = w["heard"]
            if h.get("ok"):
                badge += (f' <span class="b sync">HEARD ✓ — the slice was transcribed: its lines match the card '
                          f'({h.get("lineCoverage", 0):.0%}), last word present, nothing in the silence</span>')
            else:
                badge += (f' <span class="b" style="background:#4a1d1d;color:#ff9a9a">HEARD ✗ — '
                          f'{html.escape("; ".join(h.get("problems", [])))}</span>')
        if w.get("muteTailSec"):
            badge += (f' <span class="b">reference SILENT from {float(w["muteTailSec"]):.1f}s — '
                      f'the next line belongs to the next window</span>')
        if w.get("onDisk"):
            od = w["onDisk"]
            src = os.path.basename(os.path.dirname(os.path.dirname(od["reusedFrom"]))) + "/" + os.path.basename(od["reusedFrom"]) if od.get("reusedFrom") else ""
            badge += (f' <span class="b have">ALREADY HAVE IT — not sent to the lane: '
                      f'{html.escape(str(od.get("why") or ""))}{(" · from " + html.escape(src)) if src else ""}</span>')
        if w.get("headSpill"):
            badge += f' <span class="b warn">head spill {w["headSpill"]}s of the previous line</span>'
        start = w.get("startSec")
        at = (f'{start:.2f}–{w["endSec"]:.2f}s' if isinstance(start, (int, float)) and w.get("endSec")
              else "?")
        pos = f'{at} · {w.get("seconds")}s · {html.escape(str(w.get("kind") or ""))}'
        if w.get("section"):
            pos += f' · {html.escape(str(w["section"]))}'
        lines = ""
        if w.get("sung"):
            rows = "".join(
                f'<tr class="{"other" if sp["performer"].startswith("lips") else ""}">'
                f'<td>{sp["start"]:.1f}–{sp["end"]:.1f}s</td><td>{html.escape(str(sp["who"]))} · {html.escape(str(sp["how"]))}</td>'
                f'<td>{html.escape(str(sp["text"]))}</td><td>{html.escape(sp["performer"])}</td></tr>'
                for sp in w["sung"] if isinstance(sp.get("start"), (int, float)))
            lines = f'<table class="sung"><tr><th>when</th><th>who</th><th>line</th><th>this performer</th></tr>{rows}</table>'
        elif w["plan"] != "broll":
            lines = '<div class="meta">nothing sung under this window — lips closed throughout</div>'
        variants = ""
        for vname, v in (w.get("variants") or {}).items():
            variants += (f'<details><summary>{html.escape(vname)} variant — draw 2 after a moderation '
                         f'refusal (approved with this card; payload {v["payloadHash"][:8]}) — '
                         f'{html.escape("; ".join(v.get("changes", [])))}</summary>'
                         f'<pre>{html.escape(v["prompt"])}</pre></details>')
        params = ""
        if w.get("params"):
            pj = json.dumps(w["params"], indent=1, ensure_ascii=False)
            params = (f'<details><summary>provider body — POST {html.escape(w["params"]["endpoint"])} '
                      f'(the adapter\'s own build_params/submit_body; upload slots marked)</summary>'
                      f'<pre class="params">{html.escape(pj)}</pre></details>')
        else:
            params = '<div class="meta">provider body not shown — adapter.py not importable here</div>'
        cards.append(f"""<article id="{html.escape(str(w['id']))}">
  <h2>{html.escape(str(w['id']))} {badge}</h2>
  <div class="meta">{pos} · {html.escape(str(w.get('styleId') or ''))}
    · {html.escape(doc['aspect'])} {html.escape(doc['resolution'])} · payload {w['payloadHash'][:8]}</div>
  {refs}
  {lines}
  <pre>{html.escape(w['prompt'])}</pre>
  {variants}
  {params}
</article>""")
    allowed = (f"ALL {n_win} windows" + (f" + {n_broll} B-roll" if n_broll else "")
               + " — narrow with --allow")
    body = f"""<div class="hdr">
  contract <span class="sha">{sha[:8]}</span> &nbsp;·&nbsp; generated {time.strftime('%Y-%m-%d %H:%M:%S')}
  &nbsp;·&nbsp; plan.json {html.escape(doc.get('planMtime') or '?')}<br>
  <b>Approving submits:</b> {html.escape(allowed)}<br>
  From <b>your own terminal</b> (an agent session is refused):<br>
  <code>python3 skills/rap-avatar-mv/scripts/spend_gate.py --build-dir '{html.escape(os.path.dirname(os.path.abspath(path)))}' --approve --hash {sha[:8]}</code>
</div>
{''.join(cards)}
"""
    open(path, "w", encoding="utf-8").write(shell(
        f"Submit contract — {len(doc['windows'])} jobs",
        "Exactly what will be sent, per window: the payload the driver builds and the body the adapter posts. "
        "Approve this before spending; one card per style is not enough to approve twenty-five jobs.",
        body, extra_css=CONTRACT_CSS))
    inject_nav(path)


if __name__ == "__main__":
    main()
