#!/usr/bin/env python3
"""Assemble frames into final MP4 video."""
import subprocess, os, glob

BASE = '/tmp/raportis-promo'
OUT = '/tmp/raportis-promo.mp4'
FPS = 30
W, H = 1920, 1080

SEGMENTS = [
    ('01-hook', 3),
    ('02-solution', 3),
    ('03-vocal', 9),
    ('04-autofill', 7),
    ('05-save', 3),
    ('06-pdf', 5),
    ('07-cta', 5),
]

print("🎬 Assembling Raportis Promo Video...")
print(f"   Output: {OUT}")
print()

for name, dur in SEGMENTS:
    frames_dir = f'{BASE}/frames/{name}'
    frames = sorted(glob.glob(f'{frames_dir}/frame_*.png'))
    if not frames:
        print(f"⚠️  {name}: no frames, skipping")
        continue
    print(f"📦 {name}: {len(frames)} frames → {name}.mp4")
    subprocess.run(['ffmpeg', '-y', '-framerate', str(FPS), '-i', f'{frames_dir}/frame_%05d.png',
                    '-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
                    '-pix_fmt', 'yuv420p', '-movflags', '+faststart',
                    f'{BASE}/segments/{name}.mp4'],
                   capture_output=True)

# Build concat list
concat_lines = []
for name, dur in SEGMENTS:
    mp4 = f'{BASE}/segments/{name}.mp4'
    if os.path.exists(mp4):
        concat_lines.append(f"file '{mp4}'")

concat_file = f'{BASE}/concat.txt'
with open(concat_file, 'w') as f:
    f.write('\n'.join(concat_lines))

print()
print("🔗 Concatenating segments...")
subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_file,
                '-c:v', 'libx264', '-preset', 'medium', '-crf', '16',
                '-pix_fmt', 'yuv420p', '-movflags', '+faststart',
                OUT],
               capture_output=True)

# Copy to final location
import shutil
shutil.copy(OUT, '/tmp/raportis-promo.mp4')

# Get stats
size = os.path.getsize(OUT)
dur = subprocess.check_output(['ffprobe', '-v', 'quiet', '-show_entries', 'format=duration',
                                '-of', 'csv=p=0', OUT]).decode().split('.')[0]

print()
print(f"✅ Final video: /tmp/raportis-promo.mp4")
print(f"   Duration: {dur}s | Size: {size/1024/1024:.1f}MB")
print(f"   Resolution: {W}x{H} @ {FPS}fps")
