@echo off
chcp 65001 >nul
setlocal EnableExtensions
cd /d "%~dp0"

set "ENTRYPOINT=app.py"
set "VENV_DIR=.venv"
set "PY_LAUNCHER="

where py >nul 2>nul
if not errorlevel 1 set "PY_LAUNCHER=py -3"
if not defined PY_LAUNCHER (
  where python >nul 2>nul
  if not errorlevel 1 set "PY_LAUNCHER=python"
)

if not defined PY_LAUNCHER (
  echo [PYTHON_NOT_FOUND] 未检测到 Python 3，正在启动安全安装引导...
  if not exist "scripts\install_python_windows.ps1" (
    echo [PYTHON_BOOTSTRAP_MISSING] 缺少 Python 安装引导；请重新解压完整系统 ZIP。
    pause
    exit /b 1
  )
  powershell.exe -NoLogo -NoProfile -File "scripts\install_python_windows.ps1" -ProjectDir "%CD%"
  if errorlevel 1 (
    echo [PYTHON_INSTALL_FAILED] Python 未安装；请按上方中文解决步骤处理。
    pause
    exit /b 1
  )
  where py >nul 2>nul
  if not errorlevel 1 set "PY_LAUNCHER=py -3"
  if not defined PY_LAUNCHER (
    where python >nul 2>nul
    if not errorlevel 1 set "PY_LAUNCHER=python"
  )
  if not defined PY_LAUNCHER (
    echo [PYTHON_RESTART_REQUIRED] Python 已完成安装，但当前终端尚未识别；请关闭窗口后再次双击启动。
    pause
    exit /b 1
  )
)

%PY_LAUNCHER% -c "import sys; raise SystemExit(0 if sys.version_info >= (3,10) else 1)"
if errorlevel 1 (
  echo [PYTHON_VERSION_UNSUPPORTED] Python 版本过低；需要 Python 3.10 或更高版本。
  pause
  exit /b 1
)

if not exist "%VENV_DIR%\Scripts\python.exe" (
  echo [信息] 正在创建项目虚拟环境...
  %PY_LAUNCHER% -m venv "%VENV_DIR%"
  if errorlevel 1 goto :venv_fail
)

set "VENV_PY=%VENV_DIR%\Scripts\python.exe"
if not exist "scripts\install_dependencies.py" (
  echo [DEPENDENCY_HELPER_MISSING] 缺少依赖安装助手；请重新解压完整系统 ZIP。
  pause
  exit /b 2
)

echo [信息] 正在校验依赖；完整离线包存在时优先离线安装...
"%VENV_PY%" "scripts\install_dependencies.py" "." --max-retries 2
if errorlevel 1 (
  echo [DEPENDENCY_INSTALL_FAILED] 依赖准备失败；数据库未修改。
  echo 处理建议：联网后重试，或先运行 scripts\prepare_offline_dependencies.py 准备 wheels。
  pause
  exit /b 2
)

if not exist "%ENTRYPOINT%" (
  echo [ENTRYPOINT_MISSING] 找不到程序入口：%ENTRYPOINT%；请重新解压完整系统 ZIP。
  pause
  exit /b 2
)

if exist "scripts\preflight_check.py" (
  echo [信息] 正在执行启动前自检...
  "%VENV_PY%" "scripts\preflight_check.py" "."
  if errorlevel 1 (
    echo [PREFLIGHT_FAILED] 启动前自检未通过；请按上方中文解决步骤处理后重试。
    pause
    exit /b 2
  )
)

echo [信息] 正在启动无纸化业务系统...
"%VENV_PY%" "%ENTRYPOINT%"
set "EXIT_CODE=%ERRORLEVEL%"
if not "%EXIT_CODE%"=="0" (
  echo [APP_EXITED] 程序异常退出，代码：%EXIT_CODE%；请查看 logs 目录。
  pause
)
exit /b %EXIT_CODE%

:venv_fail
echo [VENV_CREATE_FAILED] 虚拟环境创建失败；请检查 Python 安装和项目目录写入权限。
pause
exit /b 1
