"""
Helper script to generate a multi-source mashup video in Target/ for empirical testing.
Cắt các đoạn từ:
- Sintel 15m (3 đoạn x 30s)
- Bunny (1 đoạn x 20s)
- Tears of Steel 12m (1 đoạn x 30s)
Sau đó ghép (concatenate) tuần tự cả video + audio thành Target/target_composite_mashup.mp4.
"""
import subprocess
import sys
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8")

from src.core.paths import APP_ROOT, DATA_DIR, TARGET_DIR, TEMP_DIR, get_ffmpeg_path

def build_mashup():
    ffmpeg = get_ffmpeg_path()
    TEMP_DIR.mkdir(parents=True, exist_ok=True)
    TARGET_DIR.mkdir(parents=True, exist_ok=True)

    sintel_src = DATA_DIR / "ref_sintel_15m.mp4"
    tears_src = DATA_DIR / "ref_tears_of_steel_12m.mp4"
    bunny_src = DATA_DIR / "sample_ref_bunny.mp4"

    clips = [
        ("sintel_1", sintel_src, "00:01:00", "00:01:30", "Sintel Đoạn 1 (30s)"),
        ("bunny_mid", bunny_src, "00:00:05", "00:00:25", "Bunny Đoạn giữa (20s)"),
        ("sintel_2", sintel_src, "00:05:30", "00:06:00", "Sintel Đoạn 2 (30s)"),
        ("tears_mid", tears_src, "00:02:00", "00:02:30", "Tears of Steel Đoạn (30s)"),
        ("sintel_3", sintel_src, "00:09:15", "00:09:45", "Sintel Đoạn 3 (30s)"),
    ]

    clip_paths = []
    print("[*] Đang cắt và chuẩn hóa 5 phân đoạn video + audio...")
    for name, src, start, end, desc in clips:
        out_clip = TEMP_DIR / f"clip_{name}.mp4"
        cmd = [
            ffmpeg, "-y",
            "-ss", start,
            "-to", end,
            "-i", str(src),
            "-vf", "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2,fps=24",
            "-c:v", "libx264",
            "-preset", "fast",
            "-crf", "22",
            "-c:a", "aac",
            "-ar", "44100",
            "-ac", "2",
            str(out_clip)
        ]
        res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if res.returncode != 0:
            raise RuntimeError(f"Lỗi khi cắt {name}: {res.stderr.decode('utf-8', errors='ignore')}")
        clip_paths.append(out_clip)
        print(f"  [OK] Đã tạo {desc} -> {out_clip.name}")

    # Tạo file danh sách concat
    concat_file = TEMP_DIR / "concat_list.txt"
    with open(concat_file, "w", encoding="utf-8") as f:
        for p in clip_paths:
            # Format cho concat demuxer: file 'path'
            f.write(f"file '{p.resolve().as_posix()}'\n")

    target_mashup = TARGET_DIR / "target_composite_mashup.mp4"
    print(f"[*] Đang ghép các đoạn thành target hoàn chỉnh: {target_mashup.name}...")
    concat_cmd = [
        ffmpeg, "-y",
        "-f", "concat",
        "-safe", "0",
        "-i", str(concat_file),
        "-c", "copy",
        str(target_mashup)
    ]
    res = subprocess.run(concat_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if res.returncode != 0:
        raise RuntimeError(f"Lỗi khi ghép mashup: {res.stderr.decode('utf-8', errors='ignore')}")

    print(f"[HOÀN TẤT] Target composite mashup đã sẵn sàng tại: {target_mashup}")

if __name__ == "__main__":
    build_mashup()
