"""FFmpeg rendering boundary for local preview videos."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
import subprocess

from autoshorts.rendering.ffmpeg_plan import FFmpegConcatPlan, validate_ffmpeg_concat_plan


@dataclass(frozen=True)
class FFmpegRenderResult:
    script_id: str
    output_path: str
    concat_file_path: str
    returncode: int
    stdout: str
    stderr: str
    side_effects: tuple[str, ...] = ("write_concat", "call_ffmpeg", "write_mp4")
    external_calls: tuple[str, ...] = ("ffmpeg",)


def render_ffmpeg_preview_video(plan: FFmpegConcatPlan) -> FFmpegRenderResult:
    """Write the concat file and invoke FFmpeg to create a local MP4 preview."""

    validation = validate_ffmpeg_concat_plan(plan)
    if not validation.is_valid:
        raise ValueError("; ".join(validation.errors))

    concat_path = Path(plan.concat_file_path)
    output_path = Path(plan.output_path)
    concat_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    concat_path.write_text(plan.concat_file_content)

    command = [
        "ffmpeg",
        "-y",
        "-f",
        "concat",
        "-safe",
        "0",
        "-i",
        str(concat_path),
        "-vf",
        f"fps={plan.fps},format=yuv420p",
        "-movflags",
        "+faststart",
        str(output_path),
    ]
    completed = subprocess.run(command, capture_output=True, text=True, check=False)
    if completed.returncode != 0:
        raise RuntimeError(completed.stderr or "ffmpeg failed")

    return FFmpegRenderResult(
        script_id=plan.script_id,
        output_path=str(output_path),
        concat_file_path=str(concat_path),
        returncode=completed.returncode,
        stdout=completed.stdout,
        stderr=completed.stderr,
        side_effects=("write_concat", "call_ffmpeg", "write_mp4"),
        external_calls=("ffmpeg",),
    )
