"""
Configuration management for the Voice Agent.

This module provides centralized configuration loading from environment variables,
logging setup, and validation of required settings.
"""

import logging
import os
from dataclasses import dataclass


@dataclass
class AgentConfig:
    """
    Configuration for the Voice Agent.

    All settings are loaded from environment variables with validation.
    """

    # LiveKit connection settings
    livekit_url: str
    livekit_api_key: str
    livekit_api_secret: str

    # API keys for services
    deepgram_api_key: str
    openai_api_key: str

    # Optional LiveKit settings
    livekit_room_name: str | None = None

    # Agent behavior settings
    initial_greeting: str = (
        "Hello! I'm your AI voice assistant. "
        "I'm here to help you navigate through the presentation. "
        "Feel free to ask me questions or request to move to different slides."
    )

    # Model configuration
    tts_model: str = "cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"  # British Lady voice
    stt_model: str = "base"  # Deepgram base model (cheapest)
    llm_model: str = "gpt-4o-mini"  # Fast and cost-effective

    # Logging configuration
    log_level: str = "INFO"

    @classmethod
    def from_env(cls) -> "AgentConfig":
        """
        Load configuration from environment variables.

        Returns:
            AgentConfig: Configuration instance with values from environment

        Raises:
            ValueError: If required environment variables are missing
        """
        # Required environment variables
        required_vars = {
            "LIVEKIT_URL": "livekit_url",
            "LIVEKIT_API_KEY": "livekit_api_key",
            "LIVEKIT_API_SECRET": "livekit_api_secret",
            "DEEPGRAM_API_KEY": "deepgram_api_key",
            "OPENAI_API_KEY": "openai_api_key",
        }

        # Check for missing required variables
        missing_vars = [
            env_var for env_var in required_vars
            if not os.environ.get(env_var)
        ]

        if missing_vars:
            raise ValueError(
                f"Missing required environment variables: {', '.join(missing_vars)}"
            )

        # Optional environment variables with defaults
        return cls(
            livekit_url=os.environ["LIVEKIT_URL"],
            livekit_api_key=os.environ["LIVEKIT_API_KEY"],
            livekit_api_secret=os.environ["LIVEKIT_API_SECRET"],
            livekit_room_name=os.environ.get("LIVEKIT_ROOM_NAME"),
            deepgram_api_key=os.environ["DEEPGRAM_API_KEY"],
            openai_api_key=os.environ["OPENAI_API_KEY"],
            initial_greeting=os.environ.get(
                "AGENT_INITIAL_GREETING",
                cls.__dataclass_fields__["initial_greeting"].default
            ),
            tts_model=os.environ.get(
                "AGENT_TTS_MODEL",
                cls.__dataclass_fields__["tts_model"].default
            ),
            stt_model=os.environ.get(
                "AGENT_STT_MODEL",
                cls.__dataclass_fields__["stt_model"].default
            ),
            llm_model=os.environ.get(
                "AGENT_LLM_MODEL",
                cls.__dataclass_fields__["llm_model"].default
            ),
            log_level=os.environ.get(
                "AGENT_LOG_LEVEL",
                cls.__dataclass_fields__["log_level"].default
            ),
        )

    def validate(self) -> None:
        """
        Validate configuration values.

        Raises:
            ValueError: If configuration values are invalid
        """
        # Validate URLs
        if not self.livekit_url.startswith(("ws://", "wss://")):
            raise ValueError(
                f"Invalid LIVEKIT_URL: must start with ws:// or wss://, got {self.livekit_url}"
            )

        # Validate log level
        valid_log_levels = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
        if self.log_level.upper() not in valid_log_levels:
            raise ValueError(
                f"Invalid log level: {self.log_level}. Must be one of {valid_log_levels}"
            )


def setup_logging(config: AgentConfig) -> logging.Logger:
    """
    Configure logging for the agent.

    Args:
        config: Agent configuration containing log level

    Returns:
        logging.Logger: Configured logger instance
    """
    # Configure root logger
    logging.basicConfig(
        level=getattr(logging, config.log_level.upper()),
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    # Create and return logger for this module
    logger = logging.getLogger("voice_agent_livekit")
    logger.info(f"Logging configured at {config.log_level} level")

    return logger


def get_config() -> AgentConfig:
    """
    Get validated configuration from environment.

    This is the main entry point for configuration loading.

    Returns:
        AgentConfig: Validated configuration instance

    Raises:
        ValueError: If configuration is invalid or required variables are missing
    """
    config = AgentConfig.from_env()
    config.validate()
    return config
