#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
THẬP NGŨ NIÊN - ASSEMBLE ROADSHOW FEATURE CUT EPISODES 1 TO 4 (900s / 15m00s)
Ghép 4 tập phim điện ảnh đầu tiên thành bản Roadshow dài 15 phút tròn,
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"

episodes = [
    EXPORTS_DIR / "thap_ngu_nien_ep01_grand_feature_master_450s_7m30s.mp4",
    EXPORTS_DIR / "thap_ngu_nien_ep02_grand_feature_master_190s_3m10s.mp4",
    EXPORTS_DIR / "thap_ngu_nien_ep03_grand_feature_master_140s_2m20s.mp4",
    EXPORTS_DIR / "thap_ngu_nien_ep04_grand_feature_master_120s_2min.mp4"
]

output_roadshow = EXPORTS_DIR / "thap_ngu_nien_ep01_to_ep04_roadshow_feature_cut_900s_15min.mp4"

for i, p in enumerate(episodes, 1):
    if not p.exists():
        print(f"[!] Lỗi: Thiếu tập #{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(episodes):
    inputs.extend(["-i", str(p)])
    filter_parts.append(f"[{i}:v:0][{i}:a:0]")

n = len(episodes)
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_roadshow)
]

print(f"🎬 Bắt đầu ghép nối 4 Tập thành Roadshow Feature Cut 15 Phút Tròn (900s)...")
print(f"   Đích xuất: {output_roadshow}")
res = subprocess.run(cmd, capture_output=True, text=True)

if res.returncode == 0 and output_roadshow.exists():
    size_mb = output_roadshow.stat().st_size / (1024 * 1024)
    print(f"\n[✓] GHÉP THÀNH CÔNG ROADSHOW FEATURE CUT 4 TẬP (15 PHÚT)!")
    print(f"    File: {output_roadshow.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)
