#!/usr/bin/env python3
"""Gera imagens de fundo realistas via OpenAI gpt-image-1 para o lote 2 do Borrello."""
import os
import base64
import sys
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor

# Carrega OPENAI_API_KEY do /opt/mia/.env
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()
        break

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

client = OpenAI()

OUT = Path("/opt/mia/workspace/clientes/borrello/criativos_ig_lote2_2026-09-21/imagens_base")
OUT.mkdir(parents=True, exist_ok=True)

# 5 estáticos + carrossel (usa imagens já do banco, gera 5 para os slides 2-6 do carrossel)
JOBS = [
    # ---- ESTÁTICOS ----
    ("01_casa_planta_baixa_bagua",
     "Realistic top-down floor plan of a modern Brazilian middle-class home, minimalist wood tones, "
     "warm natural light, seen from above like an architect drawing but photographic quality, "
     "no text, no labels, spacious rooms with subtle furniture, cinematic soft lighting, "
     "dark wood floor, high detail, editorial photography style, 4k",
     "1024x1536"),
    ("02_porta_entrada_casa",
     "Photorealistic front entrance door of a warm Brazilian home, seen from inside the living room, "
     "wooden door slightly ajar, natural sunlight coming through, plants near the door, "
     "elegant carpet, no people, cinematic mood, moody warm color grading, editorial photo, high detail 4k",
     "1024x1536"),
    ("03_sala_energia_pesada",
     "Photorealistic living room with slightly heavy atmosphere, dim golden hour light coming through window, "
     "some clutter subtly visible - stacked books, closed curtains partially, abandoned corner, "
     "warm brown wood tones, empty sofa, contemplative moody feeling, cinematic photography, no people, high detail 4k",
     "1024x1536"),
    ("04_vassoura_sal_grosso_limpeza",
     "Photorealistic close-up flat lay of energetic cleansing objects on wooden floor: "
     "a small bowl of coarse sea salt, a burning sage smudge stick with smoke, a lit white candle, "
     "a small broom, dried lavender, natural warm sunlight, top-down composition, minimalist Brazilian home, "
     "editorial photography, high detail 4k, no text",
     "1024x1536"),
    ("05_plantas_prosperidade",
     "Photorealistic beautiful arrangement of prosperity plants in ceramic pots on a wooden shelf: "
     "jade plant (crassula ovata), lucky bamboo, peace lily, money tree (pachira), pothos, "
     "natural warm sunlight from side window, modern Brazilian home interior, wooden background, "
     "editorial botanical photography, cinematic mood, high detail 4k, no text",
     "1024x1536"),

    # ---- CARROSSEL QUARTO (5 slides de conteúdo, cada um com uma cena diferente) ----
    ("c_slide2_cama_porta",
     "Photorealistic bedroom interior seen from above, showing a well-made bed with white linen "
     "positioned against a solid wall, NOT facing the door, warm natural light, minimalist wood furniture, "
     "cozy Brazilian home, cinematic soft lighting, editorial photography, no people, no text, 4k",
     "1024x1536"),
    ("c_slide3_espelho_quarto",
     "Photorealistic bedroom with a large mirror on the wall, mirror positioned so it does NOT reflect the bed, "
     "elegant wooden bed with white linen, warm evening light, minimalist decor, "
     "cinematic mood, editorial interior photography, no people, no text, high detail 4k",
     "1024x1536"),
    ("c_slide4_cabeceira_parede",
     "Photorealistic elegant bedroom close-up on the headboard against a solid painted wall, "
     "upholstered wooden headboard, white pillows, soft warm bedside lamp, "
     "Brazilian modern home, cinematic soft warm lighting, editorial photography, no people, no text, 4k",
     "1024x1536"),
    ("c_slide5_debaixo_cama_vazio",
     "Photorealistic side view of a clean bedroom with a bed slightly elevated, "
     "the space under the bed is completely empty and clean, wooden floor, "
     "warm natural light, minimalist decor, cinematic mood, editorial interior photography, no people, no text, 4k",
     "1024x1536"),
    ("c_slide6_cores_frias_quarto",
     "Photorealistic serene bedroom decorated in cool calming tones: soft blues, gentle grays, soft greens, "
     "white bed linen, natural light from a window, wooden floor, minimalist decor, "
     "peaceful atmosphere, cinematic soft lighting, editorial interior photography, no people, no text, 4k",
     "1024x1536"),
]


def gen(job):
    name, prompt, size = job
    dest = OUT / f"{name}.png"
    if dest.exists():
        print(f"  skip (existe): {name}")
        return name, True
    try:
        r = client.images.generate(
            model="gpt-image-1",
            prompt=prompt,
            size=size,
            quality="high",
            n=1,
        )
        b64 = r.data[0].b64_json
        dest.write_bytes(base64.b64decode(b64))
        print(f"  OK {name}")
        return name, True
    except Exception as e:
        print(f"  FAIL {name}: {e}")
        return name, False


if __name__ == "__main__":
    print(f"Gerando {len(JOBS)} imagens em paralelo (max 5 threads)...")
    with ThreadPoolExecutor(max_workers=5) as ex:
        results = list(ex.map(gen, JOBS))
    ok = sum(1 for _, s in results if s)
    print(f"\nConcluidos: {ok}/{len(JOBS)}")
    sys.exit(0 if ok == len(JOBS) else 1)
