import sys
import subprocess
import shutil
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.parent
VIDEOS_DIR = BASE_DIR / "04_Assets" / "videos"
EXPORTS_DIR = BASE_DIR / "06_Exports"

def merge_review():
    parts = [
        VIDEOS_DIR / "thap_ngu_nien_intro_complete_20s.mp4",
        VIDEOS_DIR / "prologue_hoai_niem_198x_to_gia_tinh_40s.mp4",
        VIDEOS_DIR / "ep01_scene01_master_50s.mp4"
    ]

    for p in parts:
        if not p.exists():
            print(f"[!] Thiếu file đầu vào: {p.name}")
            return False

    out_file = VIDEOS_DIR / "thap_ngu_nien_ep01_intro_prologue_scene01_110s.mp4"
    temp_out = VIDEOS_DIR / "temp_review_full_110s.mp4"

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

    filter_str = "".join([f"[{i}:v:0][{i}:a:0]" for i in range(len(parts))])
    filter_str += f"concat=n={len(parts)}: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("=== Đang ghép nối bản Review Hoàn chỉnh (Intro + Prologue + Scene 1) ===")
    res = subprocess.run(cmd, capture_output=True, text=True)
    if res.returncode != 0:
        print("[!] FFmpeg Lỗi:", res.stderr)
        return False

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

    # Copy một bản sang 06_Exports/ để lưu trữ chuẩn
    export_dest = EXPORTS_DIR / "thap_ngu_nien_ep01_intro_prologue_scene01_110s.mp4"
    shutil.copy2(out_file, export_dest)

    print(f"\n[OK] Xuất thành công bản Review hoàn chỉnh:")
    print(f"  -> File chính: {out_file}")
    print(f"  -> Bản Export: {export_dest}")
    return True

if __name__ == "__main__":
    merge_review()
