#!/usr/bin/env python3
"""Generate B-roll images via gpt-image-1 for each scene."""
import os, json, subprocess, base64
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor

KEY = os.environ['OPENAI_API_KEY']
OUT_DIR = Path('/opt/mia/workspace/clientes/px3lab/video_2_0/v2/broll')
OUT_DIR.mkdir(parents=True, exist_ok=True)

# 2 imagens por cena pra criar variação com corte. 1024x1536 (vertical 2:3, mais próximo do 9:16).
# gpt-image-1 aceita 1024x1024, 1024x1536, 1536x1024
SCENES = {
    # Cena 1 (0-4s) HOOK — fotógrafo cansado/frustrado
    'c1_a': 'A tired professional wedding photographer sitting at a dark desk at night, staring exhausted at a computer screen showing hundreds of unsorted photo thumbnails, overwhelmed expression, moody low-key lighting, cinematic photo, vertical composition, muted color grade, no text',
    'c1_b': 'Close-up of a professional camera lens with photographer hands, fast motion blur, dark studio background, cinematic dramatic lighting, vertical 9:16 composition, moody atmosphere, no text',

    # Cena 2 (4-8s) DOR — sistema não roda, terceirização, tempo perdido
    'c2_a': 'Frustrated photographer hands typing frantically on keyboard, multiple monitors showing chaotic folders and file lists, dark home office at night, cinematic thriller mood, vertical composition, no text',
    'c2_b': 'Close-up of an analog clock ticking rapidly with a stack of Brazilian real cash being pulled away in shallow depth of field, moody dramatic lighting, vertical composition, cinematic, no text',

    # Cena 3 (8-14s) VIRADA — sistema descobre formandos, face detection
    'c3_a': 'Futuristic AI facial recognition interface overlay on a photo of a smiling graduate in cap and gown, glowing green scan lines and detection boxes, high-tech dark UI aesthetic, cinematic, vertical composition, no text',
    'c3_b': 'Close-up screen showing multiple graduate portrait thumbnails being auto-organized into folders with glowing green highlights, futuristic tech interface, dark UI, vertical composition, no text',

    # Cena 4 (14-21s) DIFERENCIAIS — familiares + fila
    'c4_a': 'A young Brazilian graduate in cap and gown hugging their proud father and mother, warm emotional family portrait moment at a graduation ceremony, professional photography, vertical composition, cinematic warm lighting, no text',
    'c4_b': 'Multiple computer monitors showing photo processing queues with green progress bars, modern photographers studio background out of focus, tech aesthetic, vertical composition, no text',

    # Cena 6 (28-38s) CTA — logo + fotógrafo satisfeito
    'c6_a': 'A confident smiling Brazilian professional photographer holding a large printed graduation album, warm studio lighting, proud satisfied expression, vertical composition, cinematic portrait, no text',
    'c6_b': 'Modern minimalist photography studio with soft daylight, camera on tripod in foreground, computer with photo editing software in background, clean tech aesthetic, vertical composition, no text',
}

def gen(name, prompt):
    dst = OUT_DIR / f'{name}.png'
    if dst.exists():
        print(f'{name}: cached')
        return
    payload = {
        'model': 'gpt-image-1',
        'prompt': prompt,
        'size': '1024x1536',
        'quality': 'medium',
        'n': 1,
    }
    r = subprocess.run(['curl', '-s', '-X', 'POST',
        'https://api.openai.com/v1/images/generations',
        '-H', f'Authorization: Bearer {KEY}',
        '-H', 'Content-Type: application/json',
        '-d', json.dumps(payload),
    ], capture_output=True, text=True)
    try:
        data = json.loads(r.stdout)
        b64 = data['data'][0]['b64_json']
        dst.write_bytes(base64.b64decode(b64))
        print(f'{name}: OK')
    except Exception as e:
        print(f'{name}: FAIL', e, r.stdout[:300])

with ThreadPoolExecutor(max_workers=5) as ex:
    list(ex.map(lambda kv: gen(*kv), SCENES.items()))
print('done')
