"""End-anchored ffmpeg trim for storyboard videos.

Playwright's recorded video timeline does NOT align 1:1 with Python wall-clock —
recording starts before the first navigation finishes and the file is typically
a few seconds longer than the wall-clock window we measured. The storyboard
ends right before ``context.close()``, which IS the video's tail. So we anchor
on the END.
"""
from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path


def _probe_duration(path: Path) -> float | None:
    if not shutil.which("ffprobe"):
        return None
    r = subprocess.run(
        [
            "ffprobe", "-v", "error", "-show_entries", "format=duration",
            "-of", "default=noprint_wrappers=1:nokey=1", str(path),
        ],
        capture_output=True, text=True, check=False,
    )
    try:
        return float(r.stdout.strip())
    except ValueError:
        return None


def trim_video(out: Path, start_ms: int, end_ms: int) -> None:
    if not shutil.which("ffmpeg"):
        print(
            "[record] 安装 ffmpeg 可自动裁剪开头加载段。",
            file=sys.stderr,
        )
        return
    if end_ms <= start_ms:
        return

    storyboard_ms = end_ms - start_ms
    lead_ms = 80
    tail_ms = 200
    keep_ms = storyboard_ms + lead_ms + tail_ms

    video_dur = _probe_duration(out)
    if video_dur is None:
        # Fallback: start-anchored (legacy, may be off if recording drifts).
        start_s = max(0.0, (start_ms - lead_ms) / 1000.0)
        duration_s = keep_ms / 1000.0
    else:
        # End-anchored: video tail == storyboard end == context.close.
        start_s = max(0.0, video_dur - keep_ms / 1000.0)
        duration_s = video_dur - start_s

    tmp = out.with_suffix(out.suffix + ".trim.webm")
    cmd = [
        "ffmpeg", "-y", "-loglevel", "error",
        "-ss", f"{start_s:.3f}", "-i", str(out),
        "-t", f"{duration_s:.3f}",
        "-c:v", "libvpx", "-b:v", "2M",
        "-deadline", "realtime", "-cpu-used", "4",
        "-an", str(tmp),
    ]
    print(
        f"[record] ffmpeg trim (re-encode, end-anchored): "
        f"skip {start_s:.2f}s, keep {duration_s:.2f}s "
        f"(video={video_dur and f'{video_dur:.2f}s'}, storyboard={storyboard_ms/1000:.2f}s)",
        file=sys.stderr,
    )
    r = subprocess.run(cmd, check=False)
    if r.returncode == 0 and tmp.exists() and tmp.stat().st_size > 0:
        os.replace(tmp, out)
    else:
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass
        print("[record] ffmpeg 裁剪失败，保留原始视频。", file=sys.stderr)
