#!/usr/bin/env python3
"""Gera a foto base realista do criativo 03 - 'FILA ROLANDO. VOCE, LIVRE.'

Conceito: fotografo relaxado tomando cafe enquanto o laptop ao fundo processa
uma fila de jobs (indicador verde PROCESSING visivel na tela, lista de arquivos
descendo). Angulo POSITIVO/LIBERDADE -> verde neon na composicao visual.

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

PROMPT = (
    "Photorealistic photograph of a professional photographer in his late 30s, "
    "wearing a dark casual sweater, sitting at a modern wooden desk by a large "
    "window with soft natural morning light coming from the left. He is holding "
    "a white ceramic coffee cup with both hands relaxed, slightly smiling and "
    "looking toward the window (out of frame to the left), calm and content "
    "expression -- clearly RELAXED, not working. In the background behind him "
    "(mid-ground, slightly out of focus but still readable), a 15-inch laptop "
    "screen is open and clearly visible showing a dark software interface with "
    "a vertical list of photo batches being processed: green progress bars, a "
    "bright 'PROCESSING...' indicator in neon green color, file names scrolling "
    "down the list (filenames like IMG_0847.CR2, IMG_0848.CR2 visible), the "
    "screen glows with greenish-cyan tech light. On the desk: an SD card "
    "reader, a small notebook, a potted green plant, a mechanical keyboard. "
    "Clean minimalist workspace, warm wood tones contrasting with the cool "
    "green glow of the laptop screen. 50mm environmental portrait lens look, "
    "shallow depth of field but background screen still legible, cinematic "
    "warm morning tone with green accent from the laptop. The composition "
    "leaves significant NEGATIVE SPACE on the LEFT side of the frame (for "
    "text overlay). Subject positioned RIGHT-of-center. Realistic editorial "
    "photography, natural skin tones, no AI plastic look, no vector or "
    "illustration style. Square 1:1 framing."
)

print("[INFO] Gerando foto base criativo 03 (fotografo relaxado + laptop processando)...")

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: 03 - Fila rolando, voce livre\n\nPROMPT:\n{PROMPT}\n"
)
print(f"[OK] Prompt salvo: {OUT_DIR / 'PROMPT_GPT_IMAGE.txt'}")
