#!/usr/bin/env python3
"""Gera a foto base do criativo 10 - WINDOWS OU MAC.

Conceito: MacBook e laptop Windows lado a lado, ambos rodando a MESMA tela
do software de galeria de fotos de formatura (interface dark com verde).
Transmite "multiplataforma: escolha seu equipamento, o produto se adapta".

Modelo: gpt-image-2.5-sunburst (preferido)
Fallbacks: 2.5-flare -> 2 -> 1.5
PROIBIDO: gpt-image-1
"""
import os
import base64
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(__file__).resolve().parent
FOTOS_DIR = OUT_DIR / "fotos_raw"
FOTOS_DIR.mkdir(exist_ok=True)

MODELS = [
    "gpt-image-2.5-sunburst",
    "gpt-image-2.5-flare",
    "gpt-image-2",
    "gpt-image-1.5",
]

# Prompt principal: dois laptops, mesma tela
PROMPT_DUAL = (
    "Photorealistic product shot of a professional photographer's workspace: "
    "a modern silver MacBook Pro on the left and a sleek dark Windows laptop "
    "on the right, placed side by side on a clean wooden desk. Both screens "
    "show the SAME dark-mode photo gallery software interface - a grid of "
    "thumbnails of graduation photos (young graduates in black gowns with "
    "burgundy sashes), with green accent elements (progress bars, selection "
    "highlights, small green buttons). Warm desk lamp light from above, "
    "slightly out of focus background with a plant and a notebook. Clean "
    "minimalist workspace. 35mm wide lens shot from slightly above at a "
    "15-degree angle, both screens clearly visible, same software interface "
    "running on both machines. Not AI-generated appearance, documentary "
    "product photography. Dark moody background with warm highlights. "
    "Negative space on top for text overlay. Square 1:1 framing."
)


def gerar(prompt: str, out_path: Path) -> str:
    try:
        from openai import OpenAI
    except ImportError:
        os.system("pip install --break-system-packages openai -q")
        from openai import OpenAI
    client = OpenAI()
    errors = []
    for model in MODELS:
        try:
            print(f"[TRY] {model} -> {out_path.name}")
            resp = client.images.generate(
                model=model, prompt=prompt, size="1024x1024",
                quality="high", n=1,
            )
            out_path.write_bytes(base64.b64decode(resp.data[0].b64_json))
            print(f"[OK]  {model} -> {out_path.name} ({out_path.stat().st_size // 1024} KB)")
            return model
        except Exception as e:
            msg = str(e)[:200]
            print(f"[WARN] {model} falhou: {msg}")
            errors.append(f"{model}: {msg}")
    raise RuntimeError(f"Todos modelos falharam: {errors}")


def main():
    log = []
    print("\n=== Criativo 10 - WINDOWS OU MAC (foto base) ===")
    out = FOTOS_DIR / "dual_laptops.png"
    if out.exists():
        print(f"[SKIP] ja existe: {out.name}")
        log.append(("dual_laptops", "ja_existente"))
    else:
        model = gerar(PROMPT_DUAL, out)
        log.append(("dual_laptops", model))

    lines = ["# Fotos do criativo 10 - WINDOWS OU MAC\n"]
    lines.append("Modelo preferido: gpt-image-2.5-sunburst (fallback: 2.5-flare, 2, 1.5)\n")
    lines.append("\n## Fotos geradas\n")
    for name, m in log:
        lines.append(f"- {name}.png  -> {m}")
    lines.append("\n\n## PROMPT_DUAL\n")
    lines.append(PROMPT_DUAL)
    (OUT_DIR / "PROMPTS.md").write_text("\n".join(lines))
    print(f"\n[OK] Log salvo: {OUT_DIR / 'PROMPTS.md'}")


if __name__ == "__main__":
    main()
