#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Assemble fresh 40s Prologue Master & 60s Liên Hoàn (Intro + Prologue)
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

BASE_DIR = Path("c:/Projects/KieuStory")
PIPELINE_DIR = BASE_DIR / "05_Production_Pipeline"
if str(PIPELINE_DIR) not in sys.path:
    sys.path.insert(0, str(PIPELINE_DIR))

ASSETS_DIR = BASE_DIR / "04_Assets"
VIDEOS_DIR = ASSETS_DIR / "videos"
AUDIO_DIR = ASSETS_DIR / "audio" / "prologue_inspect"
EXPORTS_DIR = BASE_DIR / "06_Exports"
TEMP_DIR = ASSETS_DIR / "temp_prologue_fresh"

from audio_continuity_engine import AudioContinuityEngine
from contact_sheet_engine import ZeroWasteContactSheet
from antigravity_critic_gate import evaluate_scene_gate

ace = AudioContinuityEngine()

def main():
    print("=" * 70)
    print("🎬 GHÉP NỐI & MASTER PROLOGUE 40S TƯƠI MỚI (MUSE.AI 100%)")
    print("=" * 70)

    # 1. Chuẩn hóa Shot 1 (10s video + 10s audio gốc ngâm Kiều)
    shot01_prep = TEMP_DIR / "fresh_prologue_shot01_prep.mp4"
    cmd1 = [
        "ffmpeg", "-y",
        "-i", str(TEMP_DIR / "fresh_prologue_shot01_10s.mp4"),
        "-i", str(AUDIO_DIR / "prologue_shot_01_lang_que_198x_10s.wav"),
        "-c:v", "copy",
        "-map", "0:v:0", "-map", "1:a:0",
        "-c:a", "aac", "-b:a", "256k", "-ar", "48000",
        "-t", "10.0",
        str(shot01_prep)
    ]
    subprocess.run(cmd1, check=True, capture_output=True)
    print("  [✓] Shot 1 prep 10.0s hoàn tất.")

    # 2. Ghép 4 shots với xfade 0.5s và acrossfade 0.5s
    raw_stitched = TEMP_DIR / "prologue_fresh_stitched_raw_40s.mp4"
    filter_prologue = (
        "[0:v][1:v]xfade=transition=fade:duration=0.5:offset=9.5[v01];"
        "[v01][2:v]xfade=transition=fade:duration=0.5:offset=19.0[v02];"
        "[v02][3:v]xfade=transition=fade:duration=0.5:offset=28.5[vmaster];"
        "[0:a][1:a]acrossfade=d=0.5:c1=qsin:c2=qsin[a01];"
        "[a01][2:a]acrossfade=d=0.5:c1=qsin:c2=qsin[a02];"
        "[a02][3:a]acrossfade=d=0.5:c1=qsin:c2=qsin[amaster]"
    )
    cmd_stitch = [
        "ffmpeg", "-y",
        "-i", str(shot01_prep),
        "-i", str(TEMP_DIR / "fresh_prologue_shot02_prep.mp4"),
        "-i", str(TEMP_DIR / "fresh_prologue_shot03_prep.mp4"),
        "-i", str(TEMP_DIR / "fresh_prologue_shot04_padded.mp4"),
        "-filter_complex", filter_prologue,
        "-map", "[vmaster]", "-map", "[amaster]",
        "-c:v", "libx264", "-crf", "18", "-preset", "slow", "-pix_fmt", "yuv420p",
        "-c:a", "aac", "-b:a", "256k", "-ar", "48000",
        str(raw_stitched)
    ]
    subprocess.run(cmd_stitch, check=True, capture_output=True)
    print(f"  [✓] Ghép nối 4 shots thành raw master: {raw_stitched.name}")

    # 3. Chuẩn hóa EBU R128 (-14.0 LUFS)
    final_master = EXPORTS_DIR / "thap_ngu_nien_prologue_master_40s.mp4"
    ace.normalize_loudness(
        str(raw_stitched),
        str(final_master),
        target_lufs=-14.0,
        two_pass=True
    )
    print(f"  [✓] Chuẩn hóa âm lượng EBU R128 (-14.0 LUFS) thành công: {final_master.name}")

    # Đồng bộ sang các vị trí chuẩn
    shutil.copy2(final_master, VIDEOS_DIR / "prologue_hoai_niem_198x_to_gia_tinh_40s.mp4")
    shutil.copy2(final_master, EXPORTS_DIR / "prologue_master_40s.mp4")

    # 4. Ghép Bản Liên Hoàn 60s (Intro 20s + Prologue 40s)
    intro_master_file = EXPORTS_DIR / "thap_ngu_nien_intro_master_20s.mp4"
    if intro_master_file.exists():
        concat_list_txt = TEMP_DIR / "concat_60s.txt"
        with open(concat_list_txt, "w", encoding="utf-8") as f:
            f.write(f"file '{intro_master_file.resolve().as_posix()}'\n")
            f.write(f"file '{final_master.resolve().as_posix()}'\n")

        continuous_60s = EXPORTS_DIR / "thap_ngu_nien_intro_prologue_continuous_60s.mp4"
        cmd_60s = [
            "ffmpeg", "-y",
            "-f", "concat", "-safe", "0",
            "-i", str(concat_list_txt),
            "-c", "copy",
            str(continuous_60s)
        ]
        subprocess.run(cmd_60s, check=True, capture_output=True)
        shutil.copy2(continuous_60s, EXPORTS_DIR / "thap_ngu_nien_ep01_intro_prologue_60s.mp4")
        shutil.copy2(continuous_60s, VIDEOS_DIR / "thap_ngu_nien_ep01_intro_prologue_60s.mp4")
        print(f"  [✓] Xuất bản Bản Liên Hoàn 60s thành công: {continuous_60s.name}")

    # 5. Tạo Contact Sheet & Đo kiểm âm lượng
    cs = ZeroWasteContactSheet()
    cs_out = ASSETS_DIR / "critic_queue" / "contact_sheet_prologue_fresh_40s.jpg"
    cs.create_contact_sheet(
        video_path=str(final_master),
        num_frames=12,
        output_path=str(cs_out)
    )
    print(f"  [✓] Contact Sheet 12 frames tạo tại: {cs_out.name}")

    loud = ace.measure_loudness(str(final_master))
    print("\n" + "=" * 70)
    print("🎉 HOÀN TẤT XUẤT SẮC BẢN MASTER PROLOGUE 40S!")
    print("=" * 70)
    print(f"  - File: {final_master.name} ({final_master.stat().st_size // 1024} KB)")
    print(f"  - Integrated Loudness: {loud.get('input_i')} LUFS")
    print(f"  - True Peak:          {loud.get('input_tp')} dBTP")
    print(f"  - Loudness Range:     {loud.get('input_lra')} LU")
    print("=" * 70)

if __name__ == "__main__":
    main()
