#!/usr/bin/env python3
"""Gera os NOVOS backgrounds v2 pra features aprovadas na iteracao 2.

Baseado no feedback do Renato — v4 das copies:
- bg_copy1_pai_sozinho.png : pai do formando sozinho no baile (sem o formando no frame)
- bg_copy3_silhuetas.png   : grade de silhuetas com interrogacoes (feature separacao sem foto ID)
- bg_copy10_corpo_inteiro.png : formando corpo inteiro (feature reconhecimento de corpo)

Reaproveita fundo v1 pros demais 7 criativos.
"""
import os, json, subprocess, base64, sys, time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

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)

COMMON = (
    "cinematic dark photo, dramatic lime green accent light from the side, "
    "dark moody professional atmosphere, shallow depth of field, "
    "photorealistic, high detail, professional photography, no text, no logo, no watermark"
)

COPIES = [
    (
        'bg_copy1_pai_sozinho.png',
        # Copy 1 NOVO — Pai do formando sozinho no baile de formatura. Sem o formando no frame.
        # Meia-idade, ambiente instagramavel, iluminacao dramatica cinematografica.
        "middle-aged Brazilian father in his early 50s alone at his son's graduation ball party, "
        "wearing elegant dark suit or dress shirt, standing at a decorated instagram-worthy photo "
        "spot with flower wall or event backdrop behind him, warm proud expression on face, "
        "looking slightly to the side lost in thought or looking toward the camera, face clearly "
        "visible centered in three-quarter portrait framing, blurred graduation ball atmosphere "
        "with soft warm bokeh lights and hints of party decoration in background, "
        "shallow depth of field, emotional intimate moment, warm intimate emotional feeling, "
        + COMMON,
        '1024x1024',
    ),
    (
        'bg_copy3_silhuetas.png',
        # Copy 3 NOVO — Grade/mosaico de silhuetas escuras estilo perfil facial com interrogacoes
        # que sao substituidas por checkmarks. Composicao abstrata tecnologica.
        # Nao precisa de rosto real, e uma cena conceitual.
        "abstract dark grid of six blank silhouette head profiles arranged in 2x3 grid, "
        "silhouettes shown as dark head outlines with soft blurred edges against a very dark "
        "moody background, cinematic dark photography style, dramatic lime green rim light "
        "from the side illuminating the silhouettes, empty faces with soft glow, "
        "abstract minimalist composition suggesting facial recognition and identification, "
        "photorealistic rendering with technological atmosphere, "
        "shallow depth of field on the silhouettes, "
        "background completely dark and clean for overlay space, no text, no logo, no watermark, "
        "professional photography, high detail",
        '1024x1024',
    ),
    (
        'bg_copy10_corpo_inteiro.png',
        # Copy 10 NOVO — Formando branco jovem CORPO INTEIRO. Enquadramento vertical
        # mostrando cabeca ate joelhos ou pes. Pra reconhecimento de corpo (nao so rosto).
        "young white Brazilian male university graduate in his early 20s wearing full black "
        "graduation gown and cap, standing in full body vertical composition showing from head to "
        "knees, confident relaxed pose holding diploma scroll in one hand, natural warm smile, "
        "short brown hair, face and body clearly visible in vertical full-body framing, "
        "dramatic stage lighting behind him, blurred graduation ceremony hall in background "
        "with soft warm bokeh lights, vertical portrait composition emphasizing full silhouette, "
        + 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 NOVOS em paralelo (3 workers)...')
    with ThreadPoolExecutor(max_workers=3) 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')
