#!/usr/bin/env python3
"""sung_only.py — a paid take that renders the SUNG span of a window, not its silent head.

The first real paid take on reapi-seedance (baby-kala-chashma w08, 2026-09-21, $1.335) came
back with the picture right and the timing wrong. The window's voice slice is 5 s: 0.68 s of
muted head, the boy's 4.0 s chant, a short tail. The model swallowed the silent head and
started the chant at frame one, finishing 0.5 s early; the judge parked it (corr 0.58 at
+125 ms). The lane already knows this model behaviour on the free engine: "the model fills
the VIDEO length, not the audio length". Here the fix is to give it nothing to swallow —
cut the head off the audio, render the shortest whole second that holds the singing, and
say so in the prompt (the prompt follows the audio, always).

ONE source of truth for the derived bytes. `preflight_higgs.py` calls `derive()` +
`build_sung_audio()` to put the sung-only take on the contract page as a VARIANT
(hashed into the same approval, beside the scrub variant); `reapi_take.py` calls the same
two functions at submit and refuses unless its hash equals the approved one. The hashed
wav IS the submitted wav.

Every transform here is exact, or it refuses (exit 2). A shape this module has not been
proven on — a timestamped prompt, a template that drifted, a head too short to cut — is a
refusal with a plain sentence, never a guess: the guess costs money.
"""
from __future__ import annotations

import json
import math
import os
import re
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

from lane_render import own_spans  # noqa: E402
from make_plan import MIN_CLIP, ROUTE_MAX_CLIP, probe_seconds  # noqa: E402

SUNG_ONLY = "sungOnly"            # the variant's name on the contract page and in the approval
ROUTE = "reapi-seedance"
HEAD_SILENCE_MIN_S = 0.3          # below this there is nothing to cut — refuse, not a no-op
FRAME_TOLERANCE_S = 0.05          # one frame: ffmpeg lands a 4.000 s request at 4.02 s or so
PROVIDER_OVERRUN_TOLERANCE_S = 0.1  # reAPI answered a 5 s request with 5.056 s; up to this much is trimmed, more refuses

# make_plan._direction's partialHead clause, ONE-CLOCK form (`; then ` join; the `, until
# <poss> first line` tail is only written in that mode). The timestamped form (`0.0–0.7s `
# prefixes, `; ` join) is refused before this is tried — every later line's clock would
# need shifting by −t0 and that is not proven.
HEAD_CLAUSE_RE = re.compile(
    r"the previous line is ending on the track — lips closed, no words(?:, until \w+ first line)?; then ")
TIMESTAMP_RE = re.compile(r"\b\d+\.\d–\d+\.\ds ")
# make_plan's Audio-1 sentence asserts the WINDOW length; it must say the render's.
LENGTH_RE_TEMPLATE = r"is the {seconds}-second track"
# make_plan writes the sung line in curly quotes; reAPI's field doc: "Wrap spoken lines in
# double quotes to steer the generated speech." Straight quotes are what it names.
CURLY_QUOTE_RE = re.compile("“([^“”]*)”")
# Not in any live template (it survives in older films' prompts.json); optional. With the
# head cut, an order to hold a silent head is the exact defect being paid to remove.
SILENT_ENDS = "Preserve the specified silent head and tail."
SILENT_TAIL = "Preserve the specified silent tail."


class NotApplicable(Exception):
    """The sung-only take does not apply to this window as it is; the normal take does."""
    code = 2


# --------------------------------------------------------------------------
# the pure derivation
# --------------------------------------------------------------------------

def span(plan: dict, job: dict) -> tuple[float, float]:
    """(t0, t1) window-relative seconds: this face's first sung word to its last."""
    spans = own_spans(plan, job)
    if not spans:
        raise NotApplicable(f"{job['id']}: the plan carries no sung spans for this performer "
                            "(vocal.spans) — the sung window cannot be located; run the normal take")
    return round(min(s for s, _ in spans), 3), round(max(e for _, e in spans), 3)


