import subprocess
from pathlib import Path

from app.config import ASSETS_DIR, CATEGORIES, FFMPEG_PATH
from app.render.duration import compute_duration
from app.render.frame_builder import build_background_layer, build_text_layer

FPS = 30
ZOOM_END = 1.08
OUT_WIDTH, OUT_HEIGHT = 1080, 1920


def render_video(category_slug: str, fact_text: str, output_path: Path) -> Path:
    category = CATEGORIES[category_slug]
    duration = compute_duration(fact_text)

    tmp_dir = output_path.parent / "_frames"
    tmp_dir.mkdir(parents=True, exist_ok=True)
    bg_path = tmp_dir / f"{category_slug}_bg.png"
    text_path = tmp_dir / f"{category_slug}_text.png"

    build_background_layer(category_slug).save(bg_path)
    build_text_layer(fact_text).save(text_path)

    music_path = ASSETS_DIR / "music" / category["music_file"]

    total_frames = max(1, int(FPS * duration))
    zoom_increment = (ZOOM_END - 1.0) / total_frames
    audio_fade_start = max(duration - 1, 0)

    filter_complex = (
        f"[0:v]zoompan=z='min(zoom+{zoom_increment:.8f},{ZOOM_END})':"
        f"d={total_frames}:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':"
        f"s={OUT_WIDTH}x{OUT_HEIGHT}:fps={FPS}[bgz];"
        f"[1:v]fade=t=in:st=0:d=0.6:alpha=1[txt];"
        f"[bgz][txt]overlay=0:0:format=auto[vout];"
        f"[2:a]afade=t=out:st={audio_fade_start:.2f}:d=1[aout]"
    )

    cmd = [
        FFMPEG_PATH, "-y",
        "-loop", "1", "-i", str(bg_path),
        "-loop", "1", "-i", str(text_path),
        "-stream_loop", "-1", "-i", str(music_path),
        "-filter_complex", filter_complex,
        "-map", "[vout]", "-map", "[aout]",
        "-t", f"{duration:.2f}",
        "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p",
        "-c:a", "aac", "-b:a", "192k",
        str(output_path),
    ]

    output_path.parent.mkdir(parents=True, exist_ok=True)
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"ffmpeg failed:\n{result.stderr}")
    return output_path
