"""Alibaba Cloud Model Studio native DashScope protocol."""

from typing import Any

from agenteval.models import ModelCapability, ModelProtocol

from .base import ModelProtocolAdapter, ProtocolAdapterError


class DashScopeAdapter(ModelProtocolAdapter):
    protocol = ModelProtocol.DASHSCOPE
    supported_capabilities = frozenset({ModelCapability.CHAT})

    def headers(self, api_key: str | None) -> dict[str, str]:
        headers = super().headers(api_key)
        if api_key:
            headers["Authorization"] = f"Bearer {api_key}"
        return headers

    def chat_payload(
        self,
        model_name: str | None,
        messages: list[dict[str, str]],
        temperature: float,
    ) -> dict[str, Any]:
        return {
            "model": self.require_model(model_name),
            "input": {"messages": messages},
            "parameters": {"result_format": "message", "temperature": temperature},
        }

    def parse_chat(self, data: dict[str, Any]) -> str:
        try:
            content = data["output"]["choices"][0]["message"]["content"]
        except (KeyError, IndexError, TypeError) as exc:
            raise ProtocolAdapterError("DashScope 接口返回格式不正确") from exc
        if isinstance(content, list):
            content = "\n".join(
                str(block.get("text") or block.get("content") or "")
                for block in content
                if isinstance(block, dict)
            )
        if not content:
            raise ProtocolAdapterError("模型接口返回内容为空")
        return str(content)
