@echo off
setlocal
cd /d "%~dp0"

set "PY="
py -3.12 -c "import sys" >nul 2>nul && set "PY=py -3.12"
if not defined PY py -3.11 -c "import sys" >nul 2>nul && set "PY=py -3.11"
if not defined PY (
  echo 分弦需要 Python 3.11 或 3.12。
  echo 请先从 https://www.python.org/downloads/windows/ 安装。
  pause
  exit /b 1
)

set "RUNTIME=..\..\runtime\fenxuan"
set "VENV=%RUNTIME%\venv-windows"
set "FENXUAN_DATA=%RUNTIME%\data"
set "TORCH_HOME=%RUNTIME%\torch-home"
if not exist "%FENXUAN_DATA%" mkdir "%FENXUAN_DATA%"

for /f %%H in ('powershell -NoProfile -Command "$a=(Get-FileHash requirements.txt -Algorithm SHA256).Hash; $b=(Get-FileHash requirements-demucs.txt -Algorithm SHA256).Hash; Write-Output ($a+$b)"') do set "REQ_HASH=%%H"
set "INSTALLED_HASH="
if exist "%RUNTIME%\requirements-windows.sha256" set /p INSTALLED_HASH=<"%RUNTIME%\requirements-windows.sha256"

if not exist "%VENV%\Scripts\python.exe" goto rebuild
if /i not "%REQ_HASH%"=="%INSTALLED_HASH%" goto rebuild
goto ready

:rebuild
echo 正在准备分弦运行环境，第一次需要几分钟...
%PY% -m venv --clear "%VENV%" || goto error
"%VENV%\Scripts\python.exe" -m pip install --quiet --upgrade pip || goto error
"%VENV%\Scripts\python.exe" -m pip install --quiet -r requirements.txt -r requirements-demucs.txt || goto error
>"%RUNTIME%\requirements-windows.sha256" echo %REQ_HASH%

:ready
start "" http://127.0.0.1:8642
"%VENV%\Scripts\python.exe" server\app.py
exit /b %errorlevel%

:error
echo 安装没有完成，请检查网络后重新双击。
pause
exit /b 1