def render_seconds(t0: float, t1: float, job_seconds: float) -> int:
    """The shortest whole second that holds the singing; the remainder is tail, never head.

    This departs from the lane's own law for the free engine (render = sung + 0.3 s head
    + 0.3 s tail, never below ceil(sung + 0.1)): that law was measured where the defect was
    singing SLOW to fill a padded clip. The padded shape is exactly what failed on reAPI —
    the head was swallowed and the line pulled to frame one. The head is the only thing
    cut; the slice is already muted after t1, so no sung word is newly clipped; D = 4 for
    4.0 s of singing leaves the model a 1.0 ratio. One variable moves: the head.
    """
    sung = t1 - t0
    seconds = max(MIN_CLIP, math.ceil(sung - 1e-6))
    if seconds > float(job_seconds) + 1e-6:
        raise NotApplicable(f"the sung span ({sung:.2f} s) needs {seconds} s, more than the window's "
                            f"{job_seconds:g} s — nothing to cut; run the normal take")
    if seconds > ROUTE_MAX_CLIP[ROUTE]:
        raise NotApplicable(f"the sung span needs {seconds} s, over the route's {ROUTE_MAX_CLIP[ROUTE]} s cap")
    return int(seconds)


def sung_prompt(prompt: str, job_seconds: float, seconds_out: int, tail_s: float) -> tuple[str, list[str]]:
    """The window's prompt with the silent head gone from the words as well as the audio.

    Four exact rewrites; each is named in `changes`. Every other byte is untouched.
    """
    changes: list[str] = []
    out, n = HEAD_CLAUSE_RE.subn("", prompt, count=1)
    if n != 1:
        raise NotApplicable("the prompt does not carry make_plan's one-clock head clause "
                            "(\"the previous line is ending on the track — lips closed, no words…; then \") "
                            "— the template drifted or this is not a partial-head window; refusing to guess")
    changes.append("head clause dropped: the audio now starts on the first sung word")
    length_re = re.compile(LENGTH_RE_TEMPLATE.format(seconds=re.escape(f"{float(job_seconds):g}")))
    out, n = length_re.subn(f"is the {seconds_out}-second track", out, count=1)
    if n != 1:
        raise NotApplicable(f"the prompt does not say \"is the {float(job_seconds):g}-second track\" — "
                            "the Audio-1 sentence drifted; refusing to guess")
    changes.append(f"track length: {float(job_seconds):g}-second → {seconds_out}-second")
    out, n = CURLY_QUOTE_RE.subn(lambda m: '"' + m.group(1) + '"', out)
    if n < 1:
        raise NotApplicable("the prompt carries no curly-quoted sung line to rewrite — refusing to guess")
    changes.append(f"{n} sung line(s) in straight double quotes (reAPI: \"wrap spoken lines in double quotes\")")
    if SILENT_ENDS in out:
        if tail_s > FRAME_TOLERANCE_S:
            out = out.replace(SILENT_ENDS, SILENT_TAIL, 1)
            changes.append("silent-ends sentence: head dropped, tail kept")
        else:
            out = re.sub(r" ?" + re.escape(SILENT_ENDS), "", out, count=1)
            changes.append("silent-ends sentence dropped: no silent head, no silent tail")
    return out, changes


