#!/usr/bin/env python3
"""Gera a foto base realista do criativo 08 - 'FOTOS IGUAIS? SO A MELHOR FICA.'

Conceito: UMA foto hero realista de uma formanda brasileira sorrindo com o
diploma na mao, enquadramento tipo retrato de evento. Essa UMA foto vai ser
replicada 5 vezes no build com micro-variacoes programaticas (opacity, blur,
cor) formando a 'rajada' / filmstrip de burst-mode. A central/melhor fica em
cor viva com bracket verde 'KEEP', as outras 4 ficam dessaturadas + overlay
dark + X vermelho pequeno discreto.

Decisao: pedir UMA foto hero (modelo de imagem renderiza bem retrato
individual) e montar o filmstrip no Pillow/CSS. Pedir pro gpt-image renderizar
uma sequencia de 5 frames quase-identicos em contact-sheet costuma falhar
(acaba inventando pessoas diferentes).

Angulo POSITIVO (resolucao via dedup) -> paleta warm/natural + sorriso
franco + diploma visivel.

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/08_fotos_iguais")
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_RAW = OUT_DIR / "foto_base_formanda_raw.png"

PROMPT = (
    "Photorealistic cinematic portrait of a young Brazilian female university "
    "graduate, around 23 years old, mixed Brazilian ethnicity, long dark wavy "
    "hair, wearing a classic black graduation gown with a dark academic sash "
    "and a black mortarboard cap with tassel on her head. She is smiling "
    "genuinely at the camera, holding her rolled graduation diploma tied with "
    "a ribbon in both hands at chest level, visible and in focus. Shot from "
    "chest-up, slight 3/4 angle. Behind her, soft bokeh of a formal graduation "
    "ceremony venue with warm golden stage lighting and blurred audience/stage "
    "lights creating a cinematic halo and rim light. Natural happy expression, "
    "authentic emotion, slight tears of joy possible. 85mm portrait lens, "
    "shallow depth of field (f/1.8), warm event tone, Brazilian formal "
    "ceremony atmosphere, professional editorial event photography. Natural "
    "skin texture, no plastic AI look, no illustration or cartoon style, no "
    "excessive retouching, no filter. The subject is centered with warm "
    "negative space around her for cropping. Square 1:1 framing. CRITICAL: "
    "ONE person only, face clearly visible, diploma clearly visible, "
    "photorealistic documentary feel."
)

print("[INFO] Gerando foto base criativo 08 (formanda sorrindo com diploma)...")

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: 08 - Fotos iguais? So a melhor fica.\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
