#!/usr/bin/env python3
"""Gera a foto base realista do piloto 02 - 'OLHO FECHADO? FORA.' (v2)

v2 (2026-10-01): Renato pediu foto FRONTAL (nao perfil) com olhos
claramente fechados em mid-blink. Formatura brasileira (beca preta
+ faixa/estola), fundo discreto de evento desfocado.

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

PROMPT = (
    "Close-up photograph of a Brazilian graduation (formatura) ceremony. "
    "A young woman in her mid-20s, facing DIRECTLY toward the camera (frontal "
    "head-on portrait, NOT profile, NOT three-quarter view), head centered and "
    "squared to lens. Her EYES ARE CLEARLY CLOSED in a mid-blink moment: eyelids "
    "visibly down, lashes resting on the cheeks, the closed-eye expression is "
    "unmistakable and the clear focal point of the photo. Subtle, soft, neutral "
    "mouth expression (not a wide smile, not sad -- just caught mid-blink). "
    "She wears a classic Brazilian formatura outfit: black graduation gown with "
    "a satin sash/estola in a deep purple or burgundy institutional color draped "
    "over the shoulders. Capelo (graduation cap) optional. Natural warm "
    "cinematic event lighting from the side creating gentle rim light on her "
    "hair; main light soft on her face so the closed eyelids are perfectly "
    "readable. Shallow depth of field, 85mm portrait lens look, out-of-focus "
    "crowd of other graduates in black gowns softly visible in the background "
    "(bokeh, no distracting elements). Realistic professional event photography, "
    "editorial quality, natural skin tones with slight warm event color grading, "
    "no heavy makeup, no AI-generated plastic skin, no vector or illustration "
    "look. Square 1:1 framing, subject centered."
)

print("[INFO] Gerando foto base v2 (frontal + mid-blink)...")

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

client = OpenAI()

# Ordem preferida -> fallback. gpt-image-1 PROIBIDO.
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\nVERSION: v2 (frontal + mid-blink)\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
