#!/usr/bin/env python3
"""song_breakdown.py — Gemini listens to the song and proposes the beat sheet; whisper keeps the clock.

WHAT IT PROPOSES, per sung phrase: the SECTION (Intro / Verse / Chorus / Bridge / Bols /
Outro), the CHARACTER and playback SINGER, a translation, and a CUE (the vocal delivery and
the screen action at that moment). This is the semantic half of a film that copies a real
music video — the part the operator types by hand into the lyric sheet before anything
else can run.

WHAT IT NEVER DOES. Doctrine, learned the hard way:
  * THE CLOCK IS WHISPER'S. Gemini's timestamps on media are ±1 s (the toolkit's own
    benchmark: ±800–1500 ms on video); every phrase `start` is SNAPPED to the nearest
    whisper onset within --snap-s (default 1.5) and the raw value kept as `geminiStart`.
    An unsnappable phrase is marked `snapped: false`, never trusted for a cut.
  * THE SHEET RULES THE SINGER. `character`/`singer` are ADVISORY — written to the
    artifact and shown in the HTML beside singers.json's answer with a "differs" flag,
    exactly like `detect_voices`; nothing applies them. A pitch median once put her face
    on his vocal for seven draws; a language model's guess gets the same standing.
  * THE TEXT IS THE SHEET'S. With --brief the request carries the sheet's own lines and
    the answer must return them verbatim; the proposal only ever attaches section / who /
    translation / cue TO a line, it does not rewrite one.
  * NOTHING SPENDS. The `cue` (choreography per line) goes to build/song-cues-proposed.json
    in the SHOT_MOVES {wNN: sentence} shape the operator may pass under SHOT_REFS=1 — the
    one path that already replaces a sung performance line — never auto-applied.

WHERE IT HELPS. A film with no sheet yet: --scaffold-lyrics writes a DRAFT
references/lyrics.txt in the pack's `[Section - Who]` format (vocal_brief.parse_lyrics'
TAG_RE) with a [DRAFT …] tag line saying so (the sheet has no comment syntax); it refuses to
touch an existing sheet (exit 4).

Audio goes INLINE (mono 64 kbps mp3, ~0.5 MB/min); a --video ≤ 18 MB goes inline too, a
larger one through the Files API (resumable upload, poll ACTIVE). Plumbing (keys, cooldown,
the call) is dance-breakdown's — its unit is a shot, this one's is a phrase.

Usage:
  song_breakdown.py --project <P> [--stem build/stems/vocals.wav | --video references/source.mp4]
                    [--brief build/vocal-brief.json] [--transcript build/transcript.json]
                    [--singers build/singers.json] [--windows build/windows.json]
                    --out build/song-breakdown.json [--html build/song-breakdown.html]
                    [--scaffold-lyrics references/lyrics.txt] [--model gemini-3.5-flash]
                    [--snap-s 1.5] [--dry-run]
Exit 0 · 2 bad inputs · 3 no Gemini key · 4 --scaffold-lyrics would overwrite a sheet.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import html
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, "..", "..", "dance-breakdown", "scripts"))

DEFAULT_MODEL = "gemini-3.5-flash"
INLINE_CAP_BYTES = 18 * 1024 * 1024
FILES_ENDPOINT = "https://generativelanguage.googleapis.com/upload/v1beta/files"
FILES_GET = "https://generativelanguage.googleapis.com/v1beta/files/"
SECTIONS = ("Intro", "Verse", "Pre-Chorus", "Chorus", "Hook", "Bridge", "Instrumental", "Bols", "Interlude", "Outro")


def say(msg: str) -> None:
    print(f"song_breakdown: {msg}", file=sys.stderr)


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 read_json(path: str | None):
    if not path or not os.path.isfile(path):
        return None
    try:
        return json.load(open(path, encoding="utf-8"))
    except ValueError:
        return None


# ---------------------------------------------------------------------------------------
# pure pieces (tested without a network)
# ---------------------------------------------------------------------------------------
def snap_to_onsets(phrases: list[dict], onsets: list[float], tol_s: float = 1.5) -> list[dict]:
    """Every phrase start moves to the nearest whisper onset within tol_s; the Gemini value is
    kept as geminiStart. Ends tile to the next snapped start (the last keeps its own). A phrase
    with no onset in reach keeps its start and is marked snapped=false — never trusted for a cut.
    An end that OVERLAPS the next start is pulled back to it; an end before the next start is a
    gap and stays one (tiling ends to the next onset is exactly what whisper does wrong)."""
    ons = sorted(float(o) for o in onsets)
    out = []
    for p in sorted(phrases, key=lambda p: float(p.get("start", 0.0))):
        q = dict(p)
        g = float(q.get("start", 0.0))
        q["geminiStart"] = round(g, 2)
        best = min(ons, key=lambda o: abs(o - g)) if ons else None
        if best is not None and abs(best - g) <= tol_s:
            q["start"], q["snapped"] = round(best, 3), True
        else:
            q["start"], q["snapped"] = round(g, 3), False
        out.append(q)
    for a, b in zip(out, out[1:]):
        if a.get("end") is None or float(a["end"]) > float(b["start"]):
            a["end"] = float(b["start"])
    return out


def section_tag(section: str, who: str) -> str:
    """The sheet's `[Section - Who]` tag from a proposal's section and character."""
    sec = (section or "Verse").strip()
    sec = next((s for s in SECTIONS if s.lower() in sec.lower()), sec.title()) if sec else "Verse"
    w = (who or "").lower()
    # WHOLE WORDS: "Lata Mangeshkar" contains "man", "Sadhana" contains "he" — a substring test
    # labelled Lata Mangeshkar a male voice. Unknown stays "Lead": the sheet decides, not a guess.
    def has(*words: str) -> bool:
        return any(re.search(rf"\b{k}\b", w) for k in words)
    voice = ("Both" if has("both", "duet", "ensemble", "chorus", "all", "everyone") else
             "Female" if has("female", "woman", "girl", "she", "her", "lady") else
             "Male" if has("male", "man", "boy", "he", "him", "his") else "Lead")
    return f"[{sec} - {voice}]"


def scaffold_sheet(phrases: list[dict]) -> str:
    """A DRAFT lyric sheet in vocal_brief.parse_lyrics' format: `[Section - Who]` tags, one
    romanised line per sung phrase, instrumental phrases skipped. Consecutive phrases under
    the same tag share it. The header names it a draft."""
    # The sheet has NO comment syntax — parse_lyrics keeps every non-blank, non-tag line as a
    # lyric (a "#" header became two sung lines in the first test). A [tag] line is skipped,
    # so the draft notice rides as one; the first real section tag then sets the voice.
    lines = ["[DRAFT from song_breakdown - edit before the lyrics stage: check every line's words, who sings it and the section tags; the sheet rules, this proposal does not]", ""]
    last = None
    for p in phrases:
        text = (p.get("lyrics") or "").strip()
        if not text or text.startswith("—") or text.startswith("[") or "instrumental" in (p.get("section") or "").lower():
            continue
        who = " ".join(str(x) for x in [p.get("character"), p.get("singer"), *(p.get("singers") or [])] if x)
        tag = section_tag(p.get("section", ""), who)   # unknown → "Lead": the sheet decides, not a guess
        if tag != last:
            if last is not None:
                lines.append("")
            lines.append(tag)
            last = tag
        lines.append(re.sub(r"\s+", " ", text))
    return "\n".join(lines).rstrip() + "\n"


def cues_for_windows(phrases: list[dict], windows: list[dict]) -> dict[str, str]:
    """{wNN: sentence}: for each window, the cues of the phrases that start inside it, joined
    (≤ 25 words each, seconds stripped — a timecoded block beside the audio reference is the
    second clock that broke New Era). The SHOT_MOVES shape the operator may hand to shot_refs."""
    out: dict[str, str] = {}
    for w in windows:
        wid = w.get("id") or f"w{int(w.get('index', 0)):02d}"
        a, b = float(w.get("startSec", w.get("start", 0.0))), float(w.get("startSec", w.get("start", 0.0))) + float(w.get("seconds", w.get("end", 0.0) - w.get("start", 0.0)))
        cues = [re.sub(r"\b\d+(\.\d+)?\s?s(ec(onds?)?)?\b|\[\s*\d[^\]]*\]", "", (p.get("cue") or "")).strip()
                for p in phrases if a - 0.05 <= float(p.get("start", -1)) < b - 0.05 and p.get("cue")]
        cues = [" ".join(c.split()[:25]) for c in cues if c]
        if cues:
            out[wid] = " ".join(dict.fromkeys(cues))
    return out


def phrase_prompt(seconds: float, batch: list[dict], sheet_lines: list[str] | None) -> str:
    fixed = ("The lyric lines are given to you EXACTLY as the sheet has them; return each `lyrics` string "
             "VERBATIM (do not correct, translate or re-spell it) and attach the other fields to it.\n"
             if sheet_lines else
             "Transcribe the lyrics in Roman script (romanise Hindi/Urdu/other scripts); keep filler syllables.\n")
    return (
        f"You are a musicologist and a choreographer's assistant. This is an isolated vocal track ({seconds:.1f} s).\n"
        "For EVERY phrase listed below (their start/end seconds are correct — a speech model measured them — "
        "do not move them), answer:\n"
        "  section: Intro | Verse N | Pre-Chorus | Chorus | Hook | Bridge | Bols | Interlude | Outro\n"
        "  character: who is singing on screen in the film this song belongs to (a role name; 'Ensemble' for a chorus)\n"
        "  singer: the playback singer if you know it, else the voice type (e.g. 'female lead', 'male chorus')\n"
        "  singers: a list from ['female','male','chorus','both'] — every voice you hear in the phrase\n"
        "  translation: a one-line English gloss\n"
        "  cue: ONE sentence, ≤ 25 words, no seconds and no numbers: the vocal delivery (belt, whisper, "
        "chant, alaap, teasing, folk call…) and the physical action a dancer would do on this line\n"
        "  confidence: 0–1 for the character/singer call\n"
        + fixed
        + "Phrases:\n" + json.dumps(batch, ensure_ascii=False) + "\n\n"
        "Output ONLY a JSON array, one object per phrase, same order: "
        "[{\"index\": int, \"start\": float, \"end\": float, \"section\": str, \"character\": str, \"singer\": str, "
        "\"singers\": [str], \"lyrics\": str, \"translation\": str, \"cue\": str, \"confidence\": float}]"
    )


# ---------------------------------------------------------------------------------------
# media
# ---------------------------------------------------------------------------------------
def probe_seconds(path: str) -> float:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except ValueError:
        return 0.0


def encode_audio(path: str, out_dir: str) -> str:
    out = os.path.join(out_dir, "song-breakdown-audio.mp3")
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", path, "-vn", "-ac", "1", "-ar", "22050", "-b:a", "64k", out], check=True)
    return out


def inline_part(path: str, mime: str) -> dict:
    with open(path, "rb") as fh:
        return {"inlineData": {"mimeType": mime, "data": base64.b64encode(fh.read()).decode()}}


def files_api_part(path: str, mime: str, key: str) -> dict:
    """Resumable upload through the Files API, then poll until ACTIVE. Raw REST so the key
    pool applies (the SDK path in video-replicator takes one key)."""
    size = os.path.getsize(path)
    start = urllib.request.Request(FILES_ENDPOINT + "?key=" + key, method="POST",
                                   data=json.dumps({"file": {"display_name": os.path.basename(path)}}).encode(),
                                   headers={"X-Goog-Upload-Protocol": "resumable", "X-Goog-Upload-Command": "start",
                                            "X-Goog-Upload-Header-Content-Length": str(size),
                                            "X-Goog-Upload-Header-Content-Type": mime, "Content-Type": "application/json"})
    with urllib.request.urlopen(start, timeout=120) as r:
        upload_url = r.headers.get("X-Goog-Upload-URL")
    if not upload_url:
        raise RuntimeError("Files API gave no upload URL")
    with open(path, "rb") as fh:
        data = fh.read()
    up = urllib.request.Request(upload_url, method="POST", data=data,
                                headers={"X-Goog-Upload-Offset": "0", "X-Goog-Upload-Command": "upload, finalize",
                                         "Content-Length": str(size)})
    with urllib.request.urlopen(up, timeout=600) as r:
        info = json.load(r)["file"]
    name, uri = info["name"], info["uri"]
    for _ in range(120):
        with urllib.request.urlopen(FILES_GET + name.split("/")[-1] + "?key=" + key, timeout=60) as r:
            st = json.load(r)
        if st.get("state") == "ACTIVE":
            return {"fileData": {"mimeType": mime, "fileUri": uri}}
        if st.get("state") == "FAILED":
            raise RuntimeError("Files API processing failed")
        time.sleep(5)
    raise RuntimeError("Files API upload did not become ACTIVE in time")


# ---------------------------------------------------------------------------------------
# the html
# ---------------------------------------------------------------------------------------
def write_html(path: str, doc: dict, singers: dict | None) -> None:
    from lane_page import page, pill
    by_start = {}
    for row in (singers or {}).get("lines", []):
        try:
            by_start[round(float(row.get("start", -1)), 1)] = row
        except (TypeError, ValueError):
            pass
    rows = []
    for p in doc["phrases"]:
        s_row = by_start.get(round(float(p["start"]), 1))
        ear = (s_row or {}).get("who") or (s_row or {}).get("voice") or ""
        gem = " / ".join(x for x in [p.get("character"), p.get("singer")] if x)
        differs = bool(ear) and ear.lower() not in (gem or "").lower() and not any(k in (gem or "").lower() for k in (ear.lower(),))
        who_cell = html.escape(gem or "—") + (f' <span class="pill fail">differs from singers.json ({html.escape(ear)})</span>' if differs
                                              else (f' <span class="pill pass">agrees ({html.escape(ear)})</span>' if ear else ""))
        rows.append(
            "<tr>"
            f"<td class=mono>{p['start']:.2f}–{float(p.get('end') or p['start']):.2f}"
            + ("" if p.get("snapped") else ' <span class="pill skip">unsnapped</span>') + "</td>"
            f"<td>{html.escape(p.get('section') or '')}</td>"
            f"<td>{html.escape(p.get('lyrics') or '')}<div class=sub>{html.escape(p.get('translation') or '')}</div></td>"
            f"<td>{who_cell}</td>"
            f"<td>{html.escape(p.get('cue') or '')}</td>"
            "</tr>")
    body = (
        '<section class="card"><p><b>ADVISORY.</b> Gemini heard the song and proposed a section, a singer and a cue per phrase. '
        "The times are whisper's (snapped); the words are the sheet's when a brief existed. "
        "<b>Who sings is decided by your ear on singers.html, never by this page</b> — a row that differs is a question, not a correction. "
        f"Cues are in <code>song-cues-proposed.json</code> (SHOT_MOVES shape) for <code>SHOT_REFS=1</code> if you want them.</p>"
        f'<p class=sub>model {html.escape(doc["model"])} · {len(doc["phrases"])} phrases · '
        f'{sum(1 for p in doc["phrases"] if p.get("snapped"))} snapped to whisper onsets · input {html.escape(doc["inputKind"])}</p></section>'
        '<table class="grid"><thead><tr><th>time</th><th>section</th><th>lyric · translation</th><th>who (proposal)</th><th>cue</th></tr></thead>'
        f"<tbody>{''.join(rows)}</tbody></table>")
    css = ".grid{width:100%;border-collapse:collapse}.grid td,.grid th{border-bottom:1px solid var(--line);padding:6px 8px;vertical-align:top;text-align:left}.mono{font-family:ui-monospace,monospace;white-space:nowrap}.sub{color:var(--ink3);font-size:12px}.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:12px 0}"
    with open(path, "w", encoding="utf-8") as fh:
        fh.write(page("Song breakdown — what Gemini heard", "Which section, who sings, and what the body does on each line — a proposal for the sheet, never a verdict.",
                      body, slug=doc.get("slug", ""), extra_css=css))
    try:
        from lane_nav import inject_nav
        inject_nav(path)
    except Exception:   # noqa: BLE001 — the menu is a convenience
        pass


# ---------------------------------------------------------------------------------------
def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--stem", default="")
    ap.add_argument("--video", default="")
    ap.add_argument("--brief", default="")
    ap.add_argument("--transcript", default="")
    ap.add_argument("--singers", default="")
    ap.add_argument("--windows", default="")
    ap.add_argument("--out", default="")
    ap.add_argument("--html", default="")
    ap.add_argument("--scaffold-lyrics", default="")
    ap.add_argument("--model", default=os.environ.get("SONG_BREAKDOWN_MODEL", DEFAULT_MODEL))
    ap.add_argument("--snap-s", type=float, default=1.5)
    ap.add_argument("--batch", type=int, default=14)
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()

    P = os.path.abspath(a.project)
    build = os.path.join(P, "build")
    stem = a.stem or os.path.join(build, "stems", "vocals.wav")
    video = a.video
    brief_path = a.brief or os.path.join(build, "vocal-brief.json")
    transcript_path = a.transcript or os.path.join(build, "transcript.json")
    singers_path = a.singers or os.path.join(build, "singers.json")
    windows_path = a.windows or os.path.join(build, "windows.json")
    out = a.out or os.path.join(build, "song-breakdown.json")
    html_out = a.html or os.path.join(build, "song-breakdown.html")

    media = video if video else stem
    kind = "video" if video else "stem"
    if not os.path.isfile(media):
        hook = os.path.join(build, "hook.wav")
        if not video and os.path.isfile(hook):
            media, kind = hook, "mix"
        else:
            say(f"no {kind} at {media}")
            return 2
    if a.scaffold_lyrics and os.path.isfile(a.scaffold_lyrics):
        say(f"--scaffold-lyrics refuses to overwrite an existing sheet: {a.scaffold_lyrics} (the sheet rules)")
        return 4

    # the phrases Gemini is asked about: the brief's placed lines (sheet text, whisper time),
    # else whisper's own segments
    brief = read_json(brief_path)
    transcript = read_json(transcript_path)
    onsets: list[float] = []
    phrases_in: list[dict] = []
    sheet_lines = None
    if brief and brief.get("lines"):
        for i, ln in enumerate(brief["lines"]):
            if ln.get("start") is None:
                continue
            phrases_in.append({"index": len(phrases_in), "start": round(float(ln["start"]), 2),
                               "end": round(float(ln.get("end") or ln["start"]), 2), "lyrics": ln.get("text", "")})
        sheet_lines = [p["lyrics"] for p in phrases_in]
        onsets = [p["start"] for p in phrases_in]
    elif transcript and transcript.get("segments"):
        for seg in transcript["segments"]:
            if (seg.get("text") or "").strip():
                phrases_in.append({"index": len(phrases_in), "start": round(float(seg["start"]), 2),
                                   "end": round(float(seg["end"]), 2), "lyrics": seg["text"].strip()})
        onsets = sorted({round(float(w["start"]), 3) for seg in transcript["segments"] for w in seg.get("words", [])} | {p["start"] for p in phrases_in})
    else:
        say("neither a vocal brief nor a whisper transcript is on disk — the map stage has not run; nothing to ask about")
        return 2

    from breakdown import api_keys, call_model  # noqa: E402
    keys = api_keys()
    if not keys:
        say("no Gemini key (GEMINI_API_KEYS / GOOGLE_API_KEY, or .env.local) — set one, or leave SONG_BREAKDOWN unset")
        return 3
    seconds = probe_seconds(media)
    batches = [phrases_in[k:k + a.batch] for k in range(0, len(phrases_in), a.batch)]
    if a.dry_run:
        say(f"DRY RUN — {len(phrases_in)} phrases from {'the brief' if sheet_lines else 'whisper segments'} in {len(batches)} batch(es); "
            f"{kind} {media} ({seconds:.1f} s) would go {'inline' if kind != 'video' or os.path.getsize(media) <= INLINE_CAP_BYTES else 'through the Files API'}; "
            f"model {a.model}; no call made, nothing written")
        print(json.dumps({"dryRun": True, "inputKind": kind, "phrases": len(phrases_in), "batches": len(batches),
                          "parts": [{"inlineData": {"mimeType": "audio/mpeg" if kind != "video" else "video/mp4", "data": "<bytes>"}}, {"text": phrase_prompt(seconds, batches[0], sheet_lines)[:200] + "…"}]}, ensure_ascii=False))
        return 0

    tmp = tempfile.mkdtemp(prefix="song-breakdown-")
    if kind == "video":
        part = inline_part(media, "video/mp4") if os.path.getsize(media) <= INLINE_CAP_BYTES else files_api_part(media, "video/mp4", keys[0])
    else:
        part = inline_part(encode_audio(media, tmp), "audio/mpeg")
    cooldown: dict[str, float] = {}
    answers: list[dict] = []
    for bi, batch in enumerate(batches):
        say(f"batch {bi + 1}/{len(batches)} ({len(batch)} phrases) → {a.model}")
        ans = call_model(keys, a.model, [part, {"text": phrase_prompt(seconds, batch, sheet_lines)}], cooldown, max_output_tokens=16384)
        rows = ans if isinstance(ans, list) else ans.get("phrases", []) if isinstance(ans, dict) else []
        by_index = {}
        for r in rows:
            try:
                by_index[int(r.get("index"))] = r
            except (TypeError, ValueError):
                continue
        for p in batch:
            r = by_index.get(p["index"], {})
            answers.append({**p,
                            "lyrics": p["lyrics"] if sheet_lines else (r.get("lyrics") or p["lyrics"]),
                            "start": float(r.get("start", p["start"])) if not sheet_lines else p["start"],
                            "section": r.get("section", ""), "character": r.get("character", ""), "singer": r.get("singer", ""),
                            "singers": r.get("singers") or [], "translation": r.get("translation", ""), "cue": r.get("cue", ""),
                            "confidence": r.get("confidence")})
    phrases = snap_to_onsets(answers, onsets, a.snap_s)
    doc = {"schemaVersion": 1, "slug": os.path.basename(P), "model": a.model, "inputKind": kind, "input": os.path.abspath(media),
           "inputSha": {"media": sha256_file(media), "brief": sha256_file(brief_path) if os.path.isfile(brief_path) else None,
                        "transcript": sha256_file(transcript_path) if os.path.isfile(transcript_path) else None},
           "promptSha": hashlib.sha256(phrase_prompt(seconds, batches[0], sheet_lines).encode()).hexdigest()[:16],
           "textFrom": "sheet" if sheet_lines else "gemini", "snapTolS": a.snap_s, "phrases": phrases,
           "advisory": "character/singer/section/cue are proposals; the sheet and singers.html decide"}
    os.makedirs(os.path.dirname(out), exist_ok=True)
    with open(out + ".tmp", "w", encoding="utf-8") as fh:
        json.dump(doc, fh, indent=1, ensure_ascii=False)
    os.replace(out + ".tmp", out)
    write_html(html_out, doc, read_json(singers_path))
    cues_path = os.path.join(os.path.dirname(out), "song-cues-proposed.json")
    windows = (read_json(windows_path) or {}).get("windows") or []
    cues = cues_for_windows(phrases, windows) if windows else {}
    with open(cues_path, "w", encoding="utf-8") as fh:
        json.dump({"schemaVersion": 1, "source": os.path.relpath(out, P), "shape": "SHOT_MOVES {wNN: sentence}",
                   "windows": cues, "note": "hand to shot_refs via SHOT_MOVES under SHOT_REFS=1; never applied on its own"}, fh, indent=1, ensure_ascii=False)
    if a.scaffold_lyrics:
        os.makedirs(os.path.dirname(os.path.abspath(a.scaffold_lyrics)), exist_ok=True)
        with open(a.scaffold_lyrics, "w", encoding="utf-8") as fh:
            fh.write(scaffold_sheet(phrases))
        say(f"DRAFT sheet → {a.scaffold_lyrics} (edit it; the lyrics stage's checks still gate it)")
    say(f"{len(phrases)} phrases ({sum(1 for p in phrases if p['snapped'])} snapped) → {out}; {html_out}; {len(cues)} window cue(s) → {cues_path}")
    return 0


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