"""
火山方舟 Adapter
================

实现 PlatformAdapter + SyncCapable。
直接接入 VolcengineProvider，提供标准 Protocol 接口。
"""

from __future__ import annotations

import logging
from typing import Any

from app.ai.adapters.base import AdapterResponse, PlatformAdapter, SyncCapable
from app.ai.adapters.constants import Method
from app.ai.providers.volcengine_provider import VolcengineProvider
from app.core.exceptions import PlatformError, PlatformErrorType

logger = logging.getLogger(__name__)


class VolcengineArkAdapter(PlatformAdapter, SyncCapable):
    """火山方舟 LLM 平台标准 Adapter"""

    platform_id = "volcengine_ark"

    def __init__(self, provider: VolcengineProvider):
        self.provider = provider

    # ── PlatformAdapter ──

    async def health(self) -> AdapterResponse:
        try:
            health = await self.provider.health_check()
            return AdapterResponse(
                success=health.is_available,
                data={"response_time_ms": health.response_time},
            )
        except Exception as e:
            return AdapterResponse(
                success=False,
                error_message=str(e),
                retryable=False,
            )

    async def close(self) -> None:
        if hasattr(self.provider.client, "close"):
            await self.provider.client.close()

    # ── SyncCapable ──

    async def call(self, method: str, payload: dict[str, Any]) -> AdapterResponse:
        try:
            if method == Method.CHAT:
                result = await self.provider.generate(
                    prompt=payload["prompt"],
                    model=payload.get("model"),
                    max_tokens=payload.get("max_tokens"),
                    system_prompt=payload.get("system_prompt"),
                    reasoning_effort=payload.get("reasoning_effort"),
                )
                return AdapterResponse(
                    success=True,
                    data={
                        "content": result.content,
                        "usage": result.usage,
                        "model": result.model,
                    },
                )

            elif method == Method.EMBEDDING:
                result = await self.provider.create_embeddings(
                    texts=payload["texts"],
                    model=payload.get("model"),
                )
                return AdapterResponse(success=True, data=result)

            else:
                return AdapterResponse(
                    success=False,
                    error_message=f"不支持的方法: {method}",
                    retryable=False,
                )

        except PlatformError:
            raise
        except Exception as e:
            raise PlatformError(
                f"火山方舟 {method} 调用失败: {e}",
                platform="volcengine_ark",
                retryable=False,
                error_type=PlatformErrorType.UNKNOWN,
            ) from e
