"""
Setup helper functions for interactive configuration guidance.
"""
from __future__ import annotations

import re

from ..config import (
    ConnectionProfile,
    EnvVars,
    SafetyConfig,
    SafetyPolicy,
    generate_env_var_commands,
    generate_safety_env_commands,
    need_setup,
    save_profiles,
    save_safety_config,
    load_config,
)


def generate_env_var_names(description: str | None, env_name: str) -> dict:
    """
    根据描述生成推荐的环境变量名。
    """
    clean_desc = re.sub(r'[^a-zA-Z0-9]', '', description or "")
    clean_desc = clean_desc.upper()[:10]

    prefix = f"{env_name.upper()}_{clean_desc}" if clean_desc else env_name.upper()

    return {
        "hosts": f"{prefix}_HOSTS",
        "username": f"{prefix}_USERNAME",
        "password": f"{prefix}_PASSWORD",
    }


def run_setup(
    description: str | None = None,
    env_name: str = "test",
    hosts_env_var: str | None = None,
    username_env_var: str | None = None,
    password_env_var: str | None = None,
    # 基础安全配置
    read_only: bool = False,
    max_search_size: int = 100,
    request_timeout: int = 30,
    # DDL/DML 策略
    allow_search: bool = True,
    allow_index: bool = True,
    allow_update: bool = True,
    allow_delete: bool = True,
    allow_bulk: bool = True,
    allow_create_index: bool = False,
    allow_delete_index: bool = False,
    allow_update_mapping: bool = False,
    allow_cluster: bool = False,
    # 执行确认
    confirm_write: bool = True,
    confirm_delete: bool = True,
    confirm_index: bool = True,
) -> dict:
    """
    执行配置引导。
    """
    # 生成推荐的环境变量名
    recommended = generate_env_var_names(description, env_name)

    # 使用推荐值填充空值
    if not hosts_env_var:
        hosts_env_var = recommended["hosts"]
    if not password_env_var:
        password_env_var = recommended["password"]

    # 验证必填参数
    if not hosts_env_var:
        return {"success": False, "message": "hosts 环境变量名不能为空"}

    if not password_env_var:
        return {"success": False, "message": "password 环境变量名不能为空"}

    # 生成 profile 名称
    profile_name = f"{env_name}-{description.replace(' ', '-').lower() if description else env_name}"

    # 构建 profile
    profile = ConnectionProfile(
        name=profile_name,
        env=env_name,
        description=description,
        skip_product_check=True,
        env_vars=EnvVars(
            hosts=hosts_env_var,
            username=username_env_var,
            password=password_env_var,
        ),
    )

    # 构建安全策略
    policy = SafetyPolicy(
        allow_search=allow_search,
        allow_index=allow_index,
        allow_update=allow_update,
        allow_delete=allow_delete,
        allow_bulk=allow_bulk,
        allow_create_index=allow_create_index,
        allow_delete_index=allow_delete_index,
        allow_update_mapping=allow_update_mapping,
        allow_cluster=allow_cluster,
    )

    # 构建安全配置
    safety = SafetyConfig(
        read_only=read_only,
        max_search_size=max_search_size,
        request_timeout=request_timeout,
        policy=policy,
        confirm_write=confirm_write,
        confirm_delete=confirm_delete,
        confirm_index=confirm_index,
    )

    # 保存配置
    save_profiles([profile], has_prompted_setup=True)
    save_safety_config(safety)

    # 生成环境变量设置命令
    env_commands = generate_env_var_commands(profile)
    safety_commands = generate_safety_env_commands(safety)

    # 构建策略信息
    policy_info = []
    policy_info.append(f"  允许 search: {'是' if allow_search else '否'}")
    policy_info.append(f"  允许 index/create 文档: {'是' if allow_index else '否'}")
    policy_info.append(f"  允许 update 文档: {'是' if allow_update else '否'}")
    policy_info.append(f"  允许 delete 文档: {'是' if allow_delete else '否'}")
    policy_info.append(f"  允许 bulk 操作: {'是' if allow_bulk else '否'}")
    policy_info.append(f"  允许创建索引: {'是' if allow_create_index else '否'}")
    policy_info.append(f"  允许删除索引: {'是' if allow_delete_index else '否'}")
    policy_info.append(f"  允许修改 mapping: {'是' if allow_update_mapping else '否'}")
    policy_info.append(f"  允许集群操作: {'是' if allow_cluster else '否'}")

    confirm_info = []
    confirm_info.append(f"  写操作需确认: {'是' if confirm_write else '否'}")
    confirm_info.append(f"  删除操作需确认: {'是' if confirm_delete else '否'}")
    confirm_info.append(f"  创建索引需确认: {'是' if confirm_index else '否'}")

    message = f"""配置已保存到 profiles.json

Profile: {profile_name}
描述: {description or '无'}
环境: {env_name}

=== 基础配置 ===
只读模式: {read_only}
最大搜索条数: {max_search_size}
请求超时: {request_timeout}秒

=== DDL/DML 策略 ===
{chr(10).join(policy_info)}

=== 执行确认 ===
{chr(10).join(confirm_info)}

=== 推荐的环境变量名 ===
hosts: {recommended['hosts']}
username: {recommended.get('username', '(可选)')}
password: {recommended['password']}

请在您的 shell 配置文件中添加以下环境变量并填入实际值：

┌────────────────────────────────────────────────────────┐
│  # Elasticsearch MCP - {env_name} 环境配置                 │
│                                                        │
│  # 连接配置                                              │
│  {env_commands}
│                                                        │
│  # 安全配置                                              │
│  {safety_commands}
│                                                        │
│  # 配置完成后请运行: source ~/.zshrc (或对应配置文件)      │
└────────────────────────────────────────────────────────┘
"""

    return {
        "success": True,
        "message": message,
        "profile_name": profile_name,
        "recommended_env_vars": recommended,
    }


def do_check_setup_status() -> dict:
    """检查当前配置状态。"""
    config = load_config()
    p = config.safety.policy

    return {
        "need_setup": need_setup(),
        "profiles_count": len(config.profiles),
        "has_prompted_setup": config.has_prompted_setup,
        "safety": {
            "read_only": config.safety.read_only,
            "max_search_size": config.safety.max_search_size,
            "request_timeout": config.safety.request_timeout,
            "confirm_write": config.safety.confirm_write,
            "confirm_delete": config.safety.confirm_delete,
            "confirm_index": config.safety.confirm_index,
            "policy": {
                "allow_search": p.allow_search,
                "allow_index": p.allow_index,
                "allow_update": p.allow_update,
                "allow_delete": p.allow_delete,
                "allow_bulk": p.allow_bulk,
                "allow_create_index": p.allow_create_index,
                "allow_delete_index": p.allow_delete_index,
                "allow_update_mapping": p.allow_update_mapping,
                "allow_cluster": p.allow_cluster,
            },
        },
    }
