#!/usr/bin/env python3
"""rap_fixture.py — a from-scratch synthetic film the pipeline can prove itself on.

The dry run (dryrun.sh --synthetic) proves the back half on a COPY of a real project,
which needs a real song, a real transcript and a real plan. Nothing proved the front
half, and nothing proved the DUET path until a duet film paid five hours of lane time
to find rows 7, 12 and 17 (Baby Ram & Sita, 2026-09-01/02). This builds a whole film
from nothing, in seconds, with the parts a real one has:

  a pack (from _template.rap.pack, the approved recipe)
  a romanised lyric sheet with section tags ([Hook - Both], [Verse 1 - Female], …)
  a song: a synthetic beat + the lines SPOKEN by macOS `say` at their planned times, so
      Demucs separates a real voice and whisper (the stub) has something to hear
  the vocal-only track and the word timeline the whisper stub answers from
  one portrait per performer (drawn, > 500 px — the identity gate's floor)
  a styles register with a performer per world, and the sections file

Two kinds:
  solo   one voice, three worlds, no instrumental gap >= 2 s — the baseline
  duet   two voices, six worlds, a handover mid-section and two gap sections — rows
         7, 12 and 17 of film #2 were duet-only paths a solo film never executes

Usage:  rap_fixture.py --kind solo|duet --workspace <W> [--slug NAME]
Prints the pack path; the project lands at <W>/projects/<slug>.
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
SKILL = os.path.dirname(HERE)
FFMPEG = os.environ.get("FFMPEG_FULL", "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg")

# ---- the two films -----------------------------------------------------------------
# (section tag, performer: a|b|both, lines, world id, start of the first line)
SOLO = {
    "names": "Ava", "pronouns": "she", "voices": {"a": "Samantha"},
    "sections": [
        ("Hook", "a", ["Sunny day in the garden we run", "Chase the butterfly under the sun",
                       "Mud on my feet and a flower in my hair", "Sunny day and the song is everywhere"], 0, 2.0),
        ("Verse 1", "a", ["Woke up early with the birds in the tree", "Kicked my sandal and it flew past me",
                          "Higher and higher on the swing I go", "Touch the mango touch the sky I know"], 1, 15.0),
        ("Hook", "a", ["Sunny day in the garden we run", "Chase the butterfly under the sun",
                       "Mud on my feet and a flower in my hair", "Sunny day and the song is everywhere"], 2, 28.0),
    ],
    "line_gap": 3.0, "tail": 3.0,
}
DUET = {
    "names": "Ava|Ben", "pronouns": "she|he", "voices": {"a": "Samantha", "b": "Daniel"},
    # a 6 s instrumental INTRO before the first line: line_windows opens an intro window
    # (kind intro, shot-led), the one window that takes the composed no-voice register
    "sections": [
        ("Hook - Both", "both", ["Sunny day in the garden we run", "Chase the butterfly under the sun",
                                 "Mud on my feet and a flower in my hair", "Sunny day and the song is everywhere"], 0, 6.0),
        ("Verse 1 - Female", "a", ["Woke up early with the birds in the tree", "Kicked my sandal and it flew past me",
                                   "Higher and higher on the swing I go", "Touch the mango touch the sky I know"], 1, 20.0),
        # a 4 s instrumental gap here (32 -> 36): a gap section the cutter must fill
        ("Verse 2 - Male", "b", ["Tiptoe down to the lily pond", "The frog said hello and I said bond",
                                 "Splash the water catch a rainbow ring", "Sunny day is a wonderful thing"], 2, 36.0),
        # the bridge hands over mid-section: her line, then his, no gap between them
        ("Bridge - Female", "a", ["Who is the fastest in the garden today"], 3, 50.0),
        ("Bridge - Male", "b", ["Me me me is what I say"], 4, 53.5),
        # a second gap (57 -> 61), then the closing hook
        ("Hook - Both", "both", ["Sunny day in the garden we run", "Chase the butterfly under the sun",
                                 "Mud on my feet and a flower in my hair", "Sunny day and the song is everywhere"], 5, 61.0),
    ],
    "line_gap": 3.0, "tail": 3.0,
}


def run(cmd: list[str]) -> None:
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        sys.exit(f"rap_fixture: {' '.join(cmd[:3])} failed:\n{r.stderr[-600:]}")


def seconds(path: str) -> float:
    out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                         capture_output=True, text=True).stdout.strip()
    return float(out) if out else 0.0


def speak(text: str, voice: str, out_wav: str) -> float:
    """macOS `say` -> 16 kHz mono wav; returns its length."""
    aiff = out_wav[:-4] + ".aiff"
    r = subprocess.run(["say", "-v", voice, "-o", aiff, text], capture_output=True, text=True)
    if r.returncode:   # a missing voice: fall back to the default voice
        run(["say", "-o", aiff, text])
    run([FFMPEG, "-v", "error", "-y", "-i", aiff, "-ac", "1", "-ar", "16000", out_wav])
    os.remove(aiff)
    return seconds(out_wav)


def build_timeline(spec: dict, tmp: str) -> tuple[list[dict], list[dict], list[tuple[str, float, str]], float]:
    """Speak every line; place it. Returns (lines, words, placements, songLength).
    lines: [{section, performer, text, start, end}]   words: [{t, end, w}]
    placements: [(wav, start, performer)] for the mix."""
    lines, words, placed = [], [], []
    for si, (tag, perf, texts, world, first) in enumerate(spec["sections"]):
        t = first
        for li, text in enumerate(texts):
            voices = [spec["voices"]["a"], spec["voices"]["b"]] if perf == "both" else [spec["voices"][perf]]
            length = 0.0
            for vi, voice in enumerate(voices):
                wav = os.path.join(tmp, f"s{si}-l{li}-v{vi}.wav")
                length = max(length, speak(text, voice, wav))
                placed.append((wav, t, perf))
            ws = text.split()
            per = length / len(ws)
            for wi, w in enumerate(ws):
                words.append({"t": round(t + wi * per, 3), "end": round(t + (wi + 1) * per - 0.05, 3), "w": w})
            lines.append({"section": tag, "performer": perf, "text": text, "start": round(t, 3), "end": round(t + length, 3)})
            t += max(length + 0.4, spec["line_gap"])
    song_len = lines[-1]["end"] + spec["tail"]
    return lines, words, placed, song_len


def mix_song(placed: list[tuple[str, float, str]], song_len: float, vocal_wav: str, song_mp3: str) -> None:
    """The vocal-only track (every spoken line at its time) and the mix (a low beat under it)."""
    inputs, parts = [], []
    for i, (wav, start, _) in enumerate(placed):
        inputs += ["-i", wav]
        parts.append(f"[{i}:a]adelay={int(start * 1000)}|{int(start * 1000)}[d{i}]")
    n = len(placed)
    # BOUNDED, OR IT NEVER ENDS: an unbounded `apad` behind `amix` ran ffmpeg for ten
    # hours once and 47 minutes once today (2026-09-02) — `atrim` after it does not
    # reliably stop the graph. Pad only to the song's length and cap the output too.
    graph = (";".join(parts) + ";" + "".join(f"[d{i}]" for i in range(n))
             + f"amix=inputs={n}:normalize=0:duration=longest,apad=whole_dur={song_len:.3f}[v]")
    run([FFMPEG, "-v", "error", "-y", *inputs, "-filter_complex", graph, "-map", "[v]",
         "-t", f"{song_len:.3f}", "-ac", "1", "-ar", "44100", vocal_wav])
    # the beat: a low pulse and a hat, quiet under the voice
    beat = os.path.join(os.path.dirname(vocal_wav), "beat.wav")
    # The bed is WIDE by construction: the same low pulse in both channels (centre), and a
    # different noise stream per channel (uncorrelated left/right = side energy), so the
    # mix has a side channel for vocal_map to separate the centred voice against.
    run([FFMPEG, "-v", "error", "-y",
         "-f", "lavfi", "-i", f"sine=frequency=55:duration={song_len:.3f}",
         "-f", "lavfi", "-i", f"anoisesrc=colour=pink:seed=11:amplitude=0.3:duration={song_len:.3f}",
         "-f", "lavfi", "-i", f"anoisesrc=colour=pink:seed=23:amplitude=0.3:duration={song_len:.3f}",
         "-filter_complex", "[0:a]volume=0.25,tremolo=f=2:d=0.9,aformat=channel_layouts=stereo[b];"
                            "[1:a]highpass=f=1500,tremolo=f=8:d=1[l];[2:a]highpass=f=1500,tremolo=f=8:d=1[r];"
                            "[l][r]join=inputs=2:channel_layout=stereo[h];[b][h]amix=inputs=2:normalize=0[m]",
         "-map", "[m]", "-ac", "2", "-ar", "44100", beat])
    # STEREO WIDTH IS LOAD-BEARING: vocal_map separates the voice as the CENTRE of the mix
    # against the stereo SIDE, and refuses a dual-mono song ("no usable side channel"). A
    # real record has width; the beat gets it here (an auto-panner), the voice stays centred.
    run([FFMPEG, "-v", "error", "-y", "-i", vocal_wav, "-i", beat,
         "-filter_complex", "[0:a]volume=1.0,aformat=channel_layouts=stereo[v];"
                            "[1:a]volume=0.6[b];"
                            "[v][b]amix=inputs=2:normalize=0,alimiter=limit=0.9[m]",
         "-map", "[m]", "-ac", "2", "-ar", "44100", "-c:a", "libmp3lame", "-b:a", "192k", song_mp3])


def draw_portrait(path: str, hue: tuple[int, int, int], label: str) -> None:
    from PIL import Image, ImageDraw
    im = Image.new("RGB", (720, 900), (245, 240, 232))
    d = ImageDraw.Draw(im)
    d.ellipse((160, 150, 560, 620), fill=hue, outline=(40, 40, 40), width=6)          # a head
    d.ellipse((260, 320, 320, 380), fill=(30, 30, 30)); d.ellipse((400, 320, 460, 380), fill=(30, 30, 30))  # eyes
    d.arc((280, 430, 440, 540), 15, 165, fill=(30, 30, 30), width=8)                  # a smile
    d.rectangle((200, 640, 520, 900), fill=(90, 110, 160))                            # shoulders
    d.text((40, 40), label, fill=(30, 30, 30))
    im.save(path)


def sheet_text(spec: dict) -> str:
    out = []
    for tag, perf, texts, _, _ in spec["sections"]:
        out.append(f"[{tag}]")
        out.extend(texts)
        out.append("")
    return "\n".join(out).strip() + "\n"


def styles_for(spec: dict, out_path: str) -> None:
    """The lane's default register, one row per world the fixture names, with the
    performer the section says (a/b/both) and the duet extras a both-world needs."""
    base = json.load(open(os.path.join(SKILL, "references", "styles.json"), encoding="utf-8"))
    rows = list(base if isinstance(base, list) else base.get("styles") or [])
    out = []
    for tag, perf, _, world, _ in spec["sections"]:
        if any(r["id"] == rows[world]["id"] for r in out):
            continue
        r = dict(rows[world])
        r["performer"] = perf
        r["solo"] = perf != "both"                      # a two-person world cannot be a solo shot
        if perf == "both":
            r.setdefault("wardrobe2", r.get("wardrobe", ""))
        out.append(r)
    json.dump({"styles": out}, open(out_path, "w", encoding="utf-8"), indent=1)   # pick_styles reads {"styles": [...]}


def world_ids() -> list[str]:
    base = json.load(open(os.path.join(SKILL, "references", "styles.json"), encoding="utf-8"))
    return [r["id"] for r in (base if isinstance(base, list) else base.get("styles") or [])]


def sections_for(spec: dict, lines: list[dict], song_len: float) -> list[dict]:
    """One block per sheet section: from its first line's onset (or 0) to the next
    section's first onset (or the song's end)."""
    ids = world_ids()
    firsts = [(ids[s[3]], s[4], s[0]) for s in spec["sections"]]
    out, prev_end = [], 0.0
    for i, (world, first, tag) in enumerate(firsts):
        start = 0.0 if i == 0 else first
        end = firsts[i + 1][1] if i + 1 < len(firsts) else song_len
        out.append({"styleId": world, "start": round(start, 3), "end": round(end, 3), "label": tag})
    return out


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--kind", choices=("solo", "duet"), required=True)
    ap.add_argument("--workspace", required=True)
    ap.add_argument("--slug", default="")
    a = ap.parse_args()
    spec = SOLO if a.kind == "solo" else DUET
    slug = a.slug or f"rap-fixture-{a.kind}"
    W = os.path.abspath(a.workspace)
    P = os.path.join(W, "projects", slug)
    if os.path.isdir(P):
        shutil.rmtree(P)
    for d in ("references", "artifacts/audio", "build", "fixture"):
        os.makedirs(os.path.join(P, d), exist_ok=True)
    os.makedirs(os.path.join(W, "packs"), exist_ok=True)
    json.dump({"slug": slug, "mode": "storyboard", "state": "fixture"}, open(os.path.join(P, "project.json"), "w"))

    tmp = tempfile.mkdtemp()
    lines, words, placed, song_len = build_timeline(spec, tmp)
    vocal = os.path.join(P, "fixture", "vocal.wav")
    song = os.path.join(P, "artifacts", "audio", "soundtrack-suno.mp3")
    mix_song(placed, song_len, vocal, song)
    json.dump({"words": words, "lines": lines, "songSeconds": song_len}, open(os.path.join(P, "fixture", "words.json"), "w"), indent=1)
    open(os.path.join(P, "references", "lyrics.txt"), "w", encoding="utf-8").write(sheet_text(spec))
    draw_portrait(os.path.join(P, "references", "portrait-a.png"), (230, 180, 150), "Ava")
    if a.kind == "duet":
        draw_portrait(os.path.join(P, "references", "portrait-b.png"), (150, 190, 230), "Ben")
    styles_for(spec, os.path.join(P, "fixture", "styles.json"))
    json.dump({"sections": sections_for(spec, lines, song_len)}, open(os.path.join(P, "build", "sections.json"), "w"), indent=1)

    # the pack: the approved recipe, then the fixture's own keys
    tpl = open(os.path.join(SKILL, "_template.rap.pack"), encoding="utf-8").read()
    over = {
        "PACK_NAME": slug, "DISPLAY_NAME": "Fixture", "PERFORMER_NAMES": spec["names"], "PERFORMER_PRONOUNS": spec["pronouns"],
        "PORTRAIT": os.path.join(P, "references", "portrait-a.png"), "PORTRAIT_CONSENT": "yes",
        "IDENTITY_NOTES": "a drawn face on a cream ground, round head, dark eyes, blue shoulders",
        "TITLE_ROMAN": "Sunny Day", "BOOKEND_TITLE": "Sunny Day", "SONG_LANGUAGE": "en", "LYRIC_LANGUAGE": "English",
        "STYLES_FILE": os.path.join(P, "fixture", "styles.json"), "SECTIONS": os.path.join(P, "build", "sections.json"),
        "STYLE_COUNT": str(len({s[3] for s in spec["sections"]})), "SINGER_DETECT": "0", "RAP_PROOF": "each", "RAP_SKIP_DRYRUN": "1",
        "VCLAW_WORKSPACE": W, "MADE_FOR_KIDS": "no", "YT_PRIVACY": "private",
    }
    if a.kind == "duet":
        over.update({"PORTRAIT_2": os.path.join(P, "references", "portrait-b.png"), "PORTRAIT_CONSENT_2": "yes",
                     "IDENTITY_NOTES_2": "a drawn face on a cream ground, round head, dark eyes, blue shoulders"})
    out_lines, seen = [], set()
    for line in tpl.splitlines():
        key = line.split("=", 1)[0].strip() if "=" in line and not line.lstrip().startswith("#") else ""
        if key in over:
            out_lines.append(f'{key}="{over[key]}"'); seen.add(key)
        else:
            out_lines.append(line)
    for key, val in over.items():
        if key not in seen:
            out_lines.append(f'{key}="{val}"')
    pack = os.path.join(W, "packs", f"{slug}.pack")
    open(pack, "w", encoding="utf-8").write("\n".join(out_lines) + "\n")
    shutil.rmtree(tmp, ignore_errors=True)
    print(json.dumps({"pack": pack, "slug": slug, "project": P, "songSeconds": round(song_len, 2),
                      "lines": len(lines), "words": len(words), "vocal": vocal,
                      "wordsFile": os.path.join(P, "fixture", "words.json")}))


if __name__ == "__main__":
    main()
