#!/usr/bin/env python3
"""line_windows.py — cut the film into windows that START ON SUNG LINES, on WHOLE seconds.

Fixed-length windows start mid-phrase: the slice opens on nothing, or on the tail
of the previous line, and the mouth has to open on cue with no cue. SKILL.md called
cutting on lyric lines "the biggest win still on the table (NOT BUILT)"; with a
vocal brief on disk (every lyric line timed), it is a list comprehension.

Rules (operator-approved 2026-08-22, whole-second revision the same day):
  * a wordless HEAD (intro) is split into whole-second windows of its own, from 0 up to
    floor(first line start) — they are shot-led, the planner sends them with no voice;
  * every other window starts on floor(lineStart) — a WHOLE second — and its length is
    an integer in [--min, --max]: it extends line by line until >= --min and stops before
    exceeding --max; when the next line start is beyond --max it takes the last one
    <= --max. So `trimStartSec = 0` on every window but the last: the clip IS the window,
    nothing is slid back, nothing is trimmed off its head;
  * the LAST window runs to the song's (fractional) end and keeps the slide-back:
    seconds = ceil(end - start), startSec = end - seconds, the head trimmed. A tail too
    short to be a valid clip is folded into the previous window instead;
  * because start = floor(lineStart), up to 1 s of the PREVIOUS line's tail rides at the
    head of a phrase window. `headSpill` reports it per window (the contract page shows
    it; make_plan's per-window direction already tells the other performer to listen).
make_plan.py --windows consumes the list.

Usage: line_windows.py --brief build/vocal-brief.json --song-seconds 107.52 \\
           --out build/windows.json [--min 8] [--max 14]
"""
from __future__ import annotations

import argparse
import json
import math
import sys

MIN_CLIP = 4            # mirrors make_plan.MIN_CLIP: the route's shortest valid clip
INTRO_MIN = MIN_CLIP
PHRASE_GAP_S = 2.0   # phrase mode: a real instrumental break, not a breath
GAP_SPLIT_S = 0.8        # a silence this long inside a synced window becomes a window edge
SUNG_HEAD_MIN_S = 0.25   # less than this of the previous line in the head counts as a silent head    # a head shorter than one valid clip is folded into the first phrase


def _tile_whole(t0: int, t1: int, hi: int, kind: str) -> list[dict]:
    """Whole-second chunks of [t0, t1], none longer than hi, as even as possible."""
    out = []
    span = t1 - t0
    if span <= 0:
        return out
    n = max(1, math.ceil(span / hi))
    # floor, so the LAST chunk carries the remainder: an intro that grows by a second
    # when a later line anchor moves keeps its earlier chunks (and their landed clips).
    step = max(MIN_CLIP, math.floor(span / n))
    if step * (n - 1) + hi < span:       # remainder would not fit the last chunk
        step = math.ceil(span / n)
    t = t0
    for k in range(n):
        b = t1 if k == n - 1 else min(t1, t + step)
        if b > t:
            out.append({"start": float(t), "end": float(b), "kind": kind})
        t = b
    return out


