#!/usr/bin/env python3
"""first_take.py — the page the operator judges ONE take on before the rest renders.

What it shows, for one landed window:
  * a filmstrip of the take, one frame a second, beside the identity portrait — the FACE
    question (is it him in every frame?);
  * the primed word measure against the slice the take sang to: rate (1.00 = on the
    track's speed), spread, median, drift — the SPEED question;
  * players for the take and for its slice.
The New Era film rendered fifteen windows before anyone looked at one; every window had
the same padded render and the same wrong face. Forty minutes and this page would have
caught both. It writes first-take.json too, so the runner's gate can quote the numbers.

Usage:
  first_take.py --plan build/plan.json --window w03 --clip build/queue/explore/clips/w03.mp4 \
                --portrait <face.png> --out build/first-take.html [--json build/first-take.json]
"""
from __future__ import annotations

import argparse
import html
import json
import os
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lane_nav import inject_nav
from lane_page import clock, front_padding_for, page as shell  # noqa: E402

RATE_OK = (0.97, 1.03)
SPREAD_OK_MS = 300


def filmstrip(clip: str, out: str, fps: int = 1, width: int = 160) -> bool:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", clip],
                       capture_output=True, text=True)
    try:
        n = max(1, int(float(r.stdout.strip()) * fps + 0.999))
    except ValueError:
        n = 8
    p = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", clip,
                        "-vf", f"fps={fps},scale={width}:-1,tile={n}x1", "-frames:v", "1", out],
                       capture_output=True)
    return p.returncode == 0 and os.path.isfile(out)


def with_song(clip: str, song: str, job: dict, out: str) -> bool:
    """The take's picture with THE SONG under it at this window — what the film will
    play. Judging sync from the take's own audio is circular (a model's mouth always
    matches its own voice); the operator asked for a "Both" (2026-08-31)."""
    start = float(job.get("startSec") or 0.0)
    p = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", clip, "-ss", f"{max(0.0, start):.3f}",
                        "-i", song, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac",
                        "-b:a", "160k", "-shortest", out], capture_output=True)
    return p.returncode == 0 and os.path.isfile(out)


def measure(plan: dict, job: dict, clip: str) -> dict:
    """The driver's own primed judge plus rate_fit's slope, both against the slice."""
    out: dict = {}
    try:
        import lane_render as lr
        v = lr.judge_landed(plan, job, clip)
        out["verdict"] = v.get("why", "")
        out["shape"] = v.get("shape")
        out["ok"] = bool(v.get("ok"))
        from transcribe_clips import whisper_words
        import rate_fit as rf
        lines = lr._window_lines(job)
        cache = os.path.join(plan["queueDir"], "verify-tx")
        lang = os.environ.get("SONG_LANGUAGE") or "en"
        want = whisper_words(job["voiceRef"], lr.VERIFY_MODEL, cache, language=lang, prompt=lines)["words"]
        got = whisper_words(clip, lr.VERIFY_MODEL, cache, language=lang, prompt=lines)["words"]
        d = lr.word_onset_drift(want, got)
        f = rf.fit(rf.pair_words(want, got))
        out.update({"pairs": d.get("pairs"), "medianMs": d.get("medianMs"), "spreadMs": d.get("spreadMs"),
                    "driftMs": d.get("driftMs"), "rate": f.get("rate"), "residualMs": f.get("residualMs"),
                    "sliceWords": " ".join(w["w"] for w in want), "takeWords": " ".join(w["w"] for w in got)})
    except Exception as exc:              # noqa: BLE001 — the page still shows the pictures
        out["error"] = f"{type(exc).__name__}: {exc}"
    r = out.get("rate")
    s = out.get("spreadMs")
    out["speedOk"] = (r is not None and RATE_OK[0] <= r <= RATE_OK[1]
                      and s is not None and s <= SPREAD_OK_MS)
    return out


