"""
安装向导 - 自动检测依赖和引导配置
"""
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional, Tuple


def check_playwright() -> Tuple[bool, str]:
    """检查 Playwright 浏览器是否已安装"""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True)
            browser.close()
        return True, "Playwright 浏览器已安装"
    except Exception as e:
        error_msg = str(e).lower()
        if "executable doesn't exist" in error_msg or "browser" in error_msg:
            return False, "Playwright 浏览器未安装"
        return False, f"Playwright 检查失败: {e}"


def install_playwright() -> bool:
    """自动安装 Playwright 浏览器 - 支持多个镜像源"""
    print("\n正在安装 Playwright 浏览器...")
    print("这可能需要几分钟，请耐心等待...\n")
    
    # 多个镜像源，按优先级尝试
    mirrors = [
        ("国内镜像（淘宝）", "https://npmmirror.com/mirrors/playwright/"),
        ("国内镜像（华为）", "https://repo.huaweicloud.com/playwright/"),
        ("官方源", None),
    ]
    
    for mirror_name, mirror_url in mirrors:
        print(f"尝试使用 {mirror_name}...")
        
        # 设置环境变量
        env = os.environ.copy()
        if mirror_url:
            env["PLAYWRIGHT_DOWNLOAD_HOST"] = mirror_url
        
        try:
            result = subprocess.run(
                [sys.executable, "-m", "playwright", "install", "chromium"],
                capture_output=True,
                text=True,
                timeout=300,  # 5分钟超时
                env=env
            )
            
            if result.returncode == 0:
                print(f"✓ 使用 {mirror_name} 安装成功！\n")
                return True
            else:
                print(f"✗ {mirror_name} 安装失败，尝试下一个源...\n")
        except subprocess.TimeoutExpired:
            print(f"✗ {mirror_name} 超时，尝试下一个源...\n")
        except Exception as e:
            print(f"✗ {mirror_name} 出错: {e}，尝试下一个源...\n")
    
    # 所有镜像都失败
    print("✗ 所有镜像源都安装失败\n")
    return False


def prompt_install_playwright() -> bool:
    """提示用户安装 Playwright"""
    print("=" * 60)
    print("  检测到 Playwright 浏览器未安装")
    print("=" * 60)
    print("\nPlaywright 用于自动化浏览器操作，是爬取功能的核心组件。")
    print("\n是否现在安装？(y/n)")
    print("  y - 自动安装（推荐）")
    print("  n - 跳过，稍后手动安装")
    
    choice = input("\n请选择 [y/n]: ").strip().lower()
    
    if choice == 'y':
        return install_playwright()
    else:
        print("\n已跳过安装。")
        print("\n手动安装方法：")
        print("  python -m playwright install chromium")
        print("\n或：")
        print("  playwright install chromium")
        print()
        return False


def check_llm_config() -> Tuple[bool, Optional[dict]]:
    """检查 LLM 配置是否存在"""
    import os
    from dotenv import load_dotenv
    
    # 优先从用户主目录加载配置（全局配置）
    env_paths = [
        Path.home() / ".nsfc_spider" / ".env",  # 优先
        Path.cwd() / "config" / ".env",
        Path.cwd() / ".env",
    ]
    
    for env_path in env_paths:
        if env_path.exists():
            load_dotenv(env_path)
            break
    
    # 检查必要的配置
    api_key = os.getenv("LLM_API_KEY")
    provider = os.getenv("LLM_PROVIDER", "openai")
    model = os.getenv("LLM_MODEL", "gpt-4o")
    
    if api_key:
        return True, {
            "provider": provider,
            "model": model,
            "api_key": api_key[:10] + "..." if len(api_key) > 10 else api_key
        }
    
    return False, None


