#!/usr/bin/env python3
"""Normalize MP4s for mobile 9:16 playback.

This is intentionally a post-render boundary: it does not alter source clips;
it writes a square-pixel 1080x1920 H.264 export with explicit SAR/DAR metadata.
"""

from __future__ import annotations

import argparse
import json
import subprocess
from pathlib import Path


TARGET_WIDTH = 1080
TARGET_HEIGHT = 1920


def normalize_vertical_mp4(input_path: Path, output_path: Path) -> dict[str, object]:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    video_filter = (
        f"scale={TARGET_WIDTH}:{TARGET_HEIGHT}:force_original_aspect_ratio=increase,"
        f"crop={TARGET_WIDTH}:{TARGET_HEIGHT},"
        "setsar=1,setdar=9/16,format=yuv420p"
    )
    cmd = [
        "ffmpeg",
        "-y",
        "-hide_banner",
        "-loglevel",
        "error",
        "-i",
        str(input_path),
        "-vf",
        video_filter,
        "-c:v",
        "libx264",
        "-preset",
        "veryfast",
        "-crf",
        "18",
        "-movflags",
        "+faststart",
        "-an",
        str(output_path),
    ]
    subprocess.check_call(cmd)
    probe = json.loads(
        subprocess.check_output(
            [
                "ffprobe",
                "-v",
                "error",
                "-select_streams",
                "v:0",
                "-show_entries",
                "stream=width,height,sample_aspect_ratio,display_aspect_ratio",
                "-show_entries",
                "format=duration",
                "-of",
                "json",
                str(output_path),
            ],
            text=True,
        )
    )
    stream = probe["streams"][0]
    return {
        "output_path": str(output_path),
        "width": stream["width"],
        "height": stream["height"],
        "sample_aspect_ratio": stream.get("sample_aspect_ratio"),
        "display_aspect_ratio": stream.get("display_aspect_ratio"),
        "duration": float(probe.get("format", {}).get("duration", 0.0)),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Normalize MP4 to mobile-safe 9:16 1080x1920.")
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    print(json.dumps(normalize_vertical_mp4(args.input, args.output), indent=2))


if __name__ == "__main__":
    main()
