"""配置加载."""
from __future__ import annotations

import json
import os
import sys
from pathlib import Path
from typing import Optional

from ..models import ConnectionConfig, EsVersionInfo, ProfileData, SafetyConfig


# ============== 路径配置 ==============

def _get_config_dir() -> Path:
    """获取配置目录."""
    xdg = os.environ.get("XDG_CONFIG_HOME")
    if xdg:
        return Path(xdg) / "elasticsearch-client-mcp"
    return Path.home() / ".config" / "elasticsearch-client-mcp"


PROFILE_FILE = _get_config_dir() / "profile.json"

# 默认 profile.json 模板路径（用于创建初始配置）
DEFAULT_PROFILE_TEMPLATE = Path(__file__).parent.parent.parent / "config" / "profile_template.json"


# ============== 加载连接配置（从环境变量） ==============

ES_CONNECTIONS_HELP = """
ES_CONNECTIONS 配置模板 (添加到 ~/.claude/settings.json 的 mcpServers 中):

{
  "mcpServers": {
    "elasticsearch-client": {
      "command": "uvx",
      "args": ["elasticsearch-client-mcp-py"],
      "env": {
        "ES_CONNECTIONS": "[{\\"name\\":\\"your_name\\",\\"env\\":\\"prod\\",\\"url\\":\\"http://your-es:9200\\",\\"username\\":\\"elastic\\",\\"password\\":\\"your_password\\"}]"
      },
      "type": "stdio"
    }
  }
}
"""


def load_connections() -> list[ConnectionConfig]:
    """从 ES_CONNECTIONS 环境变量加载连接配置."""
    env_connections = os.environ.get("ES_CONNECTIONS", "")

    if not env_connections:
        print("错误: ES_CONNECTIONS 环境变量未设置", file=sys.stderr)
        print(ES_CONNECTIONS_HELP, file=sys.stderr)
        print("权限配置: ~/.config/elasticsearch-client-mcp/profile.json", file=sys.stderr)
        sys.exit(1)

    try:
        connections_data = json.loads(env_connections)
    except json.JSONDecodeError as e:
        print(f"错误: ES_CONNECTIONS JSON 解析失败: {e}", file=sys.stderr)
        print(ES_CONNECTIONS_HELP, file=sys.stderr)
        sys.exit(1)

    if not connections_data:
        print("错误: ES_CONNECTIONS 中没有配置任何连接", file=sys.stderr)
        print(ES_CONNECTIONS_HELP, file=sys.stderr)
        sys.exit(1)

    connections = []
    for item in connections_data:
        # 安全配置：优先使用内联的 safety，否则为 None（后续从 profile 加载）
        safety = None
        if "safety" in item:
            safety_data = item["safety"]
            safety = SafetyConfig(
                read_only=safety_data.get("read_only", False),
                max_search_size=safety_data.get("max_search_size", 100),
                confirm_delete=safety_data.get("confirm_delete", True),
                allow_delete_index=safety_data.get("allow_delete_index", False),
                allow_create_index=safety_data.get("allow_create_index", False),
                risk_check=safety_data.get("risk_check", True),
            )

        conn = ConnectionConfig(
            name=str(item["name"]),
            env=str(item["env"]),
            description=item.get("description"),
            url=str(item.get("url", "")),
            username=str(item.get("username", "")),
            password=str(item.get("password", "")),
        )
        connections.append(conn)

    return connections


def get_connection_safety(conn: ConnectionConfig) -> SafetyConfig:
    """获取连接的安全配置.

    优先级：
    1. 连接内联的 safety（已解析）
    2. profile.json 中对应 env 的 safety
    """
    # 先检查 profile 中的 safety
    profile = load_profile()
    env_data = profile.envs.get(conn.env, {})
    safety_data = env_data.get("safety", {})

    return SafetyConfig(
        read_only=safety_data.get("read_only", False),
        max_search_size=safety_data.get("max_search_size", 100),
        confirm_delete=safety_data.get("confirm_delete", True),
        allow_delete_index=safety_data.get("allow_delete_index", False),
        allow_create_index=safety_data.get("allow_create_index", False),
        risk_check=safety_data.get("risk_check", True),
    )


# ============== Profile 操作 ==============

def load_profile() -> ProfileData:
    """从 profile.json 加载 profile 数据."""
    if not PROFILE_FILE.exists():
        # 如果 profile.json 不存在，尝试从模板创建
        if DEFAULT_PROFILE_TEMPLATE.exists():
            _get_config_dir().mkdir(parents=True, exist_ok=True)
            with open(DEFAULT_PROFILE_TEMPLATE, "r", encoding="utf-8") as f:
                template_data = json.load(f)
            with open(PROFILE_FILE, "w", encoding="utf-8") as f:
                json.dump(template_data, f, indent=2, ensure_ascii=False)
        else:
            return ProfileData()

    with open(PROFILE_FILE, "r", encoding="utf-8") as f:
        data = json.load(f)

    profile = ProfileData()
    profile.last_connection = data.get("_last_connection")

    # 加载连接缓存的版本信息
    for name, conn_data in data.get("_connection_cache", {}).items():
        profile.connections[name] = conn_data

    # 加载环境配置（safety 等）
    for env_name, env_data in data.get("_envs", {}).items():
        profile.envs[env_name] = env_data

    return profile


def save_profile(profile: ProfileData) -> None:
    """保存 profile 数据到 profile.json."""
    _get_config_dir().mkdir(parents=True, exist_ok=True)

    data = {
        "_last_connection": profile.last_connection,
        "_connection_cache": profile.connections,
        "_envs": profile.envs,
    }

    with open(PROFILE_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def load_safety(env: str) -> SafetyConfig:
    """加载指定环境的安全配置."""
    profile = load_profile()

    env_data = profile.envs.get(env, {})
    safety_data = env_data.get("safety", {})

    return SafetyConfig(
        read_only=safety_data.get("read_only", False),
        max_search_size=safety_data.get("max_search_size", 100),
        confirm_delete=safety_data.get("confirm_delete", True),
        allow_delete_index=safety_data.get("allow_delete_index", False),
        allow_create_index=safety_data.get("allow_create_index", False),
        risk_check=safety_data.get("risk_check", True),
    )


def update_profile_connection_version(connection_name: str, es_version_info: EsVersionInfo) -> None:
    """更新连接的版本缓存."""
    profile = load_profile()

    if connection_name not in profile.connections:
        profile.connections[connection_name] = {}

    profile.connections[connection_name] = {
        "es_version": es_version_info.major,
        "es_version_info": [es_version_info.major, es_version_info.minor, es_version_info.patch],
    }

    save_profile(profile)


def update_profile_last_connection(connection_name: str) -> None:
    """更新上次使用的连接."""
    profile = load_profile()
    profile.last_connection = connection_name
    save_profile(profile)


def get_cached_es_version(connection_name: str) -> Optional[EsVersionInfo]:
    """获取缓存的 ES 版本信息."""
    profile = load_profile()
    conn_data = profile.connections.get(connection_name, {})
    version_info = conn_data.get("es_version_info")
    if version_info and len(version_info) >= 3:
        return EsVersionInfo(
            major=version_info[0],
            minor=version_info[1],
            patch=version_info[2],
        )
    return None
