import os
from typing import List, Dict, Optional
from .providers.base import BaseProvider


PROVIDER_MAP = {
    "groq": ("synapse.providers.groq", "GroqProvider"),
    "openai": ("synapse.providers.openai", "OpenAIProvider"),
    "anthropic": ("synapse.providers.anthropic", "AnthropicProvider"),
    "gemini": ("synapse.providers.gemini", "GeminiProvider"),
}

DEFAULT_MODELS = {
    "groq": "llama-3.3-70b-versatile",
    "openai": "gpt-4o",
    "anthropic": "claude-sonnet-4-20250514",
    "gemini": "gemini-1.5-flash",
}

API_KEY_ENV = {
    "groq": "GROQ_API_KEY",
    "openai": "OPENAI_API_KEY",
    "anthropic": "ANTHROPIC_API_KEY",
    "gemini": "GEMINI_API_KEY",
}


class Agent:
    """
    Represents a single AI agent backed by any LLM provider.

    Usage:
        agent = Agent("researcher", provider="groq", model="llama-3.3-70b-versatile")
        agent = Agent("writer", provider="openai")  # uses default model
        agent = Agent("analyst", provider="groq", api_key="gsk_...")  # explicit key
    """

    def __init__(
        self,
        name: str,
        provider: str = "groq",
        model: Optional[str] = None,
        api_key: Optional[str] = None,
        system_prompt: Optional[str] = None,
    ):
        self.name = name
        self.provider_name = provider.lower()
        self.model = model or DEFAULT_MODELS.get(self.provider_name, "")
        self.system_prompt = system_prompt or f"You are {name}, a helpful AI agent in the Synapse multi-agent system."

        # Resolve API key: explicit > env var
        env_key = API_KEY_ENV.get(self.provider_name, "")
        self.api_key = api_key or os.getenv(env_key, "")

        if not self.api_key:
            raise ValueError(
                f"No API key for provider '{self.provider_name}'. "
                f"Pass api_key= or set {env_key} environment variable."
            )

        self._provider = self._load_provider()

    def _load_provider(self) -> BaseProvider:
        if self.provider_name not in PROVIDER_MAP:
            raise ValueError(
                f"Unknown provider '{self.provider_name}'. "
                f"Choose from: {list(PROVIDER_MAP.keys())}"
            )
        module_path, class_name = PROVIDER_MAP[self.provider_name]
        import importlib
        module = importlib.import_module(module_path)
        cls = getattr(module, class_name)
        return cls(api_key=self.api_key, model=self.model)

    def complete(self, messages: List[Dict]) -> str:
        """Send messages to this agent and get a response."""
        return self._provider.complete(messages, system_prompt=self.system_prompt)

    def __repr__(self):
        return f"Agent(name={self.name!r}, provider={self.provider_name!r}, model={self.model!r})"
