"""Application configuration."""

import json
from typing import Any

from pydantic import Field, field_validator
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """Application settings loaded from environment variables."""

    # API Keys
    openai_api_key: str = ""
    anthropic_api_key: str = ""

    # Database
    database_url: str = "postgresql://localhost:5432/myapp"

    # Supabase
    supabase_url: str = ""
    supabase_anon_key: str = ""
    supabase_service_key: str = ""

    # Redis
    redis_url: str = "redis://localhost:6379"
    redis_enabled: bool = False  # Enable Redis for distributed rate limiting

    # Search
    search_api_key: str = ""

    # Application
    debug: bool = False
    log_level: str = "INFO"

    # Security
    secret_key: str = "change-me-in-production"  # For JWT/auth token validation

    # Rate Limiting
    rate_limit_requests_per_minute: int = 60
    rate_limit_burst_size: int = 10

    # MCP Servers - Platform-wide MCP servers available to all agents
    # JSON array of server configs, e.g.:
    # [
    #   {"type": "stdio", "command": "uvx", "args": ["mcp-server-time"], "prefix": "time"},
    #   {"type": "sse", "url": "http://localhost:3001/sse", "prefix": "weather"},
    #   {"type": "http", "url": "http://localhost:8080/mcp", "prefix": "data"}
    # ]
    mcp_servers: list[dict[str, Any]] = Field(default_factory=list)

    @field_validator("mcp_servers", mode="before")
    @classmethod
    def parse_mcp_servers(cls, v: Any) -> list[dict[str, Any]]:
        """Parse MCP_SERVERS from JSON string or list."""
        if isinstance(v, str):
            if not v.strip():
                return []
            try:
                return json.loads(v)
            except json.JSONDecodeError:
                return []
        return v or []

    model_config = {"env_file": ".env", "env_file_encoding": "utf-8", "extra": "ignore"}


settings = Settings()
