"""Render Balimentari Monday Motivation video with FFmpeg."""
import subprocess
import os
import json

OUT_DIR = "/app/working/workspaces/default/OpenMontage/pipeline/balimentari-senin"
NARRATION = os.path.join(OUT_DIR, "narration.wav")
OUTPUT = os.path.join(OUT_DIR, "balimentari_senin.mp4")

# Get narration duration
dur_cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
           "-of", "default=noprint_wrappers=1:nokey=1", NARRATION]
dur = float(subprocess.run(dur_cmd, capture_output=True, text=True).stdout.strip())
total_dur = dur + 1.5  # Add padding
print(f"Narration duration: {dur:.1f}s, total: {total_dur:.1f}s")

# Scene timing: text lines with fade-in/out
# Each line mapped to approximate timing
lines = [
    {"text": "The holiday", "start": 0.3, "end": 2.0, "size": 72},
    {"text": "is over.", "start": 1.5, "end": 2.8, "size": 80},
    {"text": "But today...", "start": 3.0, "end": 5.0, "size": 64},
    {"text": "is your fresh start.", "start": 4.0, "end": 6.5, "size": 68},
    {"text": "Your new beginning.", "start": 6.0, "end": 8.5, "size": 60},
    {"text": "The world is waiting.", "start": 8.0, "end": 10.5, "size": 56},
    {"text": "Take that first step.", "start": 9.5, "end": 12.0, "size": 64},
    {"text": "SELAMAT PAGI", "start": 11.8, "end": 13.5, "size": 80},
    {"text": "Balimentari 🌅", "start": 13.0, "end": total_dur, "size": 52},
]

# Build drawtext filters
# Background: warm gradient (orange/pink) 1080x1920
W = 1080
H = 1920

# Create a smooth animated background with color filter
# Using a base color + slight hue shift over time

filter_parts = []

# Background gradient using geq
filter_parts.append(
    f"color=c=0x1a0a2e:s={W}x{H}:d={total_dur},"
    f"format=rgba,"
    f"geq=r='128+100*sin((Y/H)*PI)+30*sin(T*0.5)':"
    f"g='60+60*sin((Y/H)*PI+1)+20*sin(T*0.7)':"
    f"b='180+50*sin((Y/H)*PI+2)+40*sin(T*0.3)':a='255'"
    f"[bg]"
)

# Add vignette effect
filter_parts.append(
    f"[bg]vignette=PI/4[vbg]"
)

# Text overlays with fade-in/fade-out
prev_label = "vbg"
for i, line in enumerate(lines):
    text_escaped = line["text"].replace("'", "\\\\'").replace(":", "\\:")
    text_escaped = text_escaped.replace("%", "\\\\%")
    
    font_size = line["size"]
    start_t = line["start"]
    end_t = line["end"]
    mid_t = (start_t + end_t) / 2
    
    # Fade in duration
    fade_in = min(0.4, (end_t - start_t) / 3)
    fade_out = min(0.5, (end_t - start_t) / 3)
    
    alpha_expr = (
        f"if(lt(t,{start_t}),0,"
        f"if(lt(t,{start_t}+{fade_in}),(t-{start_t})/{fade_in},"
        f"if(lt(t,{end_t}-{fade_out}),1,"
        f"if(lt(t,{end_t}),({end_t}-t)/{fade_out},0))))"
    )
    
    # Y position: spread lines across screen
    y_pos = int(H * 0.25 + i * (H * 0.5) / len(lines))
    
    label = f"t{i}"
    filter_parts.append(
        f"[{prev_label}]drawtext="
        f"text='{text_escaped}':"
        f"fontcolor=white:"
        f"fontsize={font_size}:"
        f"fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf:"
        f"x=(w-text_w)/2:"
        f"y={y_pos}:"
        f"alpha='{alpha_expr}':"
        f"shadowcolor=black@0.3:shadowx=3:shadowy=3"
        f"[{label}]"
    )
    prev_label = label

# Build full filter complex
filter_complex = ";".join(filter_parts)
final_label = f"t{len(lines)-1}"

cmd = [
    "ffmpeg", "-y",
    "-i", NARRATION,
    "-filter_complex", filter_complex,
    "-map", f"[{final_label}]",
    "-map", "0:a",
    "-c:v", "libx264",
    "-preset", "fast",
    "-crf", "23",
    "-c:a", "aac",
    "-b:a", "128k",
    "-shortest",
    "-pix_fmt", "yuv420p",
    OUTPUT
]

print(f"Filter complex length: {len(filter_complex)} chars")
print("Rendering video...")
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120)

if proc.returncode == 0:
    size_mb = os.path.getsize(OUTPUT) / 1024 / 1024
    print(f"✅ Video rendered: {OUTPUT} ({size_mb:.1f} MB)")
    
    # Verify
    vcmd = ["ffprobe", "-v", "error", "-show_entries", 
            "format=duration,size:stream=codec_type,width,height",
            "-of", "json", OUTPUT]
    vinfo = json.loads(subprocess.run(vcmd, capture_output=True, text=True).stdout)
    print(json.dumps(vinfo, indent=2))
else:
    print("❌ Render failed!")
    print("STDERR:", proc.stderr[-2000:])