def prompt_llm_config() -> Optional[dict]:
    """引导用户配置 LLM"""
    print("\n" + "=" * 60)
    print("  LLM 配置向导")
    print("=" * 60)
    print("\nLLM 用于以下高级功能：")
    print("  • AI 智能搜索（实验性）")
    print("  • 智能筛选项目")
    print("  • 自动生成研究综述")
    print("\n如果只需要基础爬取功能，可以跳过此步骤。")
    print("\n是否现在配置 LLM？(y/n)")
    print("  y - 配置 LLM（推荐）")
    print("  n - 跳过，稍后配置")
    
    choice = input("\n请选择 [y/n]: ").strip().lower()
    
    if choice != 'y':
        print("\n已跳过 LLM 配置。")
        print("\n⚠️  跳过后以下功能将不可用：")
        print("  • /search - AI 智能搜索")
        print("  • /filter - LLM 智能筛选")
        print("  • /review - 生成研究综述")
        print("  • /pipeline - 一键流程")
        print("\n✓  以下功能仍可正常使用：")
        print("  • /scrape - 直接爬取（推荐）")
        print("  • /load - 加载数据")
        print("  • /export - 导出数据")
        print("  • /analyze - 数据分析")
        print("\n稍后可在 CLI 中运行 /config 进行配置。\n")
        return None
    
    # 开始配置
    print("\n" + "-" * 60)
    print("  配置 LLM API")
    print("-" * 60)
    
    # 选择提供商
    print("\n1. 选择 LLM 提供商：")
    print("  1) OpenAI (gpt-4o, gpt-4o-mini)")
    print("  2) Anthropic (claude-sonnet-4)")
    print("  3) DeepSeek (deepseek-chat)")
    print("  4) Ollama (本地模型)")
    print("  5) OpenAI-Compatible (自定义 API)")
    
    provider_choice = input("\n请选择 [1-5，默认 1]: ").strip() or "1"
    
    provider_map = {
        "1": ("openai", "gpt-4o", "https://api.openai.com/v1"),
        "2": ("anthropic", "claude-sonnet-4", None),
        "3": ("openai", "deepseek-chat", "https://api.deepseek.com/v1"),
        "4": ("ollama", "llama2", "http://localhost:11434"),
        "5": ("openai", "", ""),  # 自定义
    }
    
    provider, default_model, default_base_url = provider_map.get(provider_choice, provider_map["1"])
    
    # 如果选择自定义，需要输入 URL
    if provider_choice == "5":
        print("\n  OpenAI-Compatible API 配置")
        print("  支持任何兼容 OpenAI API 格式的服务")
        print("  例如：OneAPI、FastGPT、LocalAI 等")
    
    # 输入模型
    if provider_choice == "5":
        print(f"\n2. 模型名称:")
        print("  例如：gpt-4o, gpt-3.5-turbo, qwen-plus 等")
        model = input("  > ").strip()
        if not model:
            print("\n✗ 模型名称不能为空，配置取消。")
            return None
    else:
        print(f"\n2. 模型名称 [默认: {default_model}]:")
        model = input("  > ").strip() or default_model
    
    # 输入 API Key
    if provider != "ollama":
        print("\n3. API Key:")
        print("  获取地址：")
        if provider == "openai":
            print("    https://platform.openai.com/api-keys")
        elif provider == "anthropic":
            print("    https://console.anthropic.com/")
        elif provider == "deepseek":
            print("    https://platform.deepseek.com/")
        
        api_key = input("\n  请输入 API Key: ").strip()
        
        if not api_key:
            print("\n✗ API Key 不能为空，配置取消。")
            return None
    else:
        api_key = ""
        print("\n  Ollama 本地模型无需 API Key")
    
    # 输入 Base URL
    if provider_choice == "5":
        print(f"\n4. Base URL:")
        print("  例如：https://api.openai-proxy.com/v1")
        print("  例如：http://localhost:8000/v1")
        base_url = input("  > ").strip()
        if not base_url:
            print("\n✗ Base URL 不能为空，配置取消。")
            return None
    elif default_base_url:
        print(f"\n4. Base URL [默认: {default_base_url}]:")
        print("  (直接回车使用默认值)")
        base_url = input("  > ").strip() or default_base_url
    else:
        base_url = None
    
    # 保存配置
    config = {
        "provider": provider,
        "model": model,
        "api_key": api_key,
        "base_url": base_url
    }
    
    # 询问是否保存
    print("\n" + "-" * 60)
    print("  配置预览")
    print("-" * 60)
    print(f"  提供商: {provider}")
    print(f"  模型: {model}")
    if api_key:
        print(f"  API Key: {api_key[:10]}...")
    if base_url:
        print(f"  Base URL: {base_url}")
    
    print("\n是否保存配置？(y/n)")
    save_choice = input("  > ").strip().lower()
    
    if save_choice == 'y':
        save_config(config)
        print("\n✓ 配置已保存！\n")
        return config
    else:
        print("\n配置未保存。\n")
        return None


def save_config(config: dict):
    """保存配置到文件 - 默认保存到用户主目录"""
    # 默认保存到用户主目录（全局配置）
    config_dir = Path.home() / ".nsfc_spider"
    config_dir.mkdir(exist_ok=True)
    config_file = config_dir / ".env"
    
    # 写入配置
    with open(config_file, "w", encoding="utf-8") as f:
        f.write(f"# NSFC Spider 配置文件\n")
        f.write(f"# 自动生成于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
        f.write(f"LLM_PROVIDER={config['provider']}\n")
        f.write(f"LLM_MODEL={config['model']}\n")
        if config['api_key']:
            f.write(f"LLM_API_KEY={config['api_key']}\n")
        if config.get('base_url'):
            f.write(f"LLM_BASE_URL={config['base_url']}\n")
        f.write(f"\nHEADLESS=false\n")
    
    print(f"  配置文件: {config_file}")


def run_setup_wizard():
    """运行完整的安装向导"""
    print("\n" + "=" * 60)
    print("  欢迎使用 NSFC Spider！")
    print("=" * 60)
    print("\n首次运行，正在检查环境...\n")
    
    # 1. 检查 Playwright
    playwright_ok, playwright_msg = check_playwright()
    print(f"[1/2] Playwright: {playwright_msg}")
    
    if not playwright_ok:
        playwright_ok = prompt_install_playwright()
    
    # 2. 检查 LLM 配置
    llm_ok, llm_config = check_llm_config()
    
    if llm_ok:
        print(f"[2/2] LLM 配置: 已配置 ({llm_config['provider']}/{llm_config['model']})")
    else:
        print(f"[2/2] LLM 配置: 未配置")
        prompt_llm_config()
    
    # 完成
    print("\n" + "=" * 60)
    print("  环境检查完成！")
    print("=" * 60)
    
    if not playwright_ok:
        print("\n⚠️  Playwright 未安装，爬取功能将不可用。")
        print("   请稍后运行: playwright install chromium")
    
    print("\n输入 /help 查看所有命令")
    print("输入 /scrape <关键词> 开始爬取")
    print("=" * 60 + "\n")
    
    return playwright_ok
