from __future__ import annotations
from typing import Any, List

from .base import ProviderConfig, LLMMessage, LLMResponse

class AnthropicProvider:
    """Anthropic Provider (real implementation) using official `anthropic` SDK."""
    def __init__(self, config: ProviderConfig):
        self.config = config
        try:
            from anthropic import AsyncAnthropic  # type: ignore
        except Exception as e:  # pragma: no cover
            raise RuntimeError("Install provider extra: pip install adi-agentic-agi[anthropic]") from e

        kwargs: dict[str, Any] = {}
        if config.api_key:
            kwargs["api_key"] = config.api_key
        if config.base_url:
            kwargs["base_url"] = config.base_url
        self._client = AsyncAnthropic(**kwargs)

    @staticmethod
    def _system_and_messages(messages: List[LLMMessage]) -> tuple[str, list[dict[str, str]]]:
        system_parts = [m.content for m in messages if m.role == "system" and m.content]
        user_msgs: list[dict[str, str]] = []
        for m in messages:
            if m.role in {"user", "assistant"} and m.content:
                user_msgs.append({"role": m.role, "content": m.content})
        system = "\n\n".join(system_parts).strip()
        return system, user_msgs

    async def generate(self, messages: List[LLMMessage], **kwargs: Any) -> LLMResponse:
        system, msgs = self._system_and_messages(messages)
        max_tokens = int(kwargs.pop("max_tokens", self.config.extra.get("max_tokens", 1024)))
        resp = await self._client.messages.create(
            model=self.config.model,
            system=system or None,
            messages=msgs,
            max_tokens=max_tokens,
            **kwargs,
        )
        # resp.content is list of blocks; take text blocks
        parts = []
        for block in getattr(resp, "content", []) or []:
            txt = getattr(block, "text", None)
            if txt:
                parts.append(txt)
        return LLMResponse(text="\n".join(parts).strip(), raw={"id": getattr(resp, "id", None)})
