#!/usr/bin/env python3
"""slice_review.py — ONE page with every voice slice the model will hear, for the operator.

THE PAGE THIS FILM LACKED. The operator found the cause of a whole night's slow takes by
listening to one slice and reading one number ("the audio is 5 seconds, the one you
uploaded is 7"): the render was longer than the singing. Nothing had put those two
numbers side by side. This page does, per window, BEFORE the contract:

    lyric · sung seconds · silence at the head · silence at the tail · render seconds ·
    render ÷ sung · a player for the exact file the model will hear

and it prints the ratio in red when a window is padded past plan_coherence's bar, so the
operator can refuse a plan by eye as well as by gate.

Usage:
  slice_review.py --plan build/plan.json --vocal-brief build/vocal-brief.json \
                  --out build/slices.html
"""
from __future__ import annotations

import argparse
import html
import json
import os
import sys

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

MAX_PAD_S = 1.3     # mirrors plan_coherence #12


def rows_for(plan: dict, brief: dict) -> list[dict]:
    spans = {w["id"]: w for w in brief.get("windows", [])}
    out = []
    for j in plan.get("jobs", []):
        if not j.get("voiceRef"):
            continue
        w = spans.get(j["id"], {})
        own = [s for s in w.get("spans", []) if s.get("text")
               and not s.get("partialHead") and not s.get("partialTail")]
        secs = float(j.get("seconds") or 0)
        head = float(j.get("trimStartSec") or 0.0)
        tail = float(j.get("tailSec") or 0.0)
        sung = j.get("sungSec")
        if sung is None and own:
            sung = max(float(s["end"]) for s in own) - min(float(s["start"]) for s in own)
        sung = float(sung or 0.0)
        out.append({
            "id": j["id"], "styleId": j.get("styleId", ""),
            "lines": [s["text"] for s in own],
            "seconds": secs, "sung": round(sung, 2), "head": round(head, 2), "tail": round(tail, 2),
            "ratio": round(secs / sung, 2) if sung else None,
            "pad": round(secs - sung, 2), "voiceRef": j["voiceRef"],
            "startSec": float(j.get("startSec") or 0.0),
        })
    return out


def render(rows: list[dict], slug: str, front_pad: float | None = None) -> str:
    parts = [f"""<table><tr><th>window</th><th>lyric</th><th class="num">sung s</th><th class="num">head s</th><th class="num">tail s</th>
<th class="num">render s</th><th class="num">render ÷ sung</th><th>the slice the model hears</th></tr>"""]
    for r in rows:
        cls = "ok" if r["pad"] <= MAX_PAD_S and (r["ratio"] or 0) <= 1.2 else ("warn" if r["pad"] <= MAX_PAD_S else "bad")
        lyric = "".join(f"<div>{html.escape(t)}</div>" for t in r["lines"]) or "<i>(no lines placed)</i>"
        parts.append(
            f"<tr><td><b>{r['id']}</b><br><span class=sid>{html.escape(r['styleId'])}<br>{clock(r['startSec'], front_pad)}</span></td>"
            f"<td class=lyric>{lyric}</td><td class=num>{r['sung']:.2f}</td><td class=num>{r['head']:.2f}</td>"
            f"<td class=num>{r['tail']:.2f}</td><td class=num>{r['seconds']:g}</td>"
            f"<td class='num {cls}'>{r['ratio'] if r['ratio'] is not None else '—'}</td>"
            f"<td><audio controls preload=\"metadata\" src=\"file://{html.escape(r['voiceRef'])}\"></audio><br>"
            f"<span class=sid>{html.escape(os.path.basename(r['voiceRef']))}</span></td></tr>")
    worst = max((r["ratio"] or 0) for r in rows) if rows else 0
    parts.append(f"</table><p class=lead>{len(rows)} sung window(s) · worst render ÷ sung {worst:.2f}</p>")
    body = "".join(parts)
    lead = ("Each row is one render. <b>Render</b> is the clip length the model is asked for; <b>sung</b> is the "
            "singing inside it (first word to last word); <b>head</b>/<b>tail</b> are the silence either side, which the "
            "assembly cuts off. The model spreads its performance across the whole render, so <b>render ÷ sung</b> is how "
            "much slower it will sing — 1.10 is fine, 1.35 is a whole different tempo. Rows past " + f"{MAX_PAD_S:g}" + "&nbsp;s of "
            "padding are red and the plan gate refuses them. Play each slice: it should be silence, the lines, silence.")
    return page(html.escape(slug) + " — what the model will hear, window by window", lead, body, slug=slug,
                extra_css=".lyric{color:var(--ink)}.lyric div{white-space:nowrap}.sid{color:var(--ink3);font-size:12px}")


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--vocal-brief", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--json", default="")
    a = ap.parse_args()
    plan = json.load(open(a.plan, encoding="utf-8"))
    brief = json.load(open(a.vocal_brief, encoding="utf-8"))
    rows = rows_for(plan, brief)
    slug = plan.get("projectSlug") or os.path.basename(os.path.dirname(os.path.dirname(os.path.abspath(a.plan))))
    doc = render(rows, slug, front_padding_for(os.path.dirname(os.path.dirname(os.path.abspath(a.out)))))
    try:
        doc = inject_nav(doc, os.path.dirname(os.path.abspath(a.out)), "slices")
    except Exception:                     # noqa: BLE001 — the nav is decoration
        pass
    with open(a.out, "w", encoding="utf-8") as fh:
        fh.write(doc)
    if a.json:
        json.dump({"windows": rows}, open(a.json, "w", encoding="utf-8"), indent=1)
    bad = [r for r in rows if r["pad"] > MAX_PAD_S]
    print(f"slice_review: {len(rows)} window(s) -> {a.out}"
          + (f" · {len(bad)} padded past {MAX_PAD_S:g}s: {', '.join(r['id'] for r in bad)}" if bad else ""),
          file=sys.stderr)
    return 0


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