"""
Configuration data models for Elasticsearch MCP.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal


@dataclass
class EnvVars:
    """环境变量引用（敏感信息通过环境变量名引用，不暴露实际值）"""
    hosts: str | None = None
    username: str | None = None
    password: str | None = None

    def resolve(self) -> dict[str, str]:
        """解析环境变量引用，返回变量名映射（不返回实际值）"""
        import os
        resolved = {}
        if self.hosts:
            resolved["hosts"] = os.environ.get(self.hosts, "")
        if self.username:
            resolved["username"] = os.environ.get(self.username, "")
        if self.password:
            resolved["password"] = os.environ.get(self.password, "")
        return resolved

    def has_env_ref(self) -> bool:
        """检查是否配置了环境变量引用"""
        return any([self.hosts, self.username, self.password])


@dataclass
class ConnectionProfile:
    """单条 ES 连接配置"""
    name: str
    env: Literal["test", "uat", "prod"]
    description: str | None = None
    skip_product_check: bool = False
    env_vars: EnvVars = field(default_factory=EnvVars)

    def has_auth(self) -> bool:
        """检查是否配置了认证信息"""
        return bool(self.env_vars.username or self.env_vars.password)


@dataclass
class SafetyConfig:
    """安全与行为配置"""
    read_only: bool = False
    max_search_size: int = 100
    request_timeout: int = 30


@dataclass
class ConnectionConfig:
    """与 client.py 兼容的连接配置"""
    host: str
    port: int
    user: str = ""
    password: str = ""
    use_ssl: bool = False
    description: str | None = None
    skip_product_check: bool = False


@dataclass
class AppConfig:
    """应用完整配置"""
    profiles: list[ConnectionProfile] = field(default_factory=list)
    safety: SafetyConfig = field(default_factory=SafetyConfig)
    has_prompted_setup: bool = False

    def get_profile(self, name: str) -> ConnectionProfile | None:
        """根据名称获取 profile"""
        for p in self.profiles:
            if p.name == name:
                return p
        return None

    def default_profile(self) -> ConnectionProfile | None:
        """获取默认 profile（优先 prod）"""
        for p in self.profiles:
            if p.env == "prod":
                return p
        return self.profiles[0] if self.profiles else None
