#!/usr/bin/env python3
"""Gera 9 fundos cinematograficos via gpt-image-1 em paralelo.

Cada background pra uma copy diferente, com etnia/idade/cena variadas
conforme brief do Renato: mix de brancos, negros, pardos, asiaticos,
jovens e adultos, cenas de formatura brasileira.
"""
import os, json, subprocess, base64, sys, time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

# carrega chave manualmente pra evitar problemas com espacos no .env
KEY = None
with open('/opt/mia/.env') as f:
    for line in f:
        if line.startswith('OPENAI_API_KEY='):
            KEY = line.split('=', 1)[1].strip()
            break
assert KEY, 'OPENAI_API_KEY not found'

BGS = Path('/opt/mia/workspace/clientes/px3lab/lancamento_photorf2/criativos/bgs')
BGS.mkdir(parents=True, exist_ok=True)

# formato base horizontal-square (1024x1024) porque na renderizacao vamos crop/reposicionar
# stories e reels usam mesma foto base mas com framing diferente no HTML

COMMON = (
    "cinematic dark photo, dramatic lime green accent light from the side, "
    "dark moody professional atmosphere, shallow depth of field, "
    "blurred graduation ceremony background with soft bokeh lights, "
    "photorealistic, high detail, professional photography, no text, no logo, no watermark, "
    "warm intimate emotional feeling"
)

# Cada copy: (arquivo, prompt_especifico, size)
COPIES = [
    (
        'bg_copy2_fila.png',
        # Copy 2 — Feed 1:1 — Fila desatendida | fotografo BRANCO jovem
        "young white male Brazilian wedding/graduation photographer in his late 20s wearing dark "
        "casual shirt, walking away from professional editing desk with computer monitor visible in "
        "background showing photo grid interface, motion blur suggesting he's leaving, confident "
        "relaxed body language, studio environment with soft ambient light, " + COMMON,
        '1024x1024',
    ),
    (
        'bg_copy3_triagem.png',
        # Copy 3 — Feed 1:1 — Triagem tripla | mulher PARDA jovem formanda
        "young mixed-race Brazilian female university graduate in her early 20s wearing black "
        "graduation gown and cap, warm smile, natural curly brown hair, face clearly visible and "
        "centered, three-quarter portrait framing at graduation ceremony, " + COMMON,
        '1024x1024',
    ),
    (
        'bg_copy4_vizinhanca.png',
        # Copy 4 — Feed 1:1 — Vizinhanca | formando NEGRO jovem, de costas
        "young Black Brazilian male university graduate in his early 20s wearing black graduation "
        "gown and cap, photographed from BEHIND during graduation ceremony walking to receive diploma, "
        "audience and stage lights blurred in front, back of gown clearly visible, dramatic lighting "
        "from stage, moment of ceremony, " + COMMON,
        '1024x1024',
    ),
    (
        'bg_copy5_familiares_story.png',
        # Copy 5 — Story 9:16 — Familiares emocional | familia ASIATICA-BR jovem
        "young Asian-Brazilian male university graduate in his early 20s wearing black graduation "
        "gown and cap hugging his Asian mother in her late 40s who is smiling with tears of joy, "
        "close intimate embrace, faces side by side clearly visible, warm emotional moment at "
        "graduation ceremony, vertical portrait composition, " + COMMON,
        '1024x1536',
    ),
    (
        'bg_copy6_privacidade.png',
        # Copy 6 — Story 9:16 — Privacidade | fotografo BRANCO jovem trabalhando no PC
        "young white male Brazilian photographer in his late 20s wearing dark hoodie working at "
        "professional dual-monitor editing setup at home studio, screens showing photo library "
        "grid interface, side profile view, concentrated expression, vertical composition, "
        "cozy home office atmosphere with warm ambient lighting, " + COMMON,
        '1024x1536',
    ),
    (
        'bg_copy7_vizinhanca_story.png',
        # Copy 7 — Story 9:16 — Vizinhanca | formanda BRANCA jovem de perfil
        "young white Brazilian female university graduate in her early 20s wearing black graduation "
        "gown and cap, photographed from SIDE PROFILE during graduation ceremony, face partially "
        "turned away, long straight hair, dramatic stage lighting, vertical portrait composition, "
        "movement blur suggesting action, " + COMMON,
        '1024x1536',
    ),
    (
        'bg_copy8_familiares_reels.png',
        # Copy 8 — 4:5 — Familiares | familia MISTA (brancos + pardos), 3-4 pessoas
        "Brazilian mixed-race family group of four posing together at university graduation "
        "ceremony: young male graduate in his early 20s in center wearing black graduation gown "
        "and cap (light brown skin), his white father in his 50s wearing suit on his left, "
        "his mixed-race mother in her late 40s wearing elegant dress on his right, and a "
        "younger sister with curly hair, everyone smiling warmly, all four faces clearly visible "
        "aligned at similar height, vertical portrait composition, " + COMMON,
        '1024x1536',
    ),
    (
        'bg_copy9_fila_reels.png',
        # Copy 9 — 4:5 — Fila desatendida | fotografa NEGRA jovem
        "young Black Brazilian female photographer in her late 20s with natural afro hair wearing "
        "dark professional shirt, walking away from professional editing workstation with large "
        "monitor visible in background showing photo grid interface with progress bars, motion "
        "blur suggesting she's leaving, empowered relaxed body language, home studio with warm "
        "ambient light, vertical portrait composition, " + COMMON,
        '1024x1536',
    ),
    (
        'bg_copy10_triagem_reels.png',
        # Copy 10 — 4:5 — Triagem | formando BRANCO jovem
        "young white Brazilian male university graduate in his early 20s wearing black graduation "
        "gown and cap, confident smile, short brown hair, face clearly visible and centered in "
        "three-quarter portrait framing at graduation ceremony, vertical portrait composition, "
        + COMMON,
        '1024x1536',
    ),
]


def gen_one(item):
    filename, prompt, size = item
    out = BGS / filename
    if out.exists() and out.stat().st_size > 100_000:
        return (filename, 'CACHED', out.stat().st_size)

    payload = {
        'model': 'gpt-image-1',
        'prompt': prompt,
        'size': size,
        'quality': 'high',
        'n': 1,
    }
    t0 = time.time()
    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, timeout=300,
    )
    dt = time.time() - t0
    try:
        data = json.loads(r.stdout)
        b64 = data['data'][0]['b64_json']
        out.write_bytes(base64.b64decode(b64))
        return (filename, f'OK {dt:.0f}s', out.stat().st_size)
    except Exception as e:
        return (filename, f'FAIL {e} | {r.stdout[:300]}', 0)


if __name__ == '__main__':
    print(f'gerando {len(COPIES)} fundos em paralelo (4 workers)...')
    with ThreadPoolExecutor(max_workers=4) as ex:
        futs = [ex.submit(gen_one, c) for c in COPIES]
        for f in as_completed(futs):
            fn, status, sz = f.result()
            print(f'  {fn}: {status} ({sz} bytes)')
    print('done')
