#!/usr/bin/env python3
"""Gera a foto base realista do criativo 06 - 'FOTO DE PARENTE SOZINHO? A IA ACHA.'

Conceito: foto cândida de uma mãe/parente (50s-60s) em evento de formatura brasileiro,
sozinha no enquadramento mas com bokeh warm de evento ao fundo. Vestida social (vestido
elegante), olhando pro lado como se observasse a formanda. Representa o cenário real
em que o Cloud PhotoRF 2.0 identifica "familiar da formanda X" numa foto sem contexto
óbvio.

Os overlays verdes (bracket + pill 'FAMILIAR DETECTADO · FORMANDA 112' + conector) são
aplicados via HTML/CSS no build - a foto base precisa ser APENAS a cena realista, SEM
UI/overlays.

Ângulo POSITIVO (resolução) → paleta warm event lighting + espaço negativo pra texto
no lado DIREITO (invertido vs os anteriores pra variar composição).

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 (versão 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/06_parentes_sozinhos")
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_RAW = OUT_DIR / "foto_base_parente_sozinho_raw.png"

PROMPT = (
    "Photorealistic candid photograph of a Brazilian woman in her late 50s to early "
    "60s at an elegant graduation celebration event. She is wearing a sophisticated "
    "burgundy evening dress with discreet jewelry, holding a champagne flute near "
    "her chest, standing alone near a decorated event wall. Her soft, proud, "
    "nostalgic smile - she is looking slightly off-camera to her right, as if "
    "watching her daughter on stage from a distance. Warm golden bokeh of other "
    "guests, event lights, chandeliers and venue decor softly out of focus behind "
    "her. The woman is CLEARLY ALONE in the frame - no other faces in sharp focus, "
    "no shoulders cutting into her space. Composition: subject positioned on the "
    "LEFT third of the frame with meaningful NEGATIVE SPACE on the RIGHT side for "
    "text overlay. She reads unmistakably as a proud family member (mother or aunt), "
    "not as a graduate - no cap, no gown, no young appearance. Natural warm "
    "tungsten event lighting from above, soft shadow on her face, 85mm portrait "
    "lens look, shallow depth of field (f/1.8), cinematic warm tone, authentic "
    "Brazilian formal ceremony atmosphere, editorial event photography. Natural "
    "skin texture with visible pores and fine lines appropriate for her age, no "
    "plastic AI look, no illustration or cartoon style, no excessive beauty "
    "retouching. Square 1:1 framing."
)

print("[INFO] Gerando foto base criativo 06 (mãe sozinha em evento de formatura)...")

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: 06 - Foto de parente sozinho? A IA acha.\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