def refuse_unless_applicable(plan: dict, job: dict) -> None:
    """Every reason this window cannot take the sung-only path, as a plain sentence."""
    if not job.get("voiceRef"):
        raise NotApplicable(f"{job['id']}: no voice slice — a sung-only take needs one")
    if not os.path.isfile(job["voiceRef"]):
        raise NotApplicable(f"{job['id']}: the voice slice is missing on disk ({job['voiceRef']})")
    t0, t1 = span(plan, job)
    if t0 < HEAD_SILENCE_MIN_S:
        raise NotApplicable(f"{job['id']}: the singing starts at {t0:.2f} s — under {HEAD_SILENCE_MIN_S} s of head, "
                            "nothing to cut; run the normal take")
    prompt = job.get("prompt") or ""
    if TIMESTAMP_RE.search(prompt):
        raise NotApplicable(f"{job['id']}: the prompt is timestamped (\"S.S–E.Es …\" clocks per line); shifting "
                            "every clock by the cut head is not proven — refusing")
    # THE PROMPT MUST DESCRIBE THE CUT AUDIO. sung_prompt drops exactly one clause — the
    # partialHead fragment — so everything the slice carries before t0 must be that ONE
    # fragment, ending where the singing starts. A gap ("a short instrumental pause") or
    # another voice's line before t0 would stay in the words with its audio gone: the
    # model told to hold lips closed at the head of a clip that sings at frame one, the
    # exact defect this take exists to remove. Refuse those shapes.
    spans = sorted(((job.get("vocal") or {}).get("spans") or []), key=lambda sp: float(sp["start"]))
    before = [sp for sp in spans if float(sp["start"]) < t0 - FRAME_TOLERANCE_S]
    if not before:
        raise NotApplicable(f"{job['id']}: nothing is sung before {t0:.2f} s in the brief, yet the head is silent "
                            "— this is not a partial-head window; run the normal take")
    if len(before) != 1 or not before[0].get("partialHead"):
        raise NotApplicable(f"{job['id']}: the audio before the first sung word ({t0:.2f} s) is not one partial-head "
                            "fragment (a gap or another voice's line sits there); the prompt would keep words whose "
                            "audio is cut — refusing")
    if abs(float(before[0]["end"]) - t0) > FRAME_TOLERANCE_S:
        raise NotApplicable(f"{job['id']}: the head fragment ends at {float(before[0]['end']):.2f} s but the singing "
                            f"starts at {t0:.2f} s — an instrumental gap the prompt describes and the cut removes; refusing")
    job_seconds = float(job.get("seconds") or plan.get("seconds") or 0)
    seconds = render_seconds(t0, t1, job_seconds)
    # THE RENDER MUST FIT THE WINDOW AFTER THE HEAD IS PUT BACK. pad_to_window prepends t0
    # and trims to the window; a render longer than window − t0 would lose its tail there.
    if t0 + seconds > job_seconds + FRAME_TOLERANCE_S:
        raise NotApplicable(f"{job['id']}: a {seconds} s render plus the {t0:.2f} s cut head is {t0 + seconds:.2f} s, "
                            f"longer than the {job_seconds:g} s window — it would be trimmed when put back; run the normal take")


def derive(plan: dict, job: dict) -> dict:
    """Everything the sung-only take changes, computed once: t0/t1, seconds, tail, prompt, changes."""
    refuse_unless_applicable(plan, job)
    t0, t1 = span(plan, job)
    job_seconds = float(job.get("seconds") or plan.get("seconds"))
    seconds = render_seconds(t0, t1, job_seconds)
    tail = round(max(0.0, seconds - (t1 - t0)), 3)
    prompt, changes = sung_prompt(job["prompt"], job_seconds, seconds, tail)
    return {"t0": t0, "t1": t1, "sung": round(t1 - t0, 3), "seconds": seconds, "tail": tail,
            "windowSeconds": job_seconds, "prompt": prompt, "changes": changes}


def audio_path(job: dict) -> str:
    """`build/voice/<id>-sung.wav`, beside the slice it is cut from."""
    voice = os.path.abspath(job["voiceRef"])
    return os.path.join(os.path.dirname(voice), f"{job['id']}-sung.wav")


def derived_job(job: dict, wav: str, d: dict) -> dict:
    """The job as the approval sees the sung-only take: build_payload_doc on THIS is the payload
    whose hash goes on the page and in the approval (prompt, duration, and the wav's bytes)."""
    return {**job, "seconds": d["seconds"], "voiceRef": wav, "prompt": d["prompt"]}


# --------------------------------------------------------------------------
# the two ffmpeg cuts
# --------------------------------------------------------------------------

