#!/usr/bin/env python
"""
NSFC Spider 主入口 - 用于打包成 exe
自动检测并安装 Playwright 浏览器
"""

import sys
import os
import subprocess
from pathlib import Path


def check_and_install_playwright():
    """检查并安装 Playwright 浏览器"""
    import shutil
    
    # 打包环境下，使用内置的 playwright CLI
    if getattr(sys, 'frozen', False):
        # 查找打包的 playwright driver
        app_path = Path(sys.executable).parent
        driver_path = app_path / "_internal" / "playwright" / "driver"
        if not driver_path.exists():
            driver_path = app_path / "playwright" / "driver"
        
        # 设置环境变量让 playwright 找到 driver
        if driver_path.exists():
            os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(app_path / "_internal" / "playwright" / "browsers")
    
    try:
        from playwright.sync_api import sync_playwright
        # 尝试启动浏览器检测是否已安装
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True)
            browser.close()
        return True
    except Exception as e:
        error_msg = str(e).lower()
        
        # 打包环境下，不能用 subprocess 安装
        if getattr(sys, 'frozen', False):
            print("=" * 50)
            print("  浏览器组件未安装")
            print("=" * 50)
            print(f"\n错误: {e}")
            print("\n请先安装 Playwright 浏览器:")
            print("  1. 打开命令行")
            print("  2. 运行: playwright install chromium")
            print("\n或者安装 Python 后运行:")
            print("  python -m playwright install chromium")
            return False
        
        # 开发环境下，尝试自动安装
        print("=" * 50)
        print("  首次运行，正在安装浏览器组件...")
        print("  这可能需要几分钟，请耐心等待")
        print("=" * 50)
        try:
            subprocess.run(
                [sys.executable, "-m", "playwright", "install", "chromium"],
                check=True
            )
            print("\n✓ 浏览器组件安装完成！\n")
            return True
        except Exception as install_err:
            print(f"\n❌ 浏览器安装失败: {install_err}")
            print("请手动运行: python -m playwright install chromium")
            return False


def main():
    """主入口"""
    # 设置工作目录
    if getattr(sys, 'frozen', False):
        # 打包后的 exe
        app_path = Path(sys.executable).parent
    else:
        app_path = Path(__file__).parent
    
    os.chdir(app_path)
    
    # 检查浏览器
    if not check_and_install_playwright():
        input("\n按回车键退出...")
        return
    
    # 添加 src 到路径
    src_path = app_path / "src"
    if src_path.exists():
        sys.path.insert(0, str(src_path))
    
    # 启动 CLI
    from nsfc_spider.cli import main as cli_main
    cli_main()


if __name__ == "__main__":
    main()
