"""
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 has_any(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 SafetyPolicy:
    """安全策略配置 - DDL/DML 限制"""
    # 允许的操作
    allow_search: bool = True           # 允许 search 查询
    allow_index: bool = True            # 允许 index/create 文档
    allow_update: bool = True           # 允许 update 文档
    allow_delete: bool = True            # 允许 delete 文档
    allow_bulk: bool = True             # 允许 bulk 操作
    allow_create_index: bool = False    # 允许创建索引
    allow_delete_index: bool = False    # 允许删除索引
    allow_update_mapping: bool = False  # 允许修改 mapping
    allow_cluster: bool = False        # 允许集群操作

    # 危险操作黑名单（路径模式）
    danger_path_patterns: list[str] = field(default_factory=lambda: [
        "/_cluster",
        "/_nodes",
        "/_snapshot",
        "/_close",
        "/_open",
    ])


@dataclass
class SafetyConfig:
    """安全与行为配置"""
    # 基础配置
    read_only: bool = False                    # 只读模式
    max_search_size: int = 100                # 最大搜索条数
    request_timeout: int = 30                 # 请求超时（秒）

    # DDL/DML 策略
    policy: SafetyPolicy = field(default_factory=SafetyPolicy)

    # 执行控制
    confirm_write: bool = True                # 写操作需要确认
    confirm_delete: bool = True               # 删除操作需要确认
    confirm_index: bool = True               # 创建索引需要确认


@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:
        for p in self.profiles:
            if p.name == name:
                return p
        return None

    def default_profile(self) -> ConnectionProfile | None:
        for p in self.profiles:
            if p.env == "prod":
                return p
        return self.profiles[0] if self.profiles else None
