#!/usr/bin/env python3
"""Gera a foto base realista do criativo 09 - 'REVISAO DE FUNDOS. UM CLIQUE.'

Conceito: mosaico 3x3 de 9 fotos de 'ambiente vazio' de um evento de formatura
brasileiro - parede decorada, palco com cadeiras arrumadas, mesas redondas sem
pessoas, decoracao com flores, equipamento de luz, pista de danca vazia, backdrop
com totem/signage de formatura, canto com velas, drapejado de teto. Todos com
mesma iluminacao warm/golden e paleta (gold, cream, burgundy). Estetica de
contact-sheet editorial / documentary flat-lay.

Essa UMA imagem (contact-sheet) vai receber overlay dessaturado + X vermelho
pequeno em cada tile, com UMA foto do grid ficando com cor viva + bracket verde
(reforcar que nao e descarte burro - a IA sabe o que vale a pena manter). O pill
grande 'DESCARTAR N BGS' + botao verde vai sobreposto no CSS.

Angulo POSITIVO (resolucao via dedup/descarte) -> fotos reais de evento com
visual limpo, nenhum rosto humano em primeiro plano.

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
"""
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/09_revisao_fundos")
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_RAW = OUT_DIR / "foto_base_bgs_vazios_raw.png"

PROMPT = (
    "Photorealistic photo contact sheet composition showing a clean 3x3 grid of "
    "9 photographs - all images are 'empty background' shots from a Brazilian "
    "formal graduation ceremony venue, documentary event photography style, no "
    "people visible in any frame. The 9 images, left-to-right top-to-bottom: "
    "(1) close-up of an ornate decorated wall with golden floral arrangements, "
    "(2) wide shot of empty stage with chairs lined up in rows waiting for the "
    "ceremony, (3) round banquet tables with white tablecloths and centerpieces "
    "of candles and flowers but no guests, (4) tall golden candelabras with lit "
    "candles against a dark backdrop, (5) professional stage lighting equipment "
    "and par cans mounted on truss, (6) wide empty polished dance floor with "
    "warm uplighting on the walls, (7) a decorated graduation backdrop/photo "
    "wall with 'FORMATURA' signage typography blurred, (8) a corner detail of "
    "burgundy velvet drapery with gold tassels, (9) ceiling view of elegant "
    "fabric drapery with warm pendant lights. All 9 shots share the same warm "
    "golden-cream-burgundy event color palette, same warm ambient lighting, "
    "same editorial documentary feel, 35mm medium shots, consistent exposure. "
    "The 9 images arranged as a perfectly clean 3x3 grid with thin white "
    "gutters between frames (contact sheet style). Flat lay feel, top-down "
    "layout, no 3D perspective of the grid itself. Professional event "
    "photography portfolio sheet. NOT illustrated, NOT AI-looking, "
    "photorealistic. CRITICAL: ZERO people, ZERO faces, only empty venue "
    "details and decoration. Square 1:1 framing."
)

print("[INFO] Gerando foto base criativo 09 (contact sheet 3x3 de BGs vazios)...")

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: 09 - Revisao de fundos. Um clique.\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
