import subprocess
import os
import json

ep_dir = r"C:\Ai_Coding\apps\studio\episodes\2026-11-16_coffee-joke"
clips_dir = os.path.join(ep_dir, "src", "assets", "clips")
audio_dir = os.path.join(ep_dir, "src", "audio")
out_dir = os.path.join(ep_dir, "out")
work_dir = r"C:\Ai_Coding\scratch\coffee_edit_work"

os.makedirs(out_dir, exist_ok=True)
os.makedirs(work_dir, exist_ok=True)

c01_path = os.path.join(clips_dir, "C01.mp4")
c02_path = os.path.join(clips_dir, "C02.mp4")
c03_path = os.path.join(clips_dir, "C03.mp4")

l01_path = os.path.join(audio_dir, "L01.mp3")
l02_path = os.path.join(audio_dir, "L02.mp3")
l03_path = os.path.join(audio_dir, "L03.mp3")

def run(cmd):
    print("Running:", " ".join(cmd))
    res = subprocess.run(cmd, capture_output=True, text=True)
    if res.returncode != 0:
        print("STDERR:", res.stderr)
        raise RuntimeError(f"Command failed with code {res.returncode}")
    return res

# 1. Prepare tightened L01 (trim mid-pause 3.66s~4.24s down to 0.25s natural breath -> 4.79s)
l01_natural = os.path.join(work_dir, "L01_natural.wav")
run([
    "ffmpeg", "-y", "-i", l01_path,
    "-filter_complex",
    "[0:a]atrim=0:3.91,asetpts=PTS-STARTPTS[a1];[0:a]atrim=4.24:5.12,asetpts=PTS-STARTPTS[a2];[a1][a2]concat=n=2:v=0:a=1,loudnorm=I=-14:TP=-1.5:LRA=11,aformat=sample_rates=48000:channel_layouts=mono[out]",
    "-map", "[out]", l01_natural
])

# Prepare normalized L02 (trim trailing silence after 4.81s -> 4.81s)
l02_natural = os.path.join(work_dir, "L02_natural.wav")
run([
    "ffmpeg", "-y", "-i", l02_path,
    "-af", "atrim=0:4.81,asetpts=PTS-STARTPTS,loudnorm=I=-14:TP=-1.5:LRA=11,aformat=sample_rates=48000:channel_layouts=mono",
    l02_natural
])

# Prepare normalized L03 (1.92s)
l03_natural = os.path.join(work_dir, "L03_natural.wav")
run([
    "ffmpeg", "-y", "-i", l03_path,
    "-af", "loudnorm=I=-14:TP=-1.5:LRA=11,aformat=sample_rates=48000:channel_layouts=mono",
    l03_natural
])

# ==============================================================================
# VERSION A (Primary): coffee-joke_v1.mp4 (1.0x natural voice speed + post-line silence preserved)
# C01: 5.70s (0.00~5.70s) | L01 at 0.40s~5.19s, silence 5.19s~5.70s (0.51s)
# C02: 5.70s (5.70~11.40s) | L02 at 5.90s~10.71s, silence 10.71s~11.40s (0.69s)
# C03: 3.50s (11.40~14.90s) | L03 at 11.60s~13.52s, pat & silence 13.52s~14.90s (1.38s)
# Total: 14.90s
# ==============================================================================
v1_video = os.path.join(work_dir, "v1_video.mp4")
run([
    "ffmpeg", "-y",
    "-i", c01_path,
    "-i", c02_path,
    "-i", c03_path,
    "-filter_complex",
    # C01: 0.0 to 5.70s
    "[0:v]trim=0:5.70,setpts=PTS-STARTPTS,scale=1280:720,fps=24,format=yuv420p[v0];"
    # C02: 2.20 to 7.90s (5.70s), crop out left edge silhouette cleanly
    "[1:v]trim=2.20:7.90,setpts=PTS-STARTPTS,crop=1152:648:128:0,scale=1280:720,fps=24,format=yuv420p[v1];"
    # C03: 0.0 to 3.25s + 0.25s clone hold = 3.50s (avoids cup distortion after 3.4s)
    "[2:v]trim=0:3.25,setpts=PTS-STARTPTS,scale=1280:720,fps=24,tpad=stop_mode=clone:stop_duration=0.25,trim=0:3.50,setpts=PTS-STARTPTS,format=yuv420p[v2];"
    "[v0][v1][v2]concat=n=3:v=1:a=0[vout]",
    "-map", "[vout]",
    "-c:v", "libx264", "-preset", "fast", "-crf", "18",
    v1_video
])

