"""Global settings for the meeting system."""

import os
from dataclasses import dataclass, field
from typing import Optional

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI

# Load environment variables from .env file
load_dotenv()


def _get_env(key: str, default: str = "") -> str:
    """Get environment variable with default value."""
    return os.getenv(key, default)


def _get_env_bool(key: str, default: bool = False) -> bool:
    """Get boolean environment variable."""
    value = os.getenv(key, "").lower()
    if not value:
        return default
    return value in ("true", "1", "yes", "on")


def _get_env_int(key: str, default: int) -> int:
    """Get integer environment variable."""
    value = os.getenv(key, "")
    if not value:
        return default
    try:
        return int(value)
    except ValueError:
        return default


def _get_env_float(key: str, default: float) -> float:
    """Get float environment variable."""
    value = os.getenv(key, "")
    if not value:
        return default
    try:
        return float(value)
    except ValueError:
        return default


@dataclass
class LLMSettings:
    """LLM configuration."""

    provider: str = field(default_factory=lambda: _get_env("LLM_PROVIDER", "openrouter"))
    model: str = field(default_factory=lambda: _get_env("LLM_MODEL", "openai/gpt-4o-mini"))
    fast_model: str = field(default_factory=lambda: _get_env("LLM_FAST_MODEL", "openai/gpt-4o-mini"))

    # OpenRouter settings
    openrouter_api_key: Optional[str] = field(
        default_factory=lambda: _get_env("OPENROUTER_API_KEY") or None
    )
    openrouter_url: str = field(
        default_factory=lambda: _get_env("OPENROUTER_URL", "https://openrouter.ai/api/v1")
    )

    # Ollama settings
    ollama_url: str = field(
        default_factory=lambda: _get_env("OLLAMA_URL", "http://localhost:11434")
    )

    # Common settings
    timeout: int = field(default_factory=lambda: _get_env_int("LLM_TIMEOUT", 60))
    temperature: float = field(default_factory=lambda: _get_env_float("LLM_TEMPERATURE", 0.1))
    language: str = field(default_factory=lambda: _get_env("LLM_LANGUAGE", "ko"))  # "ko" or "en"


@dataclass
class MeetingSettings:
    """Meeting configuration."""

    max_duration: int = field(
        default_factory=lambda: _get_env_int("MEETING_MAX_DURATION", 3600)
    )
    default_agenda_time: int = field(
        default_factory=lambda: _get_env_int("MEETING_DEFAULT_AGENDA_TIME", 300)
    )
    off_topic_threshold: int = field(
        default_factory=lambda: _get_env_int("MEETING_OFF_TOPIC_THRESHOLD", 3)
    )
    min_participants: int = 2
    max_participants: int = 10


@dataclass
class WorktreeSettings:
    """Worktree configuration."""

    max_concurrent: int = 3
    timeout: int = 1800  # seconds (30 minutes)
    auto_report_interval: int = 300  # seconds (5 minutes)


@dataclass
class MCPSettings:
    """MCP tool configuration."""

    jira_enabled: bool = field(
        default_factory=lambda: _get_env_bool("MCP_JIRA_ENABLED", False)
    )
    jira_url: Optional[str] = field(
        default_factory=lambda: _get_env("MCP_JIRA_URL") or None
    )
    jira_token: Optional[str] = field(
        default_factory=lambda: _get_env("MCP_JIRA_TOKEN") or None
    )

    github_enabled: bool = field(
        default_factory=lambda: _get_env_bool("MCP_GITHUB_ENABLED", False)
    )
    github_token: Optional[str] = field(
        default_factory=lambda: _get_env("MCP_GITHUB_TOKEN") or None
    )

    calendar_enabled: bool = field(
        default_factory=lambda: _get_env_bool("MCP_CALENDAR_ENABLED", False)
    )


@dataclass
class Settings:
    """Global application settings."""

    llm: LLMSettings = field(default_factory=LLMSettings)
    meeting: MeetingSettings = field(default_factory=MeetingSettings)
    worktree: WorktreeSettings = field(default_factory=WorktreeSettings)
    mcp: MCPSettings = field(default_factory=MCPSettings)

    # Debug settings
    debug: bool = field(default_factory=lambda: _get_env_bool("DEBUG", False))
    verbose: bool = field(default_factory=lambda: _get_env_bool("VERBOSE", False))

    def create_fast_llm(self) -> ChatOpenAI:
        """고속 작업용 fast LLM 인스턴스 생성."""
        return ChatOpenAI(
            model=self.llm.fast_model,
            temperature=0.0,  # 안건 추출은 결정적이어야 함
            openai_api_key=self.llm.openrouter_api_key or "dummy",
            openai_api_base=self.llm.openrouter_url
        )


# Global settings instance
settings = Settings()