def build(starts: list[float], song_end: float, lo: float, hi: float,
          ends: list[float] | None = None, whos: list[str] | None = None,
          pins: list[int] | None = None, tags: list[str] | None = None,
          phrases: bool = False,
          lines_per_window: int = 0) -> list[dict]:
    """Windows over [0, song_end] that open on whole seconds and on lyric lines.

    `ends` (optional, parallel to `starts`) lets headSpill be measured from the previous
    line's real end; without it the spill is the fraction of a second before the line.
    """
    lo, hi = int(math.ceil(lo)), int(math.floor(hi))
    triples = sorted((s, (ends[i] if ends and i < len(ends) else None),
                      (whos[i] if whos and i < len(whos) else None))
                     for i, s in enumerate(starts) if s is not None)
    pairs = [(t[0], t[1]) for t in triples]
    who_of = {t[0]: t[2] for t in triples}
    tag_of = {st: (tags[i] if tags and i < len(tags) else None)
              for i, st in enumerate(s0 for s0 in starts if s0 is not None)}
    starts = [p[0] for p in pairs]
    line_end = {p[0]: p[1] for p in pairs}
    out: list[dict] = []
    # THE ANCHOR SECOND of a line. floor(lineStart) normally — up to a second of the
    # PREVIOUS line's tail rides at the head, which is sung, so the mouth is already
    # moving when the clip opens. But when the second before the line is SILENT (the
    # song's intro, or a real gap) the nearest whole second is used instead: a synced
    # slice that opens on ~1 s of silence came back with the model following the voice
    # (corr 0.85) yet starting 1.2 s late — and the morning's silent-head windows lagged
    # +400…+1875 ms. Rounding costs at most half a second of the first syllable.
    # AND A HEAD IN ANOTHER VOICE IS TREATED LIKE SILENCE. w05 (his rapped verse) opened on
    # 0.6 s of HER line's tail, directed "not him: lips closed, listening" — the model
    # ignored it and started his rap at frame 0, landing 600 ms early. A solo line whose
    # previous line is a different voice anchors on the nearest second: a 0.4 s cut into
    # his first word beats a 0.6 s early mouth. Same voice, or a both/duet line, keeps
    # the floor (continuous singing: the mouth is already moving when the clip opens).
    anchors, prev_end, prev_who = [], None, None
    for st, en in pairs:
        fl = int(math.floor(st))
        # a head is "silent" when less than SUNG_HEAD_MIN_S of the previous line rides in it
        silent_head = prev_end is None or prev_end - fl < SUNG_HEAD_MIN_S
        who = who_of.get(st)
        other_voice = (who in ("male", "female") and prev_who is not None and prev_who != who)
        # …AND SO IS A HEAD IN THE SAME VOICE. w03 opened 0.76 s into the previous line's
        # last word ("…chamak"); the model cannot start mid-word, started the phrase fresh
        # at frame 0, and landed 1.2 s early (corr 0.78). Every timing failure measured
        # on the first line-cut film was a head that was not the line's own first word.
        # So: the NEAREST whole second, always — at worst a quarter-second cut into the
        # first word, never a spill. (silent_head / other_voice kept for the record.)
        del silent_head, other_voice
        anchors.append(int(round(st)))
        prev_end = en if en is not None else st
        prev_who = who
    # 1. the wordless head, whole-second chunks from 0 up to the first line's anchor
    head = anchors[0] if starts else 0
    if head >= INTRO_MIN:
        out.extend(_tile_whole(0, head, hi, "intro"))
        s = head
    else:
        s = 0           # a tiny head rides inside the first phrase window
    folded = s == 0 and bool(starts)
    floors = anchors

    def opens_on_line(at: int) -> float | None:
        if at == 0 and folded:
            return starts[0]
        for st, fl in zip(starts, floors):
            if fl == at:
                return st
        # a pinned edge within a second of a line start still opens on that line
        if pins and at in pins:
            near = [st for st in starts if abs(st - at) <= 1.0]
            if near:
                return near[0]
        return None

    # A GAP INSIDE A SYNCED WINDOW IS A CUT POINT. w03 packed two hook lines around a
    # 1 s gap; the model sang them back-to-back and landed 1.4 s EARLY on two draws
    # (the silent-head case lands late — same cause, opposite sign: the model does not
    # reproduce silence). So a window ends at the first line anchor that follows a gap
    # of >= GAP_SPLIT_S, even if that leaves it shorter than --min (never shorter than
    # MIN_CLIP: a sub-4 s fragment is merged forward instead).
    gap_anchor = set()
    for (st, en), nxt in zip(pairs, pairs[1:]):
        # A CHANGE OF VOICE is a cut point too (her verse -> his verse at 52.6 s): a
        # window that straddles it opens or closes on the other performer's words.
        if who_of.get(st) is not None and who_of.get(nxt[0]) is not None \
                and who_of[st] != who_of[nxt[0]]:
            gap_anchor.add(anchors[starts.index(nxt[0])])
        # A CHANGE OF SECTION on the sheet ([Verse] -> [Bridge]) is a cut point too.
        if tag_of.get(st) is not None and tag_of.get(nxt[0]) is not None \
                and tag_of[st] != tag_of[nxt[0]]:
            gap_anchor.add(anchors[starts.index(nxt[0])])
        if en is None:
            continue                       # no line ends known: a gap cannot be measured
        # In phrase mode a breath between two lines of one voice and one section is
        # singing, not a break: only a real instrumental gap (>= PHRASE_GAP_S) cuts.
        if nxt[0] - en >= (PHRASE_GAP_S if phrases else GAP_SPLIT_S):
            gap_anchor.add(anchors[starts.index(nxt[0])])

    # PINNED EDGES: a clip already on disk fits the window they bound, so the cut must
    # land there whatever the line anchors say (operator: use what we have first).
    for pin in (pins or []):
        gap_anchor.add(int(pin))
    # 2. phrase windows, integer start -> integer end chosen among later line starts
    while song_end - s > 0.05:
        cands = sorted({fl for fl in floors if fl > s} | {int(p) for p in (pins or []) if p > s})
        pick = None
        gap_cut = next((e for e in cands if e in gap_anchor and e - s >= MIN_CLIP), None)
        first_ok = next((e for e in cands if e - s >= lo), None)
        # WHOLE PHRASES: run to the LAST line anchor that fits the cap (never past a gap,
        # a voice change or a section change), instead of the first one past --min.
        # w07 cut the bridge couplet in half — "Coat utaar…" in one clip, "Sunehri
        # chhat…" in the next — and the operator heard the slice stop mid-thought
        # (2026-08-23). One voice, one phrase group, one window.
        if phrases:
            reach = [e for e in cands if e - s <= hi and e - s >= MIN_CLIP]
            if reach:
                first_ok = reach[-1]
        if lines_per_window > 0:
            # ONE LINE PER WINDOW (or N): the published lip-sync guidance is 5-10 words a
            # line and "split a speech across cuts rather than long monologues that
            # drift"; the packed 2-3 line windows sang their second line at the wrong
            # rhythm (w11, 2026-08-29). Cut at the N-th line anchor after this start —
            # extended forward only while the clip would be shorter than MIN_CLIP, so
            # a short line merges with the next rather than making an invalid clip.
            anchors_ahead = [e for e in cands if e > s]
            nth = None
            for k, e in enumerate(anchors_ahead):
                if k + 1 >= lines_per_window and e - s >= MIN_CLIP:
                    nth = e
                    break
            if nth is not None:
                first_ok = nth
        # a reachable cut point wins over --min: never straddle a gap or a voice change.
        # In N-lines mode a cut point may only SHORTEN the window: the New Era film
        # (2026-08-29) asked for one line per window and got 10-12 s phrases, because
        # the [Hook] -> [Verse] section anchor ten seconds on replaced the one-line cut.
        if gap_cut is not None and gap_cut - s <= hi and (
                lines_per_window == 0 or first_ok is None or gap_cut < first_ok):
            first_ok = gap_cut
        elif gap_cut is not None and first_ok is not None and first_ok > gap_cut:
            first_ok = gap_cut
        if first_ok is not None:
            if first_ok - s <= hi:
                pick = first_ok
            else:
                # the nearest line start >= lo is already too far: the last one <= hi,
                # as long as it is still a valid clip; otherwise a forced cut at hi
                below = [e for e in cands if e < first_ok and e - s <= hi and e - s >= MIN_CLIP]
                pick = below[-1] if below else s + hi
        tail = song_end - s
        if pick is None:
            # no later line start reaches --min: this is the last window, or an outro
            if tail <= hi:
                out.append({"start": float(s), "end": round(song_end, 3), "kind": "phrase"
                            if opens_on_line(s) is not None else "outro"})
                break
            # the tail is too long for one clip: cut at the LAST line anchor that leaves a
            # valid final window (<= hi), so the end is a sung window and not a scrap
            fits = [e for e in cands if song_end - e <= hi and e - s >= MIN_CLIP]
            pick = fits[-1] if fits else s + hi
        if pick >= song_end - 0.05:
            out.append({"start": float(s), "end": round(song_end, 3), "kind": "phrase"
                        if opens_on_line(s) is not None else "outro"})
            break
        out.append({"start": float(s), "end": float(pick),
                    "kind": "phrase" if opens_on_line(s) is not None else "outro"})
        s = pick

    # 3. headSpill — how much of the previous line's tail rides at the head
    for w in out:
        spill = 0.0
        if w["kind"] == "phrase":
            st = opens_on_line(int(w["start"]))
            prev = [x for x in starts if x < st]
            if prev:
                pe = line_end.get(prev[-1])
                spill = max(0.0, (min(pe, st) if pe is not None else st) - w["start"])
        w["headSpill"] = round(spill, 3)
    return out