# Build Version A audio track (room tone -28dBFS + subtle cup/pat SFX + panned VOs)
v1_out = os.path.join(out_dir, "coffee-joke_v1.mp4")
run([
    "ffmpeg", "-y",
    "-i", v1_video,
    "-i", c01_path,
    "-i", l01_natural,
    "-i", l02_natural,
    "-i", l03_natural,
    "-filter_complex",
    # Continuous office pantry room tone (-28 dBFS) with 60Hz hum + C01 clean room tone, fade out last 0.5s
    "anoisesrc=color=pink:r=48000:a=0.006:d=14.90,lowpass=f=800,highpass=f=50,pan=stereo|c0=c0|c1=c0[amb_gen];"
    "[1:a]atrim=0:7.45,asetpts=PTS-STARTPTS[rt1];[1:a]atrim=0:7.45,asetpts=PTS-STARTPTS[rt2];"
    "[rt1][rt2]concat=n=2:v=0:a=1,volume=0.5,aformat=sample_rates=48000:channel_layouts=stereo[rt_flow];"
    "[amb_gen][rt_flow]amix=inputs=2:duration=first:dropout_transition=0,afade=t=in:st=0:d=0.2,afade=t=out:st=14.40:d=0.50[amb];"
    # Subtle fabric patting SFX at 13.75s (when Jeongim pats Areum's elbow in C03)
    "anoisesrc=color=brown:r=48000:a=0.04:d=0.18,bandpass=f=350:width_type=h:w=250,afade=t=in:st=0:d=0.03,afade=t=out:st=0.08:d=0.10,adelay=13750|13750,pan=stereo|c0=0.5*c0|c1=0.5*c0[sfx_pat];"
    # L01 at 0.40s (400ms), panned R15 (left 0.425, right 0.575)
    "[2:a]adelay=400|400,pan=stereo|c0=0.425*c0|c1=0.575*c0[vo1];"
    # L02 at 5.90s (5900ms), panned L20 (left 0.60, right 0.40)
    "[3:a]adelay=5900|5900,pan=stereo|c0=0.60*c0|c1=0.40*c0[vo2];"
    # L03 at 11.60s (11600ms), panned R10 (left 0.45, right 0.55)
    "[4:a]adelay=11600|11600,pan=stereo|c0=0.45*c0|c1=0.55*c0[vo3];"
    "[amb][sfx_pat][vo1][vo2][vo3]amix=inputs=5:duration=first:dropout_transition=0:normalize=0,alimiter=limit=0.85[aout]",
    "-map", "0:v", "-map", "[aout]",
    "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ar", "48000",
    "-shortest",
    v1_out
])

# ==============================================================================
# VERSION B (Strict 12.0s Cue-Sheet Timings): coffee-joke_v1_12s_strict.mp4
# C01: 4.00s (0.00~4.00s) | L01 at 0.40s~3.60s, silence 3.60s~4.00s
# C02: 4.50s (4.00~8.50s) | L02 at 4.20s~8.00s, silence 8.00s~8.50s
# C03: 3.50s (8.50~12.00s) | L03 at 8.70s~10.62s, pat & silence 10.62s~12.00s
# Total: 12.00s
# ==============================================================================
v1_12s_video = os.path.join(work_dir, "v1_12s_video.mp4")
run([
    "ffmpeg", "-y",
    "-i", c01_path,
    "-i", c02_path,
    "-i", c03_path,
    "-filter_complex",
    "[0:v]trim=0:4.00,setpts=PTS-STARTPTS,scale=1280:720,fps=24,format=yuv420p[v0];"
    "[1:v]trim=3.40:7.90,setpts=PTS-STARTPTS,crop=1152:648:128:0,scale=1280:720,fps=24,format=yuv420p[v1];"
    "[2:v]trim=0:3.25,setpts=PTS-STARTPTS,scale=1280:720,fps=24,tpad=stop_mode=clone:stop_duration=0.25,trim=0:3.50,setpts=PTS-STARTPTS,format=yuv420p[v2];"
    "[v0][v1][v2]concat=n=3:v=1:a=0[vout]",
    "-map", "[vout]",
    "-c:v", "libx264", "-preset", "fast", "-crf", "18",
    v1_12s_video
])

v1_12s_out = os.path.join(out_dir, "coffee-joke_v1_12s_strict.mp4")
run([
    "ffmpeg", "-y",
    "-i", v1_12s_video,
    "-i", c01_path,
    "-i", l01_natural,
    "-i", l02_natural,
    "-i", l03_natural,
    "-filter_complex",
    "anoisesrc=color=pink:r=48000:a=0.006:d=12.00,lowpass=f=800,highpass=f=50,pan=stereo|c0=c0|c1=c0[amb_gen];"
    "[1:a]atrim=0:6.00,asetpts=PTS-STARTPTS[rt1];[1:a]atrim=0:6.00,asetpts=PTS-STARTPTS[rt2];"
    "[rt1][rt2]concat=n=2:v=0:a=1,volume=0.5,aformat=sample_rates=48000:channel_layouts=stereo[rt_flow];"
    "[amb_gen][rt_flow]amix=inputs=2:duration=first:dropout_transition=0,afade=t=in:st=0:d=0.2,afade=t=out:st=11.50:d=0.50[amb];"
    "anoisesrc=color=brown:r=48000:a=0.04:d=0.18,bandpass=f=350:width_type=h:w=250,afade=t=in:st=0:d=0.03,afade=t=out:st=0.08:d=0.10,adelay=11000|11000,pan=stereo|c0=0.5*c0|c1=0.5*c0[sfx_pat];"
    "[2:a]atempo=1.49,loudnorm=I=-14:TP=-1.5:LRA=11,adelay=400|400,pan=stereo|c0=0.425*c0|c1=0.575*c0[vo1];"
    "[3:a]atempo=1.26,loudnorm=I=-14:TP=-1.5:LRA=11,adelay=4200|4200,pan=stereo|c0=0.60*c0|c1=0.40*c0[vo2];"
    "[4:a]adelay=8700|8700,pan=stereo|c0=0.45*c0|c1=0.55*c0[vo3];"
    "[amb][sfx_pat][vo1][vo2][vo3]amix=inputs=5:duration=first:dropout_transition=0:normalize=0,alimiter=limit=0.85[aout]",
    "-map", "0:v", "-map", "[aout]",
    "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ar", "48000",
    "-shortest",
    v1_12s_out
])

print("Both rough cut versions built successfully!")