def _sha256_file(path: str) -> str:
    import hashlib
    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 build_sung_audio(voice: str, dest: str, t0: float, seconds: int, ffmpeg: str = "ffmpeg") -> str:
    """The slice from the first sung word, `seconds` long, as a bit-exact mono wav.

    `apad` + the trailing `-t`: for sung 4.3 → 5 s, `-ss t0 -t 5` runs off the end of a
    5 s slice and would yield a short wav (w08 only lines up — t0 + 4 = 4.68, the mute
    point — by coincidence). `-fflags/-flags +bitexact`: no encoder tag in the header, so
    the same slice and the same (t0, seconds) give the same bytes on every run — the
    approval hashes them. Cached by content like make_plan.build_voice (a sidecar).
    """
    want = {"voiceSha": _sha256_file(voice), "t0": round(float(t0), 3), "seconds": int(seconds)}
    side = dest + ".json"
    if os.path.isfile(dest) and os.path.getsize(dest) > 0 and os.path.isfile(side):
        try:
            have = json.load(open(side, encoding="utf-8"))
        except (OSError, ValueError):
            have = None
        got = probe_seconds(dest)
        if have == want and got and abs(got - seconds) <= FRAME_TOLERANCE_S:
            return dest
    if os.path.isfile(side):
        os.remove(side)
    cmd = [ffmpeg, "-y", "-v", "error", "-nostdin",
           "-ss", f"{t0:.3f}", "-t", f"{seconds:.3f}", "-i", voice,
           "-vn", "-af", "apad", "-t", f"{seconds:.3f}",
           "-acodec", "pcm_s16le", "-ar", "44100", "-ac", "1",
           "-fflags", "+bitexact", "-flags", "+bitexact", dest]
    p = subprocess.run(cmd, capture_output=True, text=True)
    if p.returncode != 0 or not os.path.isfile(dest):
        raise NotApplicable(f"the sung-only slice could not be cut ({(p.stderr or '').strip()[-200:] or 'ffmpeg missing?'})")
    got = probe_seconds(dest)
    if not got or abs(got - seconds) > FRAME_TOLERANCE_S:
        raise NotApplicable(f"the sung-only slice is {got} s, not {seconds} s — refusing to submit a wrong length")
    with open(side, "w", encoding="utf-8") as fh:
        json.dump(want, fh)
    return dest


def _has_audio(path: str) -> bool:
    p = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=codec_type",
                        "-of", "csv=p=0", path], capture_output=True, text=True)
    return p.returncode == 0 and "audio" in p.stdout


def pad_to_window(clip_in: str, clip_out: str, t0: float, window_seconds: float, ffmpeg: str = "ffmpeg") -> str:
    """The rendered sung-only clip back in WINDOW shape: t0 of the first frame held at the
    head (mouth at rest), the last frame held to the window's length, the clip's own audio
    delayed by t0. The judge and the cutter both assume a clip that starts where the window
    starts and runs the window's length (memory `assembly-drift-blames-the-cutter`)."""
    delay_ms = int(round(t0 * 1000))
    got_in = probe_seconds(clip_in)
    overrun = t0 + got_in - window_seconds
    if overrun > PROVIDER_OVERRUN_TOLERANCE_S:
        raise NotApplicable(f"the rendered take is {got_in:.2f} s; with the {t0:.2f} s head put back it overruns the "
                            f"{window_seconds:g} s window by {overrun:.2f} s — padding would cut the take's tail; refusing")
    if not _has_audio(clip_in):
        raise NotApplicable("the rendered take carries no audio stream — a sung take must be heard; refusing to pad it "
                            "(ffmpeg would drop the delay silently and the clip would land unjudged)")
    cmd = [ffmpeg, "-y", "-v", "error", "-nostdin", "-i", clip_in,
           "-vf", f"tpad=start_duration={t0:.3f}:start_mode=clone:stop_mode=clone:stop_duration={window_seconds:.3f}",
           "-af", f"adelay={delay_ms}:all=1,apad",
           "-t", f"{window_seconds:.3f}",
           "-c:v", "libx264", "-preset", "veryfast", "-crf", "16", "-pix_fmt", "yuv420p",
           "-c:a", "aac", "-b:a", "192k", clip_out]
    p = subprocess.run(cmd, capture_output=True, text=True)
    if p.returncode != 0 or not os.path.isfile(clip_out):
        raise NotApplicable(f"the take could not be padded back to window shape ({(p.stderr or '').strip()[-200:]})")
    got = probe_seconds(clip_out)
    if not got or abs(got - window_seconds) > FRAME_TOLERANCE_S:
        raise NotApplicable(f"the padded take is {got} s, not the window's {window_seconds:g} s")
    return clip_out


if __name__ == "__main__":
    print("sung_only.py is reached through `paid_take.py --route reapi-seedance --sung-only`", file=sys.stderr)
    raise SystemExit(2)
