"""Provider implementation backed by agno models."""

from __future__ import annotations

from typing import Any

from asedclaw.providers.base import LLMProvider, LLMResponse


class AgnoOpenAILikeProvider(LLMProvider):
    """LLM provider powered by agno.models.openai.OpenAILike."""

    def __init__(
        self,
        api_key: str | None = None,
        api_base: str | None = None,
        default_model: str = "gpt-4o",
        provider_name: str | None = None,
        extra_headers: dict[str, str] | None = None,
    ):
        super().__init__(api_key=api_key, api_base=api_base)
        self.default_model = default_model
        self.provider_name = provider_name
        self.extra_headers = extra_headers or {}

    async def chat(
        self,
        messages: list[dict[str, Any]],
        tools: list[dict[str, Any]] | None = None,
        model: str | None = None,
        max_tokens: int = 4096,
        temperature: float = 0.7,
        reasoning_effort: str | None = None,
    ) -> LLMResponse:
        """
        Compatibility chat entrypoint.

        Runtime path has been migrated to agno Agent directly; this method remains
        for compatibility with legacy callers.
        """
        try:
            from agno.agent.agent import Agent
            from agno.models.openai import OpenAILike
        except Exception as e:
            return LLMResponse(content=f"Error loading agno runtime: {e}", finish_reason="error")

        # Legacy callers pass OpenAI-format messages; we render them into a prompt.
        prompt_parts: list[str] = []
        system_prompt = ""
        for m in messages:
            role = m.get("role", "user")
            content = m.get("content")
            text = content if isinstance(content, str) else str(content)
            if role == "system":
                system_prompt = text
            else:
                prompt_parts.append(f"{role}: {text}")
        prompt = "\n\n".join(prompt_parts) if prompt_parts else ""

        model_kwargs: dict[str, Any] = {"id": model or self.default_model}
        if self.api_key:
            model_kwargs["api_key"] = self.api_key
        if self.api_base:
            model_kwargs["base_url"] = self.api_base
        if temperature is not None:
            model_kwargs["temperature"] = temperature
        if self.extra_headers:
            model_kwargs["request_params"] = {"extra_headers": self.extra_headers}
        if max_tokens:
            model_kwargs.setdefault("request_params", {})["max_tokens"] = max(1, max_tokens)
        if reasoning_effort:
            model_kwargs.setdefault("request_params", {})["reasoning_effort"] = reasoning_effort

        # Tool-calling in provider.chat is deprecated in agno runtime path.
        # Keep parameter for signature compatibility.
        _ = tools

        try:
            agent = Agent(
                model=OpenAILike(**model_kwargs),
                instructions=system_prompt or None,
                stream=False,
            )
            run = await agent.arun(prompt, stream=False)
            content = getattr(run, "content", None)
            if not isinstance(content, str):
                content = str(content or "")
            return LLMResponse(content=content, finish_reason="stop")
        except Exception as e:
            return LLMResponse(content=f"Error calling agno model: {e}", finish_reason="error")

    def get_default_model(self) -> str:
        return self.default_model
