#!/usr/bin/env python3
"""Gera background atmosferico da capa YouTube via GPT Image."""
import os, base64, requests, sys

# Carrega API key do .env
with open("/opt/mia-bot/.env") as f:
    for line in f:
        if line.startswith("OPENAI_API_KEY="):
            os.environ["OPENAI_API_KEY"] = line.split("=", 1)[1].strip()
            break

API_KEY = os.environ["OPENAI_API_KEY"]

prompt = """Atmospheric background for premium YouTube thumbnail, 1536x1024 landscape format. Deep midnight blue gradient background #1A1A2E to #2A2A4E, with very subtle golden geometric grid pattern (lines every 80px, opacity 5%) creating depth.

CENTER-RIGHT: ethereal wireframe globe in light midnight blue #2A2A4E, semi-transparent, with thin glowing lines suggesting longitude/latitude. Behind the globe a soft golden radial halo gradient (rgba(230,179,36,0.18) fading to transparent). 4 small golden floating light particles (5-8px diameter, soft glow) scattered around the globe area suggesting energy points.

LEFT THIRD: empty atmospheric space, very dark midnight blue, with soft cinematic golden rim light bleeding from the right edge into this area (subtle gradient).

CENTER-BOTTOM and BOTTOM AREA: empty neutral dark space, reserved for text overlay later. Keep this area clean of any decorative elements.

NO TEXT WHATSOEVER. NO LETTERS. NO WORDS. NO NUMBERS. NO TYPOGRAPHY OF ANY KIND.
NO PEOPLE, NO PORTRAITS, NO FACES.
NO chinese symbols, no bagua octagon (will be added later), no compass rose, no decorative motifs.

Mood: cinematic premium, like opening shot of a documentary about astronomy or ancient navigation, elegant mysticism without any kitsch element. Style reference: book cover for "The Tao of Physics" meets minimal poster design.

DO NOT INCLUDE: any text, letters, words, numbers, ideograms, calligraphy, people, faces, portraits, golden toad, koi fish, cartoon dragon, lucky cat, chinese coins, red lanterns, wind chimes, crystals, rainbow gradients, comic sans, oversaturated colors, incense smoke, zodiac mascots, clipart, raffle confetti, roulette wheel, watermarks, logos."""

print("Gerando background da capa YouTube via GPT Image (1536x1024)...")

r = requests.post(
    "https://api.openai.com/v1/images/generations",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "model": "gpt-image-1",
        "prompt": prompt,
        "size": "1536x1024",
        "quality": "high",
        "n": 1,
        "output_format": "png"
    },
    timeout=180
)

if r.status_code != 200:
    print(f"ERRO: {r.status_code}")
    print(r.text)
    sys.exit(1)

data = r.json()
img_b64 = data["data"][0]["b64_json"]
img_bytes = base64.b64decode(img_b64)

destino = "/opt/mia/workspace/clientes/francisco_borrello/live-02-06/visuais/temp/bg_capa_yt.png"
with open(destino, "wb") as f:
    f.write(img_bytes)

print(f"OK: {destino}")
print(f"Usage: {data.get('usage', {})}")
