from __future__ import annotations

import json
import urllib.error
import urllib.request
from pathlib import Path


def generate_featured_image(
    api_key: str,
    prompt: str,
    output_path: Path,
    *,
    model: str = "dall-e-3",
    size: str = "1792x1024",
) -> Path:
    if not api_key:
        raise ValueError("OPENAI_API_KEY requis pour générer une image (DALL-E).")

    payload = {
        "model": model,
        "prompt": prompt,
        "n": 1,
        "size": size,
        "response_format": "url",
    }
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        "https://api.openai.com/v1/images/generations",
        data=data,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            body = json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        err = e.read().decode(errors="replace")
        raise RuntimeError(f"DALL-E HTTP {e.code} : {err[:400]}") from e

    image_url = body["data"][0]["url"]
    img_req = urllib.request.Request(image_url, headers={"User-Agent": "article-studio/1.0"})
    with urllib.request.urlopen(img_req, timeout=60) as resp:
        image_bytes = resp.read()

    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_bytes(image_bytes)
    return output_path
