import argparse
import subprocess


def generate_moving_text_video(file_name: str, text: str) -> None:
    """Generate a video with text scrolling horizontally across the center of the screen."""
    width = 1280
    height = 720
    duration = 5

    filter_complex = (
        f"color=c=white:s={width}x{height}:d={duration}[bg];"
        f"[bg]drawtext=text='{text}':fontsize=48:fontcolor=black:"
        f"x=w-mod(t*200\\,w+tw):y=(h-th)/2"
    )

    cmd = [
        "ffmpeg", "-y",
        "-f", "lavfi",
        "-i", f"color=c=white:s={width}x{height}:d={duration}",
        "-vf", f"drawtext=text='{text}':fontsize=48:fontcolor=black:x=w-mod(t*200\\,w+tw):y=(h-th)/2",
        "-c:v", "libx264",
        "-t", str(duration),
        file_name
    ]

    subprocess.run(cmd, check=True)


def create_slideshow_from_images(output_file_name: str, input_file_names: list, seconds_per_image: float) -> None:
    """Create a slideshow video from a list of images."""
    concat_file = "concat_list.txt"

    with open(concat_file, "w") as f:
        for img in input_file_names:
            f.write(f"file '{img}'\n")
            f.write(f"duration {seconds_per_image}\n")
        if input_file_names:
            f.write(f"file '{input_file_names[-1]}'\n")

    cmd = [
        "ffmpeg", "-y",
        "-f", "concat",
        "-safe", "0",
        "-i", concat_file,
        "-vsync", "vfr",
        "-pix_fmt", "yuv420p",
        "-c:v", "libx264",
        output_file_name
    ]

    subprocess.run(cmd, check=True)

    import os
    os.remove(concat_file)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Video tools")
    subparsers = parser.add_subparsers(dest="command", required=True)

    moving_text_parser = subparsers.add_parser("moving_text", help="Generate video with scrolling text")
    moving_text_parser.add_argument("file_name", help="Output video file name")
    moving_text_parser.add_argument("text", help="Text to scroll across the screen")

    slideshow_parser = subparsers.add_parser("slideshow", help="Create slideshow from images")
    slideshow_parser.add_argument("output_file_name", help="Output video file name")
    slideshow_parser.add_argument("input_file_names", nargs="+", help="Input image file names")
    slideshow_parser.add_argument("--seconds", type=float, default=3.0, help="Seconds per image (default: 3.0)")

    args = parser.parse_args()

    if args.command == "moving_text":
        generate_moving_text_video(args.file_name, args.text)
    elif args.command == "slideshow":
        create_slideshow_from_images(args.output_file_name, args.input_file_names, args.seconds)
