"""SSH MCP Server CLI 入口

命令:
  sshmcp                    以 MCP Server 模式运行 (stdio)
  sshgui                    启动 GUI 配置面板
  sshmcp-install            安装到所有已知 IDE
  sshmcp-install-windsurf   安装到 Windsurf
  sshmcp-install-cursor     安装到 Cursor
  sshmcp-install-claudecode 安装到 Claude Code
  sshmcp-install-codex      安装到 Codex
"""
import json
import os
import shutil
import sys
import asyncio
import logging

# ─── IDE 配置文件路径 ────────────────────────────────────────
IDE_CONFIGS = {
    "Windsurf":    os.path.join(os.path.expanduser("~"), ".codeium", "windsurf", "mcp_config.json"),
    "Cursor":      os.path.join(os.path.expanduser("~"), ".cursor", "mcp.json"),
    "Claude Code": os.path.join(os.path.expanduser("~"), ".claude.json"),
    "Codex":       os.path.join(os.path.expanduser("~"), ".codex", "config.toml"),
}


def get_mcp_command() -> str:
    """获取 MCP 启动命令"""
    if shutil.which("sshmcp"):
        return "sshmcp"
    if getattr(sys, "frozen", False):
        return os.path.abspath(sys.executable)
    return "sshmcp"


def install_to_ide(ide_name: str) -> bool:
    """安装 MCP 配置到指定 IDE，返回是否成功"""
    config_path = IDE_CONFIGS.get(ide_name)
    if not config_path:
        print(f"[sshmcp] 未知 IDE: {ide_name}")
        return False

    if ide_name == "Codex":
        return _install_codex_toml(config_path)
    return _install_json_ide(ide_name, config_path)


def _install_json_ide(ide_name: str, config_path: str) -> bool:
    """安装到使用 JSON 配置的 IDE（Windsurf/Cursor/Claude Code）"""
    command = get_mcp_command()

    # 读取已有配置
    existing = {}
    if os.path.exists(config_path):
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                existing = json.load(f)
        except (json.JSONDecodeError, OSError):
            pass

    # 写入配置
    if "mcpServers" not in existing:
        existing["mcpServers"] = {}

    already = "ssh" in existing.get("mcpServers", {})
    existing["mcpServers"]["ssh"] = {"command": command}

    os.makedirs(os.path.dirname(config_path), exist_ok=True)
    try:
        with open(config_path, "w", encoding="utf-8") as f:
            json.dump(existing, f, indent=2, ensure_ascii=False)
    except OSError as e:
        print(f"[sshmcp] 写入失败: {e}")
        return False

    action = "更新" if already else "安装"
    print(f"[sshmcp] 已{action}到 {ide_name}")
    print(f"  配置文件: {config_path}")
    print(f"  命令: {command}")
    print(f"  重启 {ide_name} 即可使用。")
    return True


def _install_codex_toml(config_path: str) -> bool:
    """安装到 Codex（TOML 格式 config.toml）"""
    command = get_mcp_command()

    # 读取已有内容
    content = ""
    if os.path.exists(config_path):
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                content = f.read()
        except OSError:
            pass

    already = "[mcp_servers.ssh]" in content

    # 构建要追加的 TOML 块
    toml_block = f'\n[mcp_servers.ssh]\ncommand = "{command}"\nstartup_timeout_sec = 60\n'

    if already:
        # 替换已有的 [mcp_servers.ssh] 块
        import re
        content = re.sub(
            r'\[mcp_servers\.ssh\][^\[]*',
            f'[mcp_servers.ssh]\ncommand = "{command}"\nstartup_timeout_sec = 60\n\n',
            content,
        )
    else:
        content = content.rstrip() + "\n" + toml_block

    os.makedirs(os.path.dirname(config_path), exist_ok=True)
    try:
        with open(config_path, "w", encoding="utf-8") as f:
            f.write(content)
    except OSError as e:
        print(f"[sshmcp] 写入失败: {e}")
        return False

    action = "更新" if already else "安装"
    print(f"[sshmcp] 已{action}到 Codex")
    print(f"  配置文件: {config_path}")
    print(f"  命令: {command}")
    print(f"  重启 Codex 即可使用。")
    return True


# ─── 入口函数 ────────────────────────────────────────────────

def main():
    if "--gui" in sys.argv:
        _run_gui()
    elif getattr(sys, "frozen", False):
        _run_gui()
    else:
        _run_mcp()


def _run_gui():
    from .config import ConfigManager
    from .ssh_manager import SSHManager
    from .gui import MainWindow

    config_manager = ConfigManager()
    ssh_manager = SSHManager(config_manager)
    window = MainWindow(config_manager, ssh_manager)
    window.run()


def _configure_mcp_logging():
    log_file = os.getenv("SSHMCP_LOG_FILE")
    if not log_file:
        logging.disable(logging.CRITICAL)
        root_logger = logging.getLogger()
        root_logger.handlers.clear()
        root_logger.addHandler(logging.NullHandler())
        return

    logging.disable(logging.NOTSET)
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        handlers=[logging.FileHandler(log_file, encoding="utf-8")],
        force=True,
    )


def _run_mcp():
    _configure_mcp_logging()

    from .config import ConfigManager
    from .ssh_manager import SSHManager
    from .mcp_server import run_mcp_server

    config_manager = ConfigManager()
    ssh_manager = SSHManager(config_manager)
    asyncio.run(run_mcp_server(config_manager, ssh_manager))


# ─── 一键安装命令 ─────────────────────────────────────────────

def install_all():
    """安装到所有 IDE"""
    print("[sshmcp] 正在安装到所有 IDE...\n")
    for ide_name in IDE_CONFIGS:
        install_to_ide(ide_name)
        print()
    print("[sshmcp] 全部完成！")


def install_windsurf():
    install_to_ide("Windsurf")


def install_cursor():
    install_to_ide("Cursor")


def install_claudecode():
    install_to_ide("Claude Code")


def install_codex():
    install_to_ide("Codex")
