"""Create alternate playback-speed GIFs for recorded Pong episodes."""

from __future__ import annotations

import argparse
from pathlib import Path

from PIL import Image, ImageSequence


DEFAULT_SPEEDS = {
    "1x": 50,
    "3x": 17,
}


def variant_path(source: Path, label: str) -> Path:
    safe_label = label.replace(".", "p")
    return source.with_name(f"{source.stem}_speed_{safe_label}{source.suffix}")


def load_frames(source: Path) -> list[Image.Image]:
    with Image.open(source) as image:
        return [frame.copy() for frame in ImageSequence.Iterator(image)]


def save_variant(source: Path, label: str, duration_ms: int) -> Path:
    frames = load_frames(source)
    output = variant_path(source, label)
    if not frames:
        return output
    frames[0].save(
        output,
        save_all=True,
        append_images=frames[1:],
        duration=duration_ms,
        loop=0,
        optimize=False,
    )
    return output


def parse_speed(value: str) -> tuple[str, int]:
    label, duration = value.split("=", 1)
    return label, int(duration)


def main() -> None:
    parser = argparse.ArgumentParser(description="Create slower/faster GIF variants.")
    parser.add_argument("gifs", nargs="*", type=Path)
    parser.add_argument("--video-dir", type=Path, default=Path("videos"))
    parser.add_argument(
        "--speed",
        action="append",
        type=parse_speed,
        help="Playback variant as label=duration_ms. Can be repeated.",
    )
    args = parser.parse_args()

    gifs = args.gifs
    if not gifs:
        gifs = sorted(
            path
            for path in args.video_dir.glob("*.gif")
            if "_speed_" not in path.stem
        )

    speeds = dict(args.speed or DEFAULT_SPEEDS.items())
    for gif in gifs:
        for label, duration_ms in speeds.items():
            output = save_variant(gif, label, duration_ms)
            print(f"{gif} -> {output} duration_ms={duration_ms}")


if __name__ == "__main__":
    main()
