#!/usr/bin/env python3
"""Gera a foto base realista do criativo 04 - '3 ETAPAS DE VERIFICACAO. ZERO ERRO.'

Conceito: formanda sendo processada pelo software, retrato limpo frontal,
com estetica de "sala de controle / painel" ao fundo. Checkmarks sao
sobrepostos via HTML/CSS no build (controle total), entao a foto base
NAO deve ter nenhum overlay de UI - so o retrato + ambiente tech sutil.

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

PROMPT = (
    "Photorealistic graduation portrait photograph of a young Brazilian woman "
    "in her early 20s, wearing a classic black academic graduation gown with "
    "a black graduation cap (mortarboard) tilted slightly, confident warm "
    "smile with white teeth visible, looking directly at the camera, soft "
    "natural brown eyes. Studio-event hybrid lighting: warm key light on her "
    "face from front-left (cinematic event lighting), subtle cool green rim "
    "light on the right side of her hair and shoulder (hinting at a software "
    "scanning environment). The background is a soft dark blurred bokeh with "
    "greenish-cyan highlights (deep out of focus suggestion of a control room "
    "or monitor glow), very shallow depth of field. Thin faint neon green "
    "horizontal scan line barely visible crossing the frame at eye level (very "
    "subtle, almost imperceptible, just a hint of a software interface). "
    "Clean skin, natural tones, no plastic AI look, no illustration style, no "
    "cartoon. 85mm portrait prime lens aesthetic. Composition: subject "
    "centered-left in the frame, head and shoulders portrait, significant "
    "NEGATIVE SPACE on the RIGHT side for UI overlay elements. Editorial "
    "quality, realistic skin pores and hair detail, warm event ceremony "
    "atmosphere mixed with cool tech accent. Square 1:1 framing."
)

print("[INFO] Gerando foto base criativo 04 (formanda retrato + ambiente tech sutil)...")

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: 04 - 3 etapas de verificacao, zero erro\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