def finish(wins: list[dict], lo: float, hi: float) -> list[dict]:
    """Clip fields. Every window but the last is whole-second: trim 0, startSec = start.

    The last window ends at the fractional song end: seconds = ceil(end - start) (capped
    at --max), startSec = end - seconds (slid back into the previous window, whose tail
    the assembly skips via trimStartSec). A tail shorter than MIN_CLIP is folded into the
    previous window when that keeps it <= --max; otherwise the clip is MIN_CLIP long.
    """
    hi = int(math.floor(hi))
    if len(wins) >= 2:
        last, prev = wins[-1], wins[-2]
        x = round(last["end"] - last["start"], 3)
        if math.ceil(x) < MIN_CLIP and (last["end"] - prev["start"]) <= hi:
            prev["end"] = last["end"]
            wins = wins[:-1]
    for k, w in enumerate(wins):
        x = round(w["end"] - w["start"], 3)
        # An integral last window is only "whole-second" when it is also a VALID clip:
        # a 1 s tail after a full 14 s window is integral, and taking this branch gave
        # it seconds=1 — which make_plan's validator then refused, so the plan stage
        # died on any song whose length was a whole number (1 in 10 of them; hook.json
        # rounds durationSec to 0.1 s).
        if k < len(wins) - 1 or (x == int(x) and x >= MIN_CLIP):
            w["seconds"] = int(round(x))
            w["trimStartSec"] = 0.0
            w["startSec"] = float(w["start"])
        else:
            secs = max(MIN_CLIP, min(hi, math.ceil(x)))
            w["seconds"] = secs
            w["trimStartSec"] = round(secs - x, 3)
            w["startSec"] = round(w["end"] - secs, 3)
    return wins


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--brief", required=True)
    ap.add_argument("--phrases", action="store_true",
                    help="whole phrase groups: a window runs to the last line that fits --max "
                         "within one voice and one sheet section, not the first past --min")
    ap.add_argument("--lines", type=int, default=0,
                    help="N lyric lines per window (1 = one line per window; a line shorter "
                         "than 4 s merges with the next). Overrides --phrases. WINDOW_LINES in the pack")
    ap.add_argument("--song-seconds", type=float, required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--min", type=float, default=8.0)
    ap.add_argument("--max", type=float, default=14.0)
    ap.add_argument("--pin", default="", help="comma-separated whole seconds that MUST be window "
                    "edges (a clip on disk already fits the window they bound)")
    args = ap.parse_args()
    doc = json.load(open(args.brief, encoding="utf-8"))
    placed = [l for l in doc["lines"] if l.get("start") is not None]
    starts = [l["start"] for l in placed]
    ends = [l.get("end") for l in placed]
    whos = [l.get("who") for l in placed]
    tags = [l.get("tag") for l in placed]
    if not starts:
        sys.exit("line_windows: the brief placed no lyric line in time")
    pins = [int(x) for x in args.pin.split(",") if x.strip()]
    wins = finish(build(starts, args.song_seconds, args.min, args.max, ends, whos, pins, tags,
                        args.phrases and not args.lines, args.lines),
                  args.min, args.max)
    json.dump({"schemaVersion": 1, "windows": wins}, open(args.out, "w", encoding="utf-8"), indent=2)
    print(f"line_windows: {len(wins)} window(s) -> {args.out}", file=sys.stderr)
    for n, w in enumerate(wins):
        print(f"  w{n:02d}  {w['kind']:<6} {w['start']:>7.2f}–{w['end']:>7.2f}  "
              f"({w['end'] - w['start']:.2f}s covered, clip {w['seconds']}s from {w['startSec']:.2f}s, "
              f"trim {w['trimStartSec']:.2f}s, head spill {w['headSpill']:.2f}s)", file=sys.stderr)


if __name__ == "__main__":
    main()
