@echo off
chcp 65001 >nul
title AI Screen Tracker - 一键安装与启动

cd /d "%~dp0"

echo ========================================
echo   AI Screen Tracker 智能安装器
echo   首次运行会自动配置环境
echo ========================================
echo.

set PYTHON_FOUND=0
where python >nul 2>&1
if %errorlevel%==0 set PYTHON_FOUND=1

if %PYTHON_FOUND%==0 (
    echo [1/3] 未检测到 Python，正在下载便携版（约 10MB）...
    if not exist "_python" mkdir _python
    powershell -Command "& {[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri 'https://www.python.org/ftp/python/3.11.9/python-3.11.9-embed-amd64.zip' -OutFile '_python\python.zip' -UseBasicParsing}" >nul 2>&1
    if not exist "_python\python.exe" (
        echo [错误] Python 下载失败！请检查网络后重试
        echo 或手动安装 Python: https://www.python.org/downloads/
        pause
        exit /b 1
    )
    echo     解压 Python...
    powershell -Command "& {Expand-Archive -Path '_python\python.zip' -DestinationPath '_python' -Force}" >nul 2>&1
    del _python\python.zip >nul 2>&1
    set "PATH=%~dp0_python;%~dp0_python\Scripts;%PATH%"
    echo     Python 已就绪
) else (
    echo [1/3] 已检测到 Python
)

echo.
echo [2/3] 安装依赖（首次需要 1-2 分钟）...
python -m pip install --disable-pip-version-check -r requirements.txt -q 2>nul
if %errorlevel% neq 0 (
    echo [!] 正在重试...
    python -m pip install --disable-pip-version-check -r requirements.txt
)
if %errorlevel% neq 0 (
    echo [错误] 依赖安装失败！
    pause
    exit /b 1
)

echo.
echo [3/3] 启动程序...
echo.
python screen_tracker.py

if %errorlevel% neq 0 (
    echo.
    echo [错误] 程序异常退出，按任意键关闭
    pause
)