"""
generate_background.py — Genera fondos artísticos para los flyers de Kings & Queens
usando DALL-E 3 de OpenAI.

Uso interno: importado por generate_flyer.py
"""

import io
import base64
from PIL import Image

# ---------------------------------------------------------------------------
# Prompts por tipo de flyer
# ---------------------------------------------------------------------------

BACKGROUND_PROMPTS = {
    "promo": (
        "Flat design background for a language school Instagram post. "
        "Solid teal color (#73C3B4) as the main background with a very subtle white square grid pattern. "
        "Scattered around the edges and corners: coral pink outlined 5-pointed stars, "
        "cartoon Saturn-like planets with rings in teal and coral pink, "
        "small cross sparkles in yellow, paper clip shapes. "
        "Fun, modern, educational aesthetic. Bright and cheerful. "
        "The center area must be clean and mostly empty for text overlay. "
        "No text. No letters. No words. No people. No faces."
    ),
    "evento": (
        "Playful flat design background for a special event announcement Instagram post. "
        "Solid teal green background with a subtle white square grid. "
        "Decorative cartoon sticker elements at the borders and corners: "
        "outlined coral pink stars, teal planets with rings, confetti dots, yellow sparkles. "
        "Festive and energetic feel. "
        "Clean empty center area for text overlay. "
        "No text. No words. No people. No faces."
    ),
    "educativo": (
        "Clean flat design background for educational content on Instagram. "
        "Teal green background with a very subtle square grid pattern. "
        "School and stationery sticker elements at the corners and edges: "
        "pencil outlines, outlined stars, Saturn planets, small books, sparkles "
        "in coral pink and yellow. Academic but playful style. "
        "Large clean empty center area. "
        "No text. No words. No letters. No people."
    ),
    "testimonio": (
        "Warm celebratory flat design background for a success story Instagram post. "
        "Teal green background with subtle white grid. "
        "Decorative elements at the edges: outlined stars and sparkles in coral pink and yellow, "
        "small planets, confetti shapes. Celebratory and inspiring feel. "
        "Clean empty center for quote overlay. "
        "No text. No words. No people. No faces."
    ),
}

# DALL-E 3 soporta: 1024x1024, 1024x1792, 1792x1024
DALLE_SIZES = {
    "story": "1024x1792",  # 9:16 — exacto para Stories
    "post":  "1024x1024",  # cuadrado, Pillow lo escala a 4:5
}


def generate_background(api_key: str, flyer_type: str, format_type: str) -> Image.Image:
    """
    Llama a DALL-E 3 para generar un fondo artístico.
    Devuelve una imagen PIL lista para redimensionar al canvas final.
    """
    from openai import OpenAI

    client = OpenAI(api_key=api_key)
    prompt = BACKGROUND_PROMPTS.get(flyer_type, BACKGROUND_PROMPTS["promo"])
    size = DALLE_SIZES.get(format_type, "1024x1792")

    print(f"  Generando fondo con DALL-E 3 ({size})...")

    response = client.images.generate(
        model="dall-e-3",
        prompt=prompt,
        size=size,
        quality="hd",
        response_format="b64_json",
        n=1,
    )

    img_bytes = base64.b64decode(response.data[0].b64_json)
    img = Image.open(io.BytesIO(img_bytes))
    print(f"  Fondo generado: {img.size[0]}x{img.size[1]}px")
    return img
