#!/usr/bin/env python3
"""Verify and apply a constant timing correction from immutable source footage.

Rate candidates remain provisional until this stage measures stable timing within
80 ms. Each candidate is written separately, remeasured and checked for visible video
coverage (one frame tolerance). An unavailable, worse, unstable or short candidate is
discarded; the previous selection survives. Identical accepted/rejected requests reuse
the persisted decision without encoding or measuring again. Full source/reference
hashes, window geometry and transform settings identify the request.

Positive offsets mean the mouth is early: use preceding real frames, then an explicit
head hold if required. Negative offsets consume head footage and may require a tail
hold. Reports identify actual visible synthetic intervals, excluding padding outside
the cut; available real head/tail footage is recomputed after each transform.
"""
from __future__ import annotations

import argparse
import json
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))   # a script loaded by path (tests) still finds its siblings
import raplib  # noqa: E402
from sync_evidence import evidence, file_hash
from timing_edits import capture_source, source_problem, output_current, edit_id, apply_window, persist, video_seconds, restore_previous
import os
import shutil
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sync_profile import (MAX_SPREAD_MS, MIN_SPANS, SHORT_SPANS_MIN, WILD_MIN,  # noqa: E402
                          clip_resolver, profile_window, robust)

MAX_HOLD_MS = 400 if os.environ.get("RAP_BAR") == "keep" else 350   # beyond this the hold is worse than the drift
MIN_SHIFT_MS = 60        # below this it is inside the noise; leave it alone
# A steady offset (IQR spread at or under this) is slid even past MAX_HOLD_MS — see the
# branch below. RAP_STEADY_SLIDE=0 restores the old refuse-and-re-render behaviour.
STEADY_SLIDE = os.environ.get("RAP_STEADY_SLIDE", "1") != "0"
STEADY_SPREAD_MS = 75


def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        raise SystemExit(f"ffmpeg failed:\n{r.stderr[-1500:]}")


def keep(src: str, dst: str) -> None:
    """Copy src to dst unless they are already the same file.

    --out-selection rewrites the selection onto the shifted clips, so a SECOND run
    resolves src to the very file it is about to write. shutil.copyfile raises
    SameFileError on that, which killed the re-run path the sync-gate itself tells
    the operator to take ("re-run --from slide"). Re-running must be a no-op, not a
    crash.
    """
    if os.path.abspath(src) != os.path.abspath(dst):
        shutil.copyfile(src, dst)


