@echo off
setlocal EnableExtensions
cd /d "%~dp0"
title Daily Loss Local App

set "ROOT=%~dp0"
set "PY=%ROOT%runtime\python\python.exe"
set "APPDIR=%ROOT%app"
set "LOGDIR=%ROOT%logs"
set "LOGFILE=%LOGDIR%\startup.log"
set "PORT=8501"

if not exist "%LOGDIR%" mkdir "%LOGDIR%"

echo.>"%LOGFILE%"
echo Daily Loss Local App startup log>>"%LOGFILE%"
echo Time: %date% %time%>>"%LOGFILE%"
echo Root: %ROOT%>>"%LOGFILE%"
echo.>>"%LOGFILE%"

echo.
echo ============================================================
echo  Daily Loss Local App
echo ============================================================
echo.
echo This launcher does not use PowerShell.
echo Keep this window open while using the app.
echo Log file: %LOGFILE%
echo.

if not exist "%PY%" (
  echo ERROR: Portable Python was not found.
  echo ERROR: Portable Python was not found.>>"%LOGFILE%"
  echo The zip may not have been fully extracted.
  goto FAILED
)

if not exist "%APPDIR%\app.py" (
  echo ERROR: App files were not found.
  echo ERROR: App files were not found.>>"%LOGFILE%"
  echo The zip may not have been fully extracted.
  goto FAILED
)

echo Checking local runtime...
"%PY%" -c "import sys; print(sys.version)" >>"%LOGFILE%" 2>&1
if errorlevel 1 (
  echo ERROR: Windows blocked or failed to start the portable Python runtime.
  echo See the log file above for details.
  goto FAILED
)

"%PY%" -c "import fastapi, uvicorn, pandas, openpyxl, xlrd, multipart; import app; print('runtime ok')" >>"%LOGFILE%" 2>&1
if errorlevel 1 (
  echo ERROR: Runtime self-check failed.
  echo See the log file above for details.
  goto FAILED
)

echo Runtime check passed.
echo Starting app at http://127.0.0.1:%PORT%
echo A browser window should open in a few seconds.
echo.

start "" /min cmd /c "timeout /t 4 >nul & start "" "http://127.0.0.1:%PORT%""

cd /d "%APPDIR%"
"%PY%" -m uvicorn app:app --host 127.0.0.1 --port %PORT% --log-level info

echo.
echo The local app has stopped.
echo If this was unexpected, check the log file:
echo %LOGFILE%
echo.
pause
exit /b 0

:FAILED
echo.
echo Startup failed. This window will stay open so the error can be read.
echo If this says the app was blocked by policy, try:
echo 1. Delete the extracted folder.
echo 2. Right-click the downloaded zip file.
echo 3. Open Properties.
echo 4. Tick Unblock, then click OK.
echo 5. Extract the zip again and run START.cmd.
echo.
echo If there is no Unblock checkbox, send this log file:
echo %LOGFILE%
echo.
type "%LOGFILE%"
echo.
cmd /k
