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_shots():
    shot_files = [
        VIDEOS_DIR / "prologue_shot_01_lang_que_198x_10s.mp4",
        VIDEOS_DIR / "prologue_shot_02_ngam_kieu_10s.mp4",
        VIDEOS_DIR / "prologue_shot_03_xuyen_khong_10s.mp4",
        VIDEOS_DIR / "prologue_shot_04_gia_tinh_trieu_minh_10s.mp4"
    ]

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

    out_path = VIDEOS_DIR / "prologue_hoai_niem_198x_to_gia_tinh_40s.mp4"
    temp_out = VIDEOS_DIR / "temp_prologue_40s.mp4"

    # Construct ffmpeg filter_complex concat to preserve both video & audio
    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 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 Master Prologue with full audio: {out_path.name}")
    return True

if __name__ == "__main__":
    merge_shots()
