"""Build an MP4 video from saved parabola overlay frames."""

from pathlib import Path

import cv2

INPUT_DIR = Path("output_parabola_fits")
RENDERED_OUTPUT_DIR = Path("rendered_output")
OUTPUT_VIDEO = RENDERED_OUTPUT_DIR / "parabola_fit_overlay_video.mp4"
FPS = 30


def collect_overlay_frames(input_dir: Path):
    """Return overlay frame paths in filename order."""
    return sorted(input_dir.glob("*.png"))


def build_video(
    input_dir: Path = INPUT_DIR, output_video: Path = OUTPUT_VIDEO, fps: int = FPS
):
    """Write all PNG frames from input_dir to one MP4 file."""
    output_video.parent.mkdir(parents=True, exist_ok=True)
    frame_paths = collect_overlay_frames(input_dir)
    if not frame_paths:
        raise RuntimeError(f"No PNG frames found in {input_dir}")

    first_frame = cv2.imread(str(frame_paths[0]))
    if first_frame is None:
        raise RuntimeError(f"Failed to read first frame: {frame_paths[0]}")

    height, width = first_frame.shape[:2]
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    writer = cv2.VideoWriter(str(output_video), fourcc, fps, (width, height))

    try:
        for frame_path in frame_paths:
            frame = cv2.imread(str(frame_path))
            if frame is None:
                print(f"Skipping unreadable frame: {frame_path}")
                continue

            if frame.shape[:2] != (height, width):
                frame = cv2.resize(frame, (width, height))

            writer.write(frame)
    finally:
        writer.release()

    print(f"Video saved to {output_video}")


if __name__ == "__main__":
    build_video()
