# -*- coding: utf-8 -*-
"""
Claude Code CLI Installer

自動檢測並安裝 Claude Code CLI：
- Windows: irm https://claude.ai/install.ps1 | iex
- Linux/macOS: curl -fsSL https://claude.ai/install.sh | bash
"""

import platform
import shutil
import subprocess
import sys

from .logging_config import get_logger

logger = get_logger("claude_code_installer")


def is_claude_code_installed() -> bool:
    """檢查 Claude Code CLI 是否已安裝"""
    return shutil.which("claude") is not None


def get_install_command() -> tuple[str, list[str]]:
    """
    根據作業系統返回安裝指令

    Returns:
        tuple: (shell, command_args)
    """
    system = platform.system().lower()

    if system == "windows":
        # PowerShell command
        return ("powershell", [
            "-ExecutionPolicy", "Bypass",
            "-Command",
            "irm https://claude.ai/install.ps1 | iex"
        ])
    else:
        # Linux / macOS - use bash
        return ("bash", [
            "-c",
            "curl -fsSL https://claude.ai/install.sh | bash"
        ])


def install_claude_code(silent: bool = False) -> bool:
    """
    安裝 Claude Code CLI

    Args:
        silent: 是否靜默安裝（不顯示輸出）

    Returns:
        bool: 是否安裝成功
    """
    system = platform.system().lower()

    if not silent:
        print()
        print("=" * 60)
        print("🔧 安裝 Claude Code CLI")
        print("=" * 60)
        print()
        print(f"   作業系統: {platform.system()}")
        print()

    shell, args = get_install_command()

    try:
        if not silent:
            print("   正在下載並安裝...")
            print()

        # 執行安裝指令
        result = subprocess.run(
            [shell] + args,
            capture_output=silent,
            text=True,
            timeout=300  # 5 分鐘超時
        )

        if result.returncode == 0:
            # 驗證安裝
            if is_claude_code_installed():
                if not silent:
                    print()
                    print("=" * 60)
                    print("✅ Claude Code CLI 安裝成功！")
                    print("=" * 60)
                    print()
                logger.info("Claude Code CLI installed successfully")
                return True
            else:
                if not silent:
                    print()
                    print("⚠️  安裝完成但找不到 claude 指令")
                    print("   請重新開啟終端機後再試")
                    print()
                logger.warning("Claude Code installed but not found in PATH")
                return False
        else:
            if not silent:
                print()
                print(f"❌ 安裝失敗 (exit code: {result.returncode})")
                if result.stderr:
                    print(f"   錯誤: {result.stderr}")
                print()
            logger.error(f"Claude Code installation failed: {result.stderr}")
            return False

    except subprocess.TimeoutExpired:
        if not silent:
            print()
            print("❌ 安裝超時")
            print()
        logger.error("Claude Code installation timed out")
        return False
    except FileNotFoundError as e:
        if not silent:
            print()
            print(f"❌ 找不到 {shell}: {e}")
            print()
        logger.error(f"Shell not found: {e}")
        return False
    except Exception as e:
        if not silent:
            print()
            print(f"❌ 安裝過程發生錯誤: {e}")
            print()
        logger.error(f"Claude Code installation error: {e}")
        return False


def ensure_claude_code_installed(auto_install: bool = True) -> bool:
    """
    確保 Claude Code CLI 已安裝

    Args:
        auto_install: 是否自動安裝（否則只提示）

    Returns:
        bool: Claude Code 是否可用
    """
    if is_claude_code_installed():
        logger.debug("Claude Code CLI is already installed")
        return True

    print()
    print("⚠️  FWAuto 需要 Claude Code CLI 才能使用 AI 功能")
    print()

    if auto_install:
        try:
            # 詢問用戶是否要安裝
            response = input("   是否現在安裝 Claude Code CLI？ [Y/n]: ").strip().lower()

            if response in ("", "y", "yes"):
                return install_claude_code(silent=False)
            else:
                _print_manual_install_instructions()
                return False
        except (KeyboardInterrupt, EOFError):
            print("\n   已取消")
            return False
    else:
        _print_manual_install_instructions()
        return False


def _print_manual_install_instructions():
    """顯示手動安裝指令"""
    system = platform.system().lower()

    print()
    print("   請手動安裝 Claude Code CLI：")
    print()

    if system == "windows":
        print("   Windows (PowerShell):")
        print("   irm https://claude.ai/install.ps1 | iex")
    else:
        print("   Linux / macOS:")
        print("   curl -fsSL https://claude.ai/install.sh | bash")

    print()
    print("   更多資訊: https://claude.ai/code")
    print()
