#!/usr/bin/env python3
"""Gera a foto base realista do criativo 07 - 'SEM FACE? AINDA ASSIM, IDENTIFICADO.'

Conceito: momento da outorga visto POR TRÁS numa formatura brasileira. Costas do
formando (beca preta + capelo) em primeiro plano, mão/aperto de mão do reitor
visível, luz quente de palco criando halo. Rostos NÃO visíveis (nem do formando,
nem do reitor) - só costas, mãos e capelo. É o momento mais icônico de formatura
e intencionalmente SEM face - exatamente o cenário em que o Cloud PhotoRF 2.0
precisa identificar pelo contexto/sequência, não pelo rosto.

Os overlays verdes (brackets + pill 'FORMANDO 089 · IDENTIFICADO POR SEQUÊNCIA'
+ tag 'ID · 089 · MATCH') 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 stage lighting + ampla composição
cinematográfica (full-bleed na composição final).

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/07_sem_face")
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_RAW = OUT_DIR / "foto_base_sem_face_raw.png"

PROMPT = (
    "Photorealistic cinematic photograph taken from BEHIND during the outorga "
    "moment of a Brazilian graduation ceremony. In the foreground, the BACK of "
    "a young graduate wearing a traditional black graduation gown with a dark "
    "sash and a black mortarboard cap with tassel - we only see their back, "
    "shoulders and the back of the mortarboard, NOT their face. The hands of "
    "the professor/reitor are visible in front of the graduate, shaking the "
    "graduate's hand or placing a graduation ring on their finger - we see "
    "only the professor's hands and sleeves (dark formal academic robe), NOT "
    "the professor's face either. Warm golden stage lighting from the front "
    "creates a soft halo and rim light around the graduate's silhouette and "
    "mortarboard, bokeh of audience and stage lights blurred in the deep "
    "background. Deeply emotional, cinematic composition. 85mm portrait lens "
    "look, shallow depth of field (f/1.8), warm event tone, authentic "
    "Brazilian formal ceremony atmosphere, editorial event photography. CRITICAL: "
    "NO FACES visible in the frame - neither the graduate nor the professor. "
    "Only backs, hands, mortarboard, gowns. Natural textures on fabric and skin, "
    "no plastic AI look, no illustration or cartoon style, no excessive "
    "retouching. Composition with the graduate slightly off-center and warm "
    "negative space in the lower-right for text overlay. Square 1:1 framing."
)

print("[INFO] Gerando foto base criativo 07 (outorga vista por trás, sem rostos)...")

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: 07 - Sem face? Ainda assim, identificado.\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