def duration(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 slack_plan(off_ms: int, head_sec: float, tail_sec: float) -> tuple[float, int]:
    """(in_sec, hold_ms): where to start reading the SOURCE, and how much of the
    correction still has to come from a held frame.

    The source may carry real frames around the window — `head_sec` before it (the
    assembly skips them) and `tail_sec` after. A mouth-EARLY take (+off) is fixed by
    showing frames from earlier in the source: in = head - off, real while head covers
    it. A mouth-LATE take (-off) by starting later: in = head + |off|; the window's END
    is then real frames while the tail covers it, a held last frame for the rest. Only
    the held remainder is measured against MAX_HOLD_MS. With no slack this is exactly the old
    behaviour (in = 0, hold = |off|)."""
    sec = abs(off_ms) / 1000.0
    if off_ms > 0:
        real = min(sec, max(0.0, head_sec))
        return round(head_sec - real, 4), int(round((sec - real) * 1000))
    if off_ms < 0:
        # The frames to advance INTO always exist (they are the clip's own); what the
        # tail slack buys is the END — without it the last |off| of the window is a
        # held last frame, with it the clip simply keeps playing.
        real = min(sec, max(0.0, tail_sec))
        return round(head_sec + sec, 4), int(round((sec - real) * 1000))
    return round(max(0.0, head_sec), 4), 0


def held_intervals(start, window_sec, source_sec, off_ms, head_sec=0.0, tail_sec=0.0):
    """Exact visible padding in song time, excluding padding beyond the chosen cut."""
    inset, hold = slack_plan(off_ms, head_sec, tail_sec)
    if off_ms > 0 and hold:
        return [{"startSec": start, "endSec": min(start + window_sec, start + hold / 1000), "edge": "head"}]
    if off_ms < 0:
        lo = start + max(0, source_sec - inset)
        hi = min(start + window_sec, lo + max(hold / 1000, 0.5))
        if hi > lo:
            return [{"startSec": lo, "endSec": hi, "edge": "tail"}]
    return []


def shift(src: str, dst: str, off_ms: int, window_sec: float,
          head_sec: float = 0.0, tail_sec: float = 0.0) -> None:
    # Same-file guard: on a re-run src resolves to the shifted clip, which is dst. ffmpeg
    # reading and writing one path truncates it to garbage — a silent corruption, unlike
    # the SameFileError the copy path at least raised. Stage through a temp and move.
    if os.path.abspath(src) == os.path.abspath(dst):
        tmp = dst + ".shift.tmp.mp4"
        shift(src, tmp, off_ms, window_sec, head_sec, tail_sec)
        os.replace(tmp, dst)
        return
    in_sec, hold_ms = slack_plan(off_ms, head_sec, tail_sec)
    hold = hold_ms / 1000.0
    vf = [f"trim=start={in_sec},setpts=PTS-STARTPTS"] if in_sec > 0 else []
    af = [f"atrim=start={in_sec},asetpts=PTS-STARTPTS"] if in_sec > 0 else []
    if hold_ms and off_ms > 0:        # mouth early, slack exhausted -> hold the first frame
        vf.append(f"tpad=start_duration={hold}:start_mode=clone")
        af.append(f"adelay={hold_ms}|{hold_ms}")
    elif off_ms < 0:                  # mouth late -> any shortfall holds the last frame
        vf.append(f"tpad=stop_duration={max(hold, 0.5)}:stop_mode=clone")
        af.append("apad")
    run(["ffmpeg", "-v", "error", "-y", "-i", src,
         *(["-vf", ",".join(vf)] if vf else []), *(["-af", ",".join(af)] if af else []),
         "-t", f"{window_sec}", "-c:v", "libx264", "-preset", "medium", "-crf", "18",
         "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", dst])




def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--song", required=True)
    ap.add_argument("--selection", required=True)
    ap.add_argument("--vocal-map", required=True)
    ap.add_argument("--stage", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--json")
    ap.add_argument("--out-selection",
                    help="write a selection pointing at the shifted clips. Without this "
                         "the assembler keeps using the ORIGINAL paths and the slide "
                         "never reaches the film.")
    a = ap.parse_args()

    sel = json.load(open(a.selection, encoding="utf-8"))
    silent = [(float(g["start"]), float(g["end"]))
              for g in json.load(open(a.vocal_map, encoding="utf-8")).get("silentStretches", [])]
    song_end = float(sel.get("songEnd", 1e9))
    os.makedirs(a.out, exist_ok=True)

    resolve = clip_resolver(sel, a.stage)
    by_id = {c["id"]: c for c in sel.get("clips", [])}
    rows, review = [], []
    for window in sel["vocalMap"]:
        record, edit, candidate = None, {}, None
        try:
            perf = window.get("performerClip")
            if not perf:
                continue
            current = resolve(perf)
            record = by_id.get(perf)
            if current is None or record is None:
                if record:
                    restore_previous(record, window, record.get("rejectedTimingEdit") or record.get("timingEdit") or {})
                review.append({"clip": perf, "reason": "missing-source", "offsetMs": None})
                continue
            if window.get("lipSyncExempt"):
                keep(current, os.path.join(a.out, f"{perf}.mp4"))
                continue
            start, finish = float(window["start"]), float(window["end"])
            window_sec = finish - start
            analysis_end = min(max(start + 8.0, finish), song_end)
            edit = record.get("rejectedTimingEdit") or record.get("timingEdit") or {}
            if edit and source_problem(edit):
                restore_previous(record, window, edit)
                review.append({"clip": perf, "reason": source_problem(edit), "offsetMs": None})
                continue
            if not edit:
                source_duration, _ = video_seconds(current)
                if not source_duration:
                    review.append({"clip": perf, "reason": "source-video-unmeasurable", "offsetMs": None})
                    continue
                edit = capture_source(current, window, a.out, source_duration)
                record["timingEdit"] = edit
            rated = edit.get("rate")
            if rated and not output_current(rated):
                restore_previous(record, window, edit)
                review.append({"clip": perf, "reason": "rate-output-changed", "offsetMs": None})
                continue
            source = rated["path"] if rated else edit["source"]["path"]
            source_sec = duration(source)
            head = float((rated or edit["source"]).get("headSec") or 0)
            real_end = float((rated or edit["source"]).get("realEndSec", edit["source"]["durationSec"]))
            tail = max(0.0, real_end - head - window_sec)
            request = {"version": 1, "inputSha256": file_hash(source), "rateId": (rated or {}).get("id"),
                       "songSha256": file_hash(a.song), "vocalMapSha256": file_hash(a.vocal_map),
                       "start": start, "end": finish, "analysisEnd": analysis_end,
                       "headSec": head, "tailSec": tail, "realEndSec": real_end,
                       "maxSpreadMs": MAX_SPREAD_MS, "maxHoldMs": MAX_HOLD_MS,
                       "steadySlide": STEADY_SLIDE, "steadySpreadMs": STEADY_SPREAD_MS}
            key = edit_id(request)
            previous = edit.get("previousSelection") if rated and not rated.get("verified") else None

            def restore():
                restore_previous(record, window, edit)

            cached = edit.get("shift") or {}
            if cached.get("id") == key and cached.get("candidateRejected"):
                restore()
                review.append({"clip": perf, **cached["report"], "cached": True})
                print(f"{perf}: reused rejected decision — verify the existing take")
                continue
            if cached.get("id") == key and output_current(cached):
                record["path"] = cached["path"]
                record["durationSec"] = cached["durationSec"]
                apply_window(window, cached)
                rows.append({"clip": perf, **cached["report"], "cached": True})
                print(f"{perf}: reused verified timing edit")
                continue
            measured = source
            aligned = os.path.join(a.out, f"{perf}-{key[:12]}.aligned.mp4")
            if head > 0:
                shift(source, aligned, 0, source_sec - head, head, tail)
                measured = aligned
            before = robust(profile_window(a.song, measured, start, analysis_end, silent))
            if measured != source:
                os.remove(measured)
            off, count, spread, wild = before
            valid_before = off is not None and count >= SHORT_SPANS_MIN and spread is not None \
                and spread <= MAX_SPREAD_MS and wild < WILD_MIN
            candidate = os.path.join(a.out, f"{perf}-{key[:12]}.candidate.mp4")
            dst = os.path.abspath(os.path.join(a.out, f"{perf}.mp4"))
            if dst == edit["source"].get("originPath"):
                dst = os.path.abspath(os.path.join(a.out, f"{perf}-{key[:16]}.mp4"))
            reason = None
            after = None
            if not valid_before:
                reason = "unmeasurable" if off is None else "unstable-or-insufficient-spans"
            else:
                hold = slack_plan(off, head, tail)[1]
                if hold > MAX_HOLD_MS and not (STEADY_SLIDE and spread <= STEADY_SPREAD_MS):
                    reason = "hold-limit"
                else:
                    applied = off if abs(off) >= MIN_SHIFT_MS else 0
                    output_sec = max(window_sec, min(source_sec - head, window_sec + tail))
                    if applied or head:
                        shift(source, candidate, applied, output_sec, head, tail)
                        after = robust(profile_window(a.song, candidate, start, analysis_end, silent))
                    else:
                        keep(source, candidate)
                        after = before
                    new, new_count, new_spread, new_wild = after
                    if new is None or new_count < SHORT_SPANS_MIN:
                        reason = "candidate-unmeasurable"
                    elif new_wild >= WILD_MIN or new_spread is None or new_spread > MAX_SPREAD_MS \
                            or new_spread > spread + 50:
                        reason = "candidate-destabilised"
                    elif abs(new) > 80 or (applied and abs(new) >= abs(off)):
                        reason = "candidate-not-improved"
            if not reason:
                video_duration, frame_tolerance = video_seconds(candidate)
                if video_duration is None or video_duration + frame_tolerance < window_sec - 0.001:
                    reason = "candidate-short-video"
            if reason:
                if os.path.isfile(candidate):
                    os.remove(candidate)
                restore()
                report = {"reason": reason, "offsetMs": off, "beforeMs": off,
                          "afterMs": after[0] if after else None, "candidateRejected": True,
                          "evidence": evidence(record["path"], a.song, start, finish)}
                edit["shift"] = {"id": key, "request": request, "candidateRejected": True, "report": report}
                review.append({"clip": perf, **report})
                print(f"{perf}: candidate rejected ({reason}); previous selection retained")
                continue
            inset, held_ms = slack_plan(applied, head, tail)
            pad_head = held_ms / 1000 if applied > 0 else 0.0
            new_real_end = max(0.0, real_end - inset) + pad_head
            output_sec = duration(candidate)
            synthetic = []
            if pad_head:
                synthetic.append([0.0, min(pad_head, output_sec)])
            if new_real_end < output_sec:
                synthetic.append([new_real_end, output_sec])
            holds = [{"startSec": start + lo, "endSec": start + min(hi, window_sec),
                      "edge": "head" if lo == 0 else "tail"}
                     for lo, hi in synthetic if lo < window_sec and hi > lo]
            os.replace(candidate, dst)
            report = {"beforeMs": off, "afterMs": after[0], "verified": True,
                      "heldMs": round(sum(x["endSec"] - x["startSec"] for x in holds) * 1000),
                      "heldSpans": holds, "evidence": evidence(dst, a.song, start, finish)}
            operation = {"id": key, "request": request, "path": dst, "outputSha256": file_hash(dst),
                         "durationSec": output_sec, "headSec": 0.0, "tailSec": max(0, new_real_end - window_sec),
                         "realEndSec": new_real_end, "syntheticSpans": synthetic,
                         "inSec": inset, "padHeadSec": pad_head, "verified": True, "report": report}
            edit["shift"] = operation
            if rated:
                rated["verified"] = True
            record.pop("rejectedTimingEdit", None)
            record.update(path=dst, durationSec=output_sec, timingEdit=edit)
            apply_window(window, operation)
            rows.append({"clip": perf, **report})
            if not applied:
                print(f"{perf:<6} already on the bar — verified")
            else:
                print(f"{perf:<6} shifted {-off:+d}ms -> {after[0]:+d}ms"
                      + (f" ({abs(off) - held_ms}ms from real frames, {held_ms}ms held)" if head or tail else "")
                      + (f" (STEADY past the {MAX_HOLD_MS}ms ceiling)" if held_ms > MAX_HOLD_MS else ""))
        except (Exception, SystemExit) as error:
            if candidate and os.path.isfile(candidate):
                os.remove(candidate)
            if record:
                restore_previous(record, window, edit)
            review.append({"clip": window.get("performerClip"), "reason": "processing-error", "offsetMs": None,
                           "candidateRejected": True, "detail": str(error)[:300]})
            print(f"{window.get('performerClip')}: correction could not be verified; previous selection retained", file=sys.stderr)
    if a.out_selection:
        persist(a.out_selection, sel)
    if a.json:
        persist(a.json, {"schemaVersion": 2, "shifted": rows, "needsRerender": review,
                         "candidateRejected": [r for r in review if r.get("candidateRejected")]})
    return 0


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