"""
Anthropic-compatible client for SpendLil proxy.
Mirrors the `anthropic` package's interface.
"""
from __future__ import annotations

from typing import Any, AsyncGenerator, Dict, List, Optional

from .client import (
    SpendLilConfig,
    SpendLilError,
    SpendLilMeta,
    async_proxy_request,
    async_stream_sse,
    proxy_request,
)

_ANTHROPIC_HEADERS = {"anthropic-version": "2023-06-01"}


class _Messages:
    """Mirrors anthropic.messages interface."""

    def __init__(self, cfg: SpendLilConfig, api_key: str):
        self._cfg = cfg
        self._api_key = api_key

    def _auth_headers(self) -> Dict[str, str]:
        return {"x-api-key": self._api_key, **_ANTHROPIC_HEADERS}

    def create(
        self,
        *,
        model: str,
        messages: List[Dict[str, str]],
        max_tokens: int,
        system: Optional[str] = None,
        temperature: Optional[float] = None,
        session_key: Optional[str] = None,
        priority: Optional[str] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Synchronous message creation.
        Returns a dict that mirrors the Anthropic response shape
        with an extra ``_spendlil`` key.
        """
        body: Dict[str, Any] = {"model": model, "messages": messages, "max_tokens": max_tokens, **kwargs}
        if system:
            body["system"] = system
        if temperature is not None:
            body["temperature"] = temperature

        status, headers, resp_body = proxy_request(
            self._cfg,
            "/proxy/anthropic/v1/messages",
            body,
            self._auth_headers(),
            session_key or self._cfg.session_key,
            priority,
        )

        if status >= 400:
            meta = SpendLilMeta.from_headers(headers)
            err = resp_body.get("error", {})
            msg = err.get("message", str(err)) if isinstance(err, dict) else str(err)
            raise SpendLilError(status, msg, resp_body, meta)

        resp_body["_spendlil"] = SpendLilMeta.from_headers(headers)
        return resp_body

    async def async_create(
        self,
        *,
        model: str,
        messages: List[Dict[str, str]],
        max_tokens: int,
        system: Optional[str] = None,
        temperature: Optional[float] = None,
        session_key: Optional[str] = None,
        priority: Optional[str] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Async message creation."""
        body: Dict[str, Any] = {"model": model, "messages": messages, "max_tokens": max_tokens, **kwargs}
        if system:
            body["system"] = system
        if temperature is not None:
            body["temperature"] = temperature

        status, headers, resp_body = await async_proxy_request(
            self._cfg,
            "/proxy/anthropic/v1/messages",
            body,
            self._auth_headers(),
            session_key or self._cfg.session_key,
            priority,
        )

        if status >= 400:
            meta = SpendLilMeta.from_headers(headers)
            err = resp_body.get("error", {})
            msg = err.get("message", str(err)) if isinstance(err, dict) else str(err)
            raise SpendLilError(status, msg, resp_body, meta)

        resp_body["_spendlil"] = SpendLilMeta.from_headers(headers)
        return resp_body

    async def async_stream(
        self,
        *,
        model: str,
        messages: List[Dict[str, str]],
        max_tokens: int,
        system: Optional[str] = None,
        temperature: Optional[float] = None,
        session_key: Optional[str] = None,
        **kwargs: Any,
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """Async streaming message creation. Yields Anthropic SSE event objects."""
        body: Dict[str, Any] = {
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "stream": True,
            **kwargs,
        }
        if system:
            body["system"] = system
        if temperature is not None:
            body["temperature"] = temperature

        async for event in async_stream_sse(
            self._cfg,
            "/proxy/anthropic/v1/messages",
            body,
            self._auth_headers(),
            session_key or self._cfg.session_key,
        ):
            yield event


class SpendLilAnthropic:
    """
    Anthropic-compatible client routed through SpendLil.

    Usage::

        sl = SpendLil(agent_id="xxx", base_url="https://spendlil.yourco.com/api")
        anthropic = sl.anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

        response = anthropic.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=1024,
            messages=[{"role": "user", "content": "Hello!"}],
        )
        print(response["content"][0]["text"])
        print(response["_spendlil"].model)
    """

    def __init__(self, cfg: SpendLilConfig, api_key: str):
        self._cfg = cfg
        self._api_key = api_key
        self.messages = _Messages(cfg, api_key)
