#!/usr/bin/env python3
"""Gera a foto base realista do criativo 05 - 'AQUELE FORMANDO ESQUECIDO? ACHOU.'

Conceito: foto de grupo de formatura com vários formandos (desfocados/compactos)
e UM formando especifico ligeiramente destacado - como se a camera "quase tivesse
esquecido" ele. Os overlays verdes (bracket + linha ligando ao grupo + pill
'FORMANDO 047 - IDENTIFICADO') sao aplicados via HTML/CSS no build (controle
total), entao a foto base precisa ser SO a cena realista, SEM UI/overlays.

Angulo POSITIVO (resolucao) -> paleta neutra com acentos warm event lighting
+ espaco negativo pra texto no lado esquerdo.

Preferido: gpt-image-2.5-sunburst (2026-09-08)
Fallbacks: gpt-image-2.5-flare -> gpt-image-2 -> gpt-image-1.5
PROIBIDO: gpt-image-1 (versao antiga)
"""
import os
import base64
import sys
from pathlib import Path

env_path = Path("/opt/mia/.env")
for line in env_path.read_text().splitlines():
    if line.startswith("OPENAI_API_KEY="):
        os.environ["OPENAI_API_KEY"] = line.split("=", 1)[1].strip()

OUT_DIR = Path("/opt/mia/workspace/clientes/px3lab/criativos_lancamento_1007/05_formando_esquecido")
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_RAW = OUT_DIR / "foto_base_formando_esquecido_raw.png"

PROMPT = (
    "Photorealistic photograph of a Brazilian graduation group photo - about "
    "20 to 25 young graduates in their early twenties wearing classic black "
    "academic graduation gowns and black mortarboard caps, standing together "
    "in a formal evening ceremony setting with warm bokeh event lights behind "
    "them. Big genuine smiles, celebratory mood, arms around each other's "
    "shoulders. Soft warm key light (tungsten event lighting) from the front, "
    "shallow depth of field with the back row slightly out of focus. In the "
    "composition, ONE specific graduate stands out subtly: a young woman in "
    "the second row toward the right-of-center area, slightly LESS sharp than "
    "the people around her and partially framed by the shoulders of the "
    "classmates in front, as if the camera 'almost missed' including her in "
    "the main frame. Natural crowd arrangement, authentic Brazilian "
    "graduation ceremony, formal indoor venue with warm golden bokeh "
    "background. 35mm wide lens look, realistic professional event "
    "photography editorial style, warm cinematic event tone, natural skin "
    "tones, no plastic AI look, no illustration or cartoon style. Significant "
    "NEGATIVE SPACE on the LEFT side of the frame and across the top for "
    "text overlay. Square 1:1 framing."
)

print("[INFO] Gerando foto base criativo 05 (grupo formatura + formando quase esquecido)...")

try:
    from openai import OpenAI
except ImportError:
    os.system("pip install --break-system-packages openai -q")
    from openai import OpenAI

client = OpenAI()

MODELS = [
    "gpt-image-2.5-sunburst",
    "gpt-image-2.5-flare",
    "gpt-image-2",
    "gpt-image-1.5",
]

model_used = None
errors = []

for model in MODELS:
    try:
        print(f"[TRY] {model}")
        resp = client.images.generate(
            model=model, prompt=PROMPT, size="1024x1024", quality="high", n=1,
        )
        OUT_RAW.write_bytes(base64.b64decode(resp.data[0].b64_json))
        model_used = model
        print(f"[OK] Gerou com {model}")
        break
    except Exception as e:
        msg = str(e)[:300]
        print(f"[WARN] {model} falhou: {msg}")
        errors.append(f"{model}: {msg}")

if not model_used:
    print("\n[ERRO] Todos os modelos falharam:")
    for e in errors:
        print(f"  - {e}")
    sys.exit(1)

print(f"[OK] Foto base salva: {OUT_RAW} ({OUT_RAW.stat().st_size // 1024} KB)")

(OUT_DIR / "PROMPT_GPT_IMAGE.txt").write_text(
    f"MODEL: {model_used}\nSIZE: 1024x1024 (1:1)\nQUALITY: high\nCRIATIVO: 05 - Aquele formando esquecido? Achou.\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
