"""VAPI image adapter — POST /images/generations, download URL to save."""
import base64
import json
import os
import sys

import requests


class VAPIImageAdapter:
    def generate(self, prompt, config, **kwargs):
        base_url = config["base_url"].rstrip("/")
        api_key = config["api_key"]
        model = config["model"]
        aspect_ratio = kwargs.get("aspect_ratio", "")
        out_dir = kwargs["out_dir"]

        url = f"{base_url}/images/generations"
        payload = {
            "model": model,
            "prompt": prompt,
            "n": 1,
            "response_format": "url",
        }
        if aspect_ratio:
            payload["aspect_ratio"] = aspect_ratio

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

        print(f"[vapi_image] generating with model={model}...", file=sys.stderr)
        resp = requests.post(url, headers=headers, json=payload, timeout=180)
        if resp.status_code != 200:
            raise RuntimeError(f"VAPI API error ({resp.status_code}): {resp.text}")

        data = resp.json()
        images = data.get("data", [])
        if not images:
            raise RuntimeError("no image data in response")

        saved = []
        for i, item in enumerate(images):
            image_url = item.get("url")
            b64 = item.get("b64_json")
            fname = kwargs.get("output_path") or os.path.join(out_dir, f"image_{i+1}.png")

            if b64:
                with open(fname, "wb") as f:
                    f.write(base64.b64decode(b64))
            elif image_url:
                r = requests.get(image_url, timeout=120)
                r.raise_for_status()
                with open(fname, "wb") as f:
                    f.write(r.content)
            else:
                raise RuntimeError(f"no image data for item {i}")

            saved.append(fname)
            print(f"[vapi_image] saved: {fname}", file=sys.stderr)

        return saved
