#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
THẬP NGŨ NIÊN - ASSEMBLE EPISODE 4 GRAND FEATURE MASTER (120s / 2m00s)
Ghép 9 phân cảnh của Tập 4 thành Grand Feature Master hoàn chỉnh,
bảo toàn 100% âm thanh AAC qua FFmpeg filter_complex concat ([v][a]).
"""

import os
import sys
import subprocess
from pathlib import Path

if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

BASE_DIR = Path(__file__).resolve().parent.parent
EXPORTS_DIR = BASE_DIR / "06_Exports"
EXPORTS_DIR.mkdir(parents=True, exist_ok=True)

ep04_scenes = [
    EXPORTS_DIR / "ep04_scene01_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene02_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene03_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene04_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene05_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene06_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene07_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene08_cinematic_master.mp4",
    EXPORTS_DIR / "ep04_scene09_cinematic_master.mp4"
]

output_master = EXPORTS_DIR / "thap_ngu_nien_ep04_grand_feature_master_120s_2min.mp4"

for i, p in enumerate(ep04_scenes, 1):
    if not p.exists():
        print(f"[!] Lỗi: Thiếu scene #{i}: {p}")
        sys.exit(1)

ffmpeg_exe = "ffmpeg"
candidates = [
    Path(r"C:\ffmpeg\bin\ffmpeg.exe"),
    Path(r"C:\Program Files\ffmpeg\bin\ffmpeg.exe"),
]
for c in candidates:
    if c.exists():
        ffmpeg_exe = str(c)
        break

inputs = []
filter_parts = []
for i, p in enumerate(ep04_scenes):
    inputs.extend(["-i", str(p)])
    filter_parts.append(f"[{i}:v:0][{i}:a:0]")

n = len(ep04_scenes)
concat_filter = f"{''.join(filter_parts)}concat=n={n}:v=1:a=1[v][a]"

cmd = [
    ffmpeg_exe, "-y",
    *inputs,
    "-filter_complex", concat_filter,
    "-map", "[v]",
    "-map", "[a]",
    "-c:v", "libx264",
    "-crf", "18",
    "-preset", "slow",
    "-c:a", "aac",
    "-b:a", "192k",
    "-ar", "48000",
    str(output_master)
]

print(f"🎬 Bắt đầu ghép nối 9 phân cảnh Tập 4 thành Grand Feature Master 120s...")
print(f"   Đích xuất: {output_master}")
res = subprocess.run(cmd, capture_output=True, text=True)

if res.returncode == 0 and output_master.exists():
    size_mb = output_master.stat().st_size / (1024 * 1024)
    print(f"\n[✓] GHÉP THÀNH CÔNG GRAND FEATURE MASTER TẬP 4!")
    print(f"    File: {output_master.name}")
    print(f"    Dung lượng: {size_mb:.2f} MB")
else:
    print(f"[!] Thất bại khi ghép:\n{res.stderr}")
    sys.exit(1)
