"""Generate images via OpenAI DALL-E 3 API."""

import os
from datetime import datetime, timezone
from pathlib import Path

import httpx

IMAGES_URL = "https://api.openai.com/v1/images/generations"
VALID_SIZES = {"1024x1024", "1792x1024", "1024x1792"}


async def handler(params: dict) -> dict:
    """Generate an image from a text prompt using DALL-E 3."""
    prompt = params["prompt"]
    size = params.get("size", "1024x1024")
    quality = params.get("quality", "standard")

    if size not in VALID_SIZES:
        raise ValueError(f"Invalid size '{size}'. Must be one of: {', '.join(VALID_SIZES)}")
    if quality not in ("standard", "hd"):
        raise ValueError(f"Invalid quality '{quality}'. Must be 'standard' or 'hd'.")

    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("OPENAI_API_KEY not set. Get one at https://platform.openai.com/api-keys")

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    body = {
        "model": "dall-e-3",
        "prompt": prompt,
        "n": 1,
        "size": size,
        "quality": quality,
        "response_format": "url",
    }

    async with httpx.AsyncClient(timeout=120) as client:
        # Generate image
        resp = await client.post(IMAGES_URL, headers=headers, json=body)
        if resp.status_code != 200:
            error = resp.text[:500]
            raise ValueError(f"OpenAI Images API error ({resp.status_code}): {error}")

        data = resp.json()
        image_data = data["data"][0]
        image_url = image_data["url"]
        revised_prompt = image_data.get("revised_prompt", prompt)

        # Download image
        img_resp = await client.get(image_url)
        img_resp.raise_for_status()

    # Save to ~/.fliiq/generated/
    output_dir = Path.home() / ".fliiq" / "generated"
    output_dir.mkdir(parents=True, exist_ok=True)

    timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
    # Create a short slug from prompt
    slug = "".join(c if c.isalnum() else "_" for c in prompt[:40]).strip("_").lower()
    filename = f"{timestamp}_{slug}.png"
    file_path = output_dir / filename

    file_path.write_bytes(img_resp.content)

    return {
        "file_path": str(file_path),
        "revised_prompt": revised_prompt,
        "size": size,
        "quality": quality,
    }