def page(job: dict, clip: str, portrait: str, strip: str | None, m: dict, both: str | None = None,
         front_pad: float | None = None) -> str:
    def num(k, fmt="{}"):
        v = m.get(k)
        return "—" if v is None else fmt.format(v)
    speed = "ok" if m.get("speedOk") else "bad"
    spans = (job.get("vocal") or {}).get("spans") or []
    lines_txt = " / ".join(sp.get("text", "") for sp in spans if sp.get("text"))
    body = f"""<h2>1. The face — one frame a second, beside the portrait</h2>
<div class=row><div><img src="file://{html.escape(portrait)}" style="height:170px"><div class=muted>the identity reference</div></div>
<div class=strip>{f'<img src="file://{html.escape(strip)}">' if strip else '<i>filmstrip unavailable</i>'}</div></div>
<h2>2. The speed — the primed word measure against the slice it sang to</h2>
<table><tr><th>rate (1.00 = the track's speed)</th><th>spread</th><th>median</th><th>drift over the take</th><th>words paired</th><th>verdict</th></tr>
<tr><td class={speed}>{num('rate', '{:.3f}')}</td><td class={speed}>{num('spreadMs')} ms</td><td>{num('medianMs')} ms</td>
<td>{num('driftMs')} ms</td><td>{num('pairs')}</td><td class={speed}>{'ON SPEED' if m.get('speedOk') else 'NOT on speed'}</td></tr></table>
<p class=muted>bar: rate {RATE_OK[0]}–{RATE_OK[1]}, spread ≤ {SPREAD_OK_MS} ms. Driver's verdict: {html.escape(m.get('verdict') or m.get('error') or '')}</p>
<p><b>slice heard:</b> {html.escape(m.get('sliceWords',''))}<br><b>take heard:</b> {html.escape(m.get('takeWords',''))}</p>
<h2>3. Listen — did it sync?</h2>
<div class=row>
<div><video id=take controls preload="metadata" src="file://{html.escape(clip)}"></video><div class=muted>the take (its own audio)</div></div>
<div><video id=slice controls preload="metadata" src="file://{html.escape(job.get('voiceRef',''))}"></video><div class=muted>the slice it sang to</div></div>
{f'<div><video controls preload="metadata" src="file://{html.escape(both)}"></video><div class=muted><b>BOTH</b> — the take with the song under it (what the film plays)</div></div>' if both else ''}
</div>
<p><button id=bothbtn style="font:inherit;padding:8px 16px;border-radius:8px;border:0;background:#4b7bec;color:#fff;cursor:pointer">▶ Both</button>
<span class=muted> plays the take muted with the slice's audio, from the top</span></p>
<script>
document.getElementById('bothbtn').onclick = () => {{
  const v = document.getElementById('take'), a = document.getElementById('slice');
  v.pause(); a.pause(); v.currentTime = 0; a.currentTime = 0; v.muted = true;
  Promise.all([v.play(), a.play()]).catch(() => {{}});
  v.onended = () => {{ v.muted = false; }};
}};
</script>
<h2>4. Your word</h2>
<p>Face right and on speed → <code>echo "{{date}} your word" &gt; build/first-take-approved</code>, then re-run the runner and the rest renders.
Face wrong → fix the portrait and <code>--from plan</code>. Slow → the rule failed; stop and say so.</p>"""
    return shell(f"{html.escape(job['id'])} — the first take, before anything else renders",
                 f"{html.escape(job.get('styleId', ''))} · {clock(float(job.get('startSec') or 0), front_pad)} · "
                 f"{job.get('seconds')}s render · sung {job.get('sungSec', '?')}s · lines: {html.escape(lines_txt)}",
                 body, extra_css=".row{display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap}img{max-width:100%}"
                                 "video{width:270px}table{width:auto}")


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--window", required=True)
    ap.add_argument("--clip", required=True)
    ap.add_argument("--portrait", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--json", default="")
    ap.add_argument("--song", default="", help="hook.wav — builds the take-with-the-song player")
    a = ap.parse_args()
    plan = json.load(open(a.plan, encoding="utf-8"))
    job = next((j for j in plan.get("jobs", []) if j["id"] == a.window), None)
    if job is None:
        print(f"first_take: {a.window} is not in the plan", file=sys.stderr)
        return 2
    build = os.path.dirname(os.path.abspath(a.out))
    strip = os.path.join(build, f"first-take-{a.window}.jpg")
    if not filmstrip(a.clip, strip):
        strip = None
    m = measure(plan, job, a.clip)
    both = None
    if a.song and os.path.isfile(a.song):
        both = os.path.join(build, f"first-take-{a.window}-with-song.mp4")
        if not with_song(a.clip, a.song, job, both):
            both = None
    doc = page(job, a.clip, a.portrait, strip, m, both, front_padding_for(os.path.dirname(build)))
    try:
        doc = inject_nav(doc, build, "first-take")
    except Exception:                     # noqa: BLE001
        pass
    with open(a.out, "w", encoding="utf-8") as fh:
        fh.write(doc)
    if a.json:
        json.dump({"window": a.window, "clip": a.clip, "strip": strip, "withSong": both, **m}, open(a.json, "w", encoding="utf-8"), indent=1)
    print(f"first_take: {a.window} rate {m.get('rate')} spread {m.get('spreadMs')}ms "
          f"{'ON SPEED' if m.get('speedOk') else 'not on speed'} -> {a.out}", file=sys.stderr)
    return 0


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