import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

CHAT_URL = "https://api.quickrouter.ai/v1/chat/completions"


class QuickRouterPrompt:
    CATEGORY = "QuickRouter"
    FUNCTION = "enhance"
    RETURN_TYPES = ("STRING",)
    RETURN_NAMES = ("prompt",)

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "prompt": ("STRING", {"multiline": True, "default": ""}),
                "model": ("STRING", {"default": "gpt-4o-mini"}),
            }
        }

    def enhance(self, prompt, model):
        api_key = os.environ.get("QUICKROUTER_API_KEY", "").strip()
        if not api_key:
            raise ValueError("Set QUICKROUTER_API_KEY before starting ComfyUI.")
        if not prompt.strip() or not model.strip():
            raise ValueError("Enter a prompt and an exact QuickRouter model ID.")
        body = {
            "model": model.strip(),
            "messages": [
                {
                    "role": "system",
                    "content": "Refine the user's image or video prompt. Keep the subject and intent. Return only the revised prompt.",
                },
                {"role": "user", "content": prompt.strip()},
            ],
            "stream": False,
        }
        request = Request(
            CHAT_URL,
            data=json.dumps(body, ensure_ascii=False).encode("utf-8"),
            headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
            method="POST",
        )
        try:
            with urlopen(request, timeout=60) as response:
                data = json.load(response)
        except HTTPError as exc:
            raise RuntimeError(f"QuickRouter HTTP {exc.code}. Check the model and token in the console.") from None
        except (URLError, TimeoutError):
            raise RuntimeError("The QuickRouter request did not complete. Check the usage log before retrying.") from None
        try:
            text = data["choices"][0]["message"]["content"]
        except (KeyError, IndexError, TypeError):
            raise RuntimeError("Expected a Chat Completions response with choices[0].message.content.") from None
        if not isinstance(text, str) or not text.strip():
            raise RuntimeError("The model did not return prompt text.")
        return (text.strip(),)


NODE_CLASS_MAPPINGS = {"QuickRouterPrompt": QuickRouterPrompt}
NODE_DISPLAY_NAME_MAPPINGS = {"QuickRouterPrompt": "QuickRouter Prompt"}
