import os
import sys
import subprocess
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent.parent
VIDEOS_DIR = BASE_DIR / "04_Assets" / "videos"

def merge_scene01():
    shot_files = [
        VIDEOS_DIR / f"ep01_scene01_shot{i:02d}_10s.mp4" for i in range(1, 6)
    ]

    for f in shot_files:
        if not f.exists():
            print(f"[!] File does not exist: {f.name}")
            return False

    out_path = VIDEOS_DIR / "ep01_scene01_master_50s.mp4"
    temp_out = VIDEOS_DIR / "temp_scene01_50s.mp4"

    cmd = ["ffmpeg", "-y"]
    for f in shot_files:
        cmd.extend(["-i", str(f)])

    filter_str = "".join([f"[{i}:v:0][{i}:a:0]" for i in range(len(shot_files))])
    filter_str += f"concat=n={len(shot_files)}:v=1:a=1[v][a]"

    cmd.extend([
        "-filter_complex", filter_str,
        "-map", "[v]",
        "-map", "[a]",
        "-c:v", "libx264",
        "-crf", "18",
        "-preset", "slow",
        "-pix_fmt", "yuv420p",
        "-c:a", "aac",
        "-b:a", "192k",
        "-ar", "48000",
        str(temp_out)
    ])

    print("Running FFmpeg concat for Scene 1 with audio preservation...")
    res = subprocess.run(cmd, capture_output=True, text=True)
    if res.returncode != 0:
        print("[!] FFmpeg error:", res.stderr)
        return False

    if out_path.exists():
        out_path.unlink()
    temp_out.rename(out_path)

    print(f"Successfully generated Scene 1 Master with full audio: {out_path.name}")
    return True

if __name__ == "__main__":
    merge_scene01()
