#!/usr/bin/env python3
"""Gera as fotos do criativo 09 v2 - CONCEITO CORRETO.

Conceito: o sistema analisa a pasta de UM formando especifico (formando 112).
Ele aparece em muitas fotos, mas na maioria delas ele e so figurante no fundo
de fotos de OUTROS formandos (cabeca baixa, de costas, passando, borrado).
O Cloud PhotoRF 2.0 identifica isso e descarta em lote da pasta dele.

Precisa de 2 tipos de foto:

PASSO 1 - KEEP (1 foto):
  Close-up/retrato nitido da formanda 112 em primeiro plano, nitida, focada.
  Essa e a UNICA foto do grid que vale a pena manter.

PASSO 2 - BG (7 fotos):
  Cenas de evento onde OUTRAS pessoas sao protagonistas. Em cada uma, um
  figurante no fundo (borrado, cabeca baixa, de costas, passando). O conceito
  funciona pela narrativa + a cara borrada do fundo e exatamente o que o
  sistema identifica.

Modelo: gpt-image-2.5-sunburst (preferido)
Fallbacks: 2.5-flare -> 2 -> 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/09_revisao_fundos")
OUT_DIR.mkdir(parents=True, exist_ok=True)
FOTOS_DIR = OUT_DIR / "fotos_v2_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",
]


# ============================================================================
# PROMPTS
# ============================================================================

PROMPT_KEEP = (
    "Photorealistic professional close-up portrait photograph of a young "
    "Brazilian woman graduate, 25 years old, long dark wavy hair, warm "
    "confident smile, facing camera directly, wearing a black graduation gown "
    "with burgundy sash and golden tassel, holding her rolled diploma proudly "
    "in both hands at chest level. Warm golden event lighting on her face, "
    "shallow depth of field, out-of-focus bokeh of graduation ceremony venue "
    "behind (candles, drapery, golden lights). 85mm portrait lens, f/1.8, "
    "crisp sharp focus on her face and eyes, in-focus foreground subject. "
    "Professional event photographer capture. Natural skin tones, no "
    "retouching. NOT AI-looking, documentary photojournalism feel. Square 1:1 "
    "framing."
)

# 7 fotos de BG - cenas de evento onde outras pessoas sao protagonistas,
# e um figurante aparece no FUNDO (borrado, de costas, cabeca baixa).
# A ideia e: cada foto tem OUTRO formando como foco, mas um corpo/figura ao
# fundo que o sistema identificou como sendo a formanda 112.
PROMPTS_BG = [
    # BG 1 - foto principal de outro formando, figura passando no fundo
    (
        "bg_1_passando",
        "Photorealistic candid event photograph. Foreground: a Brazilian male "
        "graduate (30yo, short dark hair, black graduation gown with burgundy "
        "sash) smiling broadly at the camera in sharp focus. Background: "
        "out-of-focus, a female figure with long dark hair wearing a dark "
        "graduation gown walking past from left to right, motion-blurred, "
        "head slightly down, face not visible. Warm golden ambient lighting, "
        "graduation ceremony venue, bokeh of candles behind. 50mm lens, f/2, "
        "shallow depth of field. Documentary event photography. Background "
        "figure is clearly unintentional - a bystander in frame. Not AI "
        "looking, natural, candid. Square 1:1 framing."
    ),
    # BG 2 - foto de grupo de outros, figura ao fundo cabeca baixa
    (
        "bg_2_cabeca_baixa",
        "Photorealistic candid event photograph. Foreground: group of three "
        "Brazilian graduates (two women, one man, 25-30yo, black graduation "
        "gowns with burgundy sashes) posing together with arms around each "
        "other, smiling, in sharp focus. Background: slightly out-of-focus, "
        "a lone female figure with long dark hair in dark graduation gown "
        "looking down at her phone, head tilted down, face hidden by hair. "
        "Warm event lighting, out-of-focus bokeh of ceremony behind. 35mm "
        "lens, f/2.8. Documentary candid style. The background figure is "
        "unintentional, a bystander caught in frame. Not AI-looking, natural. "
        "Square 1:1 framing."
    ),
    # BG 3 - closeup diploma, figura de costas no fundo
    (
        "bg_3_de_costas",
        "Photorealistic candid event photograph. Foreground: close-up of two "
        "hands exchanging a rolled graduation diploma with burgundy ribbon, "
        "sharp focus on the diploma and hands. Background: out-of-focus, the "
        "back of a female graduate with long dark hair in black graduation "
        "gown walking away from the camera. Warm golden lighting, bokeh of "
        "event venue behind. 85mm lens, f/1.8, extremely shallow depth of "
        "field. Documentary event photography. The background figure is "
        "incidental, caught in frame. Natural, candid, not AI-looking. "
        "Square 1:1 framing."
    ),
    # BG 4 - palco amplo, varias figuras pequenas sentadas
    (
        "bg_4_platea_distante",
        "Photorealistic wide shot of a Brazilian graduation ceremony. "
        "Foreground: elevated view from stage looking out at the audience. "
        "Multiple graduates seated in rows wearing black gowns with burgundy "
        "sashes, all facing forward toward speaker. One female figure with "
        "long dark hair visible mid-row looking slightly down at her lap. "
        "Warm golden ambient event lighting, decorated venue with drapery. "
        "35mm wide lens, f/4, deep depth of field but far distance makes "
        "faces not readable. Documentary ceremony photography. Not AI-looking, "
        "natural event photo. Square 1:1 framing."
    ),
    # BG 5 - selfie de dois, figura passando atras borrada
    (
        "bg_5_selfie_fundo_borrado",
        "Photorealistic candid event photograph. Foreground: two Brazilian "
        "graduates (a man and a woman, 25yo, black graduation gowns with "
        "burgundy sashes) taking a selfie together with phone held out, "
        "smiling broadly, sharp focus on their faces. Background: completely "
        "out-of-focus, a female figure with long dark hair in dark gown "
        "crossing behind them, motion-blurred, face not identifiable, just a "
        "silhouette. Warm golden event lighting, bokeh of candles and "
        "drapery. 50mm lens, f/1.8, extremely shallow depth of field. "
        "Documentary candid style. Not AI-looking, natural. Square 1:1 "
        "framing."
    ),
    # BG 6 - casal abracado, figura ao canto olhando pro lado
    (
        "bg_6_olhando_para_o_lado",
        "Photorealistic candid event photograph. Foreground: a graduate (man, "
        "28yo, black gown with burgundy sash) hugging his smiling mother "
        "(50yo, elegant dress), warm emotional moment, sharp focus. "
        "Background: slightly out-of-focus to the right edge of frame, a "
        "lone female figure with long dark hair in black graduation gown "
        "looking away to the side, profile view only, face partially visible. "
        "Warm golden event lighting, bokeh of ceremony venue. 50mm lens, "
        "f/2. Documentary event photography. Background figure caught "
        "incidentally in frame. Natural, not AI-looking. Square 1:1 framing."
    ),
    # BG 7 - brinde amplo, figura entre a multidao de cabeca baixa
    (
        "bg_7_multidao_cabeca_baixa",
        "Photorealistic wide shot of a Brazilian graduation celebration. "
        "Foreground: multiple graduates (6-7 people, mixed, 25-30yo, black "
        "gowns with burgundy sashes) raising champagne glasses in a toast, "
        "all smiling broadly facing each other, sharp focus. Background: in "
        "the crowd behind them, a female figure with long dark hair in "
        "graduation gown with head bowed looking at something in her hands, "
        "partially visible between other people. Warm golden ambient event "
        "lighting, decorated venue with candles and drapery. 35mm lens, "
        "f/2.8, shallow depth of field. Documentary candid celebration "
        "photography. Not AI-looking, natural. 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 = []

    # PASSO 1 - KEEP
    print("\n=== PASSO 1 - KEEP (close-up formanda) ===")
    out = FOTOS_DIR / "keep_formanda_112.png"
    if out.exists():
        print(f"[SKIP] ja existe: {out.name}")
        log.append(("keep_formanda_112", "ja_existente"))
    else:
        model = gerar(PROMPT_KEEP, out)
        log.append(("keep_formanda_112", model))

    # PASSO 2 - BGs
    print(f"\n=== PASSO 2 - BGs ({len(PROMPTS_BG)} fotos) ===")
    for name, prompt in PROMPTS_BG:
        out = FOTOS_DIR / f"{name}.png"
        if out.exists():
            print(f"[SKIP] ja existe: {out.name}")
            log.append((name, "ja_existente"))
            continue
        model = gerar(prompt, out)
        log.append((name, model))

    # salva log
    lines = ["# Fotos v2 do criativo 09 - CONCEITO CORRETO\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_KEEP\n")
    lines.append(PROMPT_KEEP)
    lines.append("\n\n## PROMPTS_BG\n")
    for name, prompt in PROMPTS_BG:
        lines.append(f"\n### {name}\n{prompt}\n")
    (OUT_DIR / "PROMPTS_V2.md").write_text("\n".join(lines))
    print(f"\n[OK] Log salvo: {OUT_DIR / 'PROMPTS_V2.md'}")


if __name__ == "__main__":
    main()
