#!/usr/bin/env python3
"""Gera fundo cinematografico via gpt-image-1 pro criativo Copy 1 - Reconhecer Familiares.

Cena: formando com toga/beca ao lado da mae idosa, ambos sorrindo/emocionados
em cerimonia de formatura brasileira. Foco na proximidade dos rostos lado a lado
pra permitir overlay de 2 caixas de reconhecimento facial.
"""
import os, json, subprocess, base64, sys
from pathlib import Path

# 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'

OUT = Path('/opt/mia/workspace/clientes/px3lab/lancamento_photorf2/criativos/bg_familia_formatura.png')
OUT.parent.mkdir(parents=True, exist_ok=True)

# formato 1024x1024 (square, mais proximo do 1:1 final 1080x1080)
PROMPT = (
    "cinematic dark photo of a Brazilian graduate wearing black graduation gown and cap "
    "next to their elderly mother, both smiling with emotion, warm intimate moment at a "
    "graduation ceremony, faces clearly visible side by side at similar height framing, "
    "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"
)

if OUT.exists() and OUT.stat().st_size > 100_000:
    print(f'CACHED: {OUT} ({OUT.stat().st_size} bytes)')
    sys.exit(0)

payload = {
    'model': 'gpt-image-1',
    'prompt': PROMPT,
    'size': '1024x1024',
    'quality': 'high',
    'n': 1,
}

print('gerando fundo via gpt-image-1 quality=high...')
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=180,
)

try:
    data = json.loads(r.stdout)
    b64 = data['data'][0]['b64_json']
    OUT.write_bytes(base64.b64decode(b64))
    print(f'OK: {OUT} ({OUT.stat().st_size} bytes)')
except Exception as e:
    print(f'FAIL: {e}')
    print('stdout:', r.stdout[:500])
    print('stderr:', r.stderr[:500])
    sys.exit(1)
