#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
环境检测与自动安装脚本 (跨平台)
支持 Windows / macOS / Linux
自动检测并安装: Python、Playwright、浏览器驱动
用法:
    python install_env.py
"""

import os
import sys
import subprocess
import platform
from pathlib import Path


def get_platform():
    if sys.platform == "win32":
        return "windows"
    elif sys.platform == "darwin":
        return "macos"
    return "linux"


def run_cmd(cmd, timeout=180, capture=True):
    """运行命令并返回结果"""
    try:
        result = subprocess.run(
            cmd, capture_output=capture, text=True, timeout=timeout,
            encoding="utf-8", errors="replace"
        )
        return result
    except Exception as e:
        class FakeResult:
            returncode = 1
            stdout = ""
            stderr = str(e)
        return FakeResult()


def print_section(title):
    print(f"\n{'='*50}")
    print(f"  {title}")
    print(f"{'='*50}")


def print_status(name, ok, detail=""):
    icon = "✅" if ok else "❌"
    print(f"  {icon} {name:<20} {detail}")


def detect_python():
    """检测 Python 环境"""
    candidates = [sys.executable]
    if sys.platform != "win32":
        candidates.insert(0, "python3")
    candidates.insert(0, "python")

    for cmd in candidates:
        result = run_cmd([cmd, "-c", "import sys; print(sys.executable)"], timeout=10)
        if result.returncode == 0 and result.stdout.strip():
            return result.stdout.strip(), cmd
    return None, None


def detect_playwright(python_path):
    """检测 Playwright"""
    result = run_cmd([python_path, "-c", "import playwright; print(playwright.__version__)"], timeout=15)
    if result.returncode == 0:
        return True, result.stdout.strip()
    return False, ""


def detect_browser(python_path):
    """检测浏览器驱动"""
    check_script = (
        "from playwright.sync_api import sync_playwright; "
        "p = sync_playwright().start(); "
        "b = p.chromium.launch(headless=True); "
        "b.close(); p.stop(); print('ok')"
    )
    result = run_cmd([python_path, "-c", check_script], timeout=60)
    if result.returncode == 0:
        return True, "Chromium"
    return False, result.stderr[:200]


def install_playwright_package(python_path):
    """安装 Playwright Python 包"""
    print("  正在安装 playwright 包...")
    result = run_cmd([python_path, "-m", "pip", "install", "playwright"], timeout=300)
    if result.returncode != 0:
        print(f"  ⚠️ 安装失败，尝试强制重装...")
        result = run_cmd([python_path, "-m", "pip", "install", "--force-reinstall", "playwright"], timeout=300)
    return result.returncode == 0


def install_browser(python_path):
    """安装浏览器驱动"""
    print("  正在下载浏览器驱动 (约 100-200MB)...")
    channels = ["chromium", "msedge", "chrome"]
    for ch in channels:
        print(f"  尝试安装 {ch}...")
        result = run_cmd([python_path, "-m", "playwright", "install", ch], timeout=600)
        if result.returncode == 0:
            return True, ch
    return False, ""


def main():
    plat = get_platform()
    print(f"\n{'='*50}")
    print(f"  优卖云自动导出 - 环境检测与安装")
    print(f"  平台: {platform.system()} ({plat})")
    print(f"{'='*50}")

    # 1. 检测 Python
    print_section("1. 检测 Python 环境")
    python_path, python_cmd = detect_python()
    if python_path:
        print_status("Python", True, python_path)
    else:
        print_status("Python", False, "未检测到")
        print("\n  请安装 Python 3.9+:")
        print("  Windows: https://python.org/downloads (勾选 'Add to PATH')")
        print("  macOS:   brew install python3")
        print("  Linux:   sudo apt install python3 python3-pip")
        input("\n按回车键退出...")
        sys.exit(1)

    # 2. 检测 Playwright
    print_section("2. 检测 Playwright 库")
    has_pw, pw_ver = detect_playwright(python_path)
    print_status("Playwright", has_pw, pw_ver if has_pw else "未安装")

    # 3. 检测浏览器
    print_section("3. 检测浏览器驱动")
    has_browser, browser_detail = detect_browser(python_path)
    print_status("浏览器驱动", has_browser, browser_detail if has_browser else "未就绪")

    # 判断是否需要安装
    all_ok = has_pw and has_browser
    if all_ok:
        print("\n✅ 环境检测全部通过！可以直接运行 sellerspace_auto_export.py")
        input("\n按回车键退出...")
        return

    print("\n⚠️ 环境未就绪，开始自动安装...")
    input("按回车键开始安装 (需要联网)...")

    # 安装 Playwright
    if not has_pw:
        print_section("安装 Playwright Python 包")
        if install_playwright_package(python_path):
            print("  ✅ Playwright 包安装成功")
        else:
            print("  ❌ Playwright 包安装失败")
            print("  请手动运行: python -m pip install playwright")
            input("\n按回车键退出...")
            sys.exit(1)

    # 安装浏览器
    if not has_browser:
        print_section("安装浏览器驱动")
        ok, ch = install_browser(python_path)
        if ok:
            print(f"  ✅ 浏览器驱动安装成功 ({ch})")
        else:
            print("  ❌ 浏览器驱动安装失败")
            print("  请手动运行: python -m playwright install chromium")
            input("\n按回车键退出...")
            sys.exit(1)

    # 最终验证
    print_section("最终验证")
    has_pw, pw_ver = detect_playwright(python_path)
    has_browser, browser_detail = detect_browser(python_path)
    print_status("Playwright", has_pw, pw_ver)
    print_status("浏览器驱动", has_browser, browser_detail)

    if has_pw and has_browser:
        print("\n✅ 所有环境已就绪！")
        print("\n  现在可以运行:")
        print("  python sellerspace_auto_export.py --interactive")
    else:
        print("\n❌ 环境验证未通过，请检查网络或手动安装")

    input("\n按回车键退出...")


if __name__ == "__main__":
    main()
