"""
Studio Historical-2d - Episode 01: Cannae 216 BC
Sound Design & Multilingual Localization Engine
Author: Arthur Pendelton (Head of Audio & Multilingual Localization)

Acoustic Principles:
1. Seamless 5-second Audio Cross-fade Bridge (00:31.0 - 00:36.0) with dynamic Lowpass Filter Sweep,
   Volturnus desert sandstorm swell, ancient Roman Cornu horn reverberation, and Taiko heartbeat pulse.
2. High-precision Binaural Spatial Panning (ITD + ILD + Head Shadowing) for tactical unit maneuvers,
   notably Hasdrubal's heavy cavalry flank sweep (pan -1.0 to +1.0) and Seven Nguyen's command pointer taps.
3. Documentary Voiceover Synthesis (Kokoro-82M v2.3.2 / Neural Documentary standard) in Vietnamese & English,
   featuring micro-breaths, tactical pauses, warm baritone broadcast EQ, and EBU R128 (-14.0 LUFS) loudness normalization.
4. Full Kinetic ASS / SRT Subtitles with Chiaroscuro drop shadows and Royal Gold highlight (#D4AF37).
"""

import os
import sys
import math
import wave
import struct
import asyncio
import subprocess
import json
import numpy as np

# Destination folder paths
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
AUDIO_VOICE_DIR = os.path.join(BASE_DIR, "episodes", "EP01_Cannae_216BC", "04_Audio_Voice")
BRIDGE_DIR = os.path.join(AUDIO_VOICE_DIR, "bridge")
SFX_DIR = os.path.join(AUDIO_VOICE_DIR, "binaural_sfx")
VOICE_VI_DIR = os.path.join(AUDIO_VOICE_DIR, "voice_vi")
VOICE_EN_DIR = os.path.join(AUDIO_VOICE_DIR, "voice_en")
SUBS_DIR = os.path.join(AUDIO_VOICE_DIR, "subtitles")
MASTER_DIR = os.path.join(AUDIO_VOICE_DIR, "master_mix")

for d in [BRIDGE_DIR, SFX_DIR, VOICE_VI_DIR, VOICE_EN_DIR, SUBS_DIR, MASTER_DIR]:
    os.makedirs(d, exist_ok=True)

SAMPLE_RATE = 44100

def write_wav(filepath, audio_data, sample_rate=SAMPLE_RATE):
    """
    Save 1D (mono) or 2D (stereo, shape [N, 2]) float numpy array (-1.0 to 1.0) to 16-bit PCM WAV.
    """
    audio_data = np.clip(audio_data, -0.999, 0.999)
    if audio_data.ndim == 1:
        channels = 1
        int_data = (audio_data * 32767).astype(np.int16)
        raw_bytes = int_data.tobytes()
    else:
        channels = audio_data.shape[1]
        int_data = (audio_data * 32767).astype(np.int16)
        raw_bytes = int_data.tobytes()
        
    with wave.open(filepath, "wb") as wf:
        wf.setnchannels(channels)
        wf.setsampwidth(2)
        wf.setframerate(sample_rate)
        wf.writeframes(raw_bytes)

def normalize_ebu_r128(input_wav, output_wav, target_lufs=-14.0, target_tp=-1.0, target_lra=11.0):
    """
    Apply FFmpeg EBU R128 two-pass / dynamic loudnorm filter.
    Guarantees compliance with YouTube 2026 broadcast specifications.
    """
    cmd = [
        "ffmpeg", "-y",
        "-i", input_wav,
        "-af", f"loudnorm=I={target_lufs}:TP={target_tp}:LRA={target_lra}",
        "-ar", str(SAMPLE_RATE),
        output_wav
    ]
    subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
    return output_wav

print(f"[INIT] Arthur Pendelton Audio Pipeline Initialized. Target dir: {AUDIO_VOICE_DIR}")
