@echo off
setlocal EnableExtensions
title Paychek Safeguard
cd /d "%~dp0"

set "ROOT=%~dp0"
if "%ROOT:~-1%"=="\" set "ROOT=%ROOT:~0,-1%"

REM Kit root = parent of _technique (user-facing .bat live there)
for %%I in ("%ROOT%\..") do set "KIT=%%~fI"

REM Unblock files marked as downloaded from the Internet (MOTW).
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "Get-ChildItem -LiteralPath '%KIT%' -Recurse -File -ErrorAction SilentlyContinue | Unblock-File -ErrorAction SilentlyContinue" >nul 2>&1

REM First launch: Desktop shortcut "Paychek Safeguard" (1 double-click afterwards).
call :EnsureDesktopShortcut

if not exist "%ROOT%\src\desktop_launcher.py" (
  call :Fail "Application files not found (_technique\src\desktop_launcher.py).||Fully extract the ZIP (do not run from inside the ZIP), then double-click 3-Open-Safeguard.bat."
  exit /b 1
)

set "PY="
set "PYW="
if exist "%ROOT%\runtime\pythonw.exe" set "PYW=%ROOT%\runtime\pythonw.exe"
if exist "%ROOT%\runtime\python.exe" set "PY=%ROOT%\runtime\python.exe"
if not defined PY (
  where python >nul 2>&1
  if not errorlevel 1 for /f "delims=" %%P in ('where python') do (
    if not defined PY set "PY=%%P"
  )
)
if not defined PYW if defined PY (
  for %%I in ("%PY%") do if exist "%%~dpIpythonw.exe" set "PYW=%%~dpIpythonw.exe"
)
if not defined PY if not defined PYW (
  call :Fail "Python not found.||The _technique\runtime\ folder must be present in the ZIP (portable python.exe).||Re-download PaychekSafeguard-Windows.zip from paychek.pro."
  exit /b 1
)

REM Prefer pythonw = no black terminal window.
REM Set PAYCHEK_SHOW_CONSOLE=1 to keep a visible console for debugging.
if /I "%PAYCHEK_SHOW_CONSOLE%"=="1" goto :RunVisible

if defined PYW (
  echo.
  echo  Paychek Safeguard is starting...
  echo  The UI opens in Edge/Chrome. No terminal stays open.
  echo  Server keeps running if you close the UI (needed for NinjaTrader).
  echo  To stop: run _technique\STOP.bat
  echo.
  start "" /D "%ROOT%" "%PYW%" "%ROOT%\src\desktop_launcher.py"
  exit /b 0
)

REM Fallback if pythonw is missing: hide via PowerShell.
echo.
echo  Paychek Safeguard is starting (hidden)...
echo  To stop: run STOP.bat
echo.
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "Start-Process -FilePath '%PY%' -ArgumentList '\"%ROOT%\src\desktop_launcher.py\"' -WorkingDirectory '%ROOT%' -WindowStyle Hidden"
exit /b 0

:RunVisible
echo.
echo  ========================================
echo   Paychek Safeguard  (debug console)
echo  ========================================
echo.
echo  Leave this window OPEN while you trade.
echo  Close it to stop.
echo.
"%PY%" "%ROOT%\src\desktop_launcher.py"
set ERR=%ERRORLEVEL%
echo.
if %ERR% neq 0 (
  call :Fail "Server stopped with an error (code %ERR%).||See logs: %%LOCALAPPDATA%%\PaychekCompanion\logs\desktop.log||If Windows blocked the ZIP: right-click the extracted folder -^> Properties -^> Unblock, or run 3-Open-Safeguard.bat again."
  exit /b %ERR%
)
echo Server stopped.
pause
exit /b 0

:EnsureDesktopShortcut
set "MARKER=%ROOT%\.desktop_shortcut_done"
if exist "%MARKER%" exit /b 0
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='Stop';" ^
  "$desk=[Environment]::GetFolderPath('Desktop');" ^
  "$lnk=Join-Path $desk 'Paychek Safeguard.lnk';" ^
  "$kit='%KIT%';" ^
  "$tech='%ROOT%';" ^
  "$target=Join-Path $kit '3-Open-Safeguard.bat';" ^
  "if (-not (Test-Path -LiteralPath $target)) { $target=Join-Path $kit 'Open-Safeguard.bat' };" ^
  "if (-not (Test-Path -LiteralPath $target)) { $target=Join-Path $tech 'START.bat' };" ^
  "if (-not (Test-Path -LiteralPath $target)) { exit 0 };" ^
  "$w=New-Object -ComObject WScript.Shell;" ^
  "$s=$w.CreateShortcut($lnk);" ^
  "$s.TargetPath=$target;" ^
  "$s.WorkingDirectory=(Split-Path -Parent $target);" ^
  "$s.WindowStyle=7;" ^
  "$s.Description='Open Paychek Safeguard (local server + UI window)';" ^
  "$ico=Join-Path $tech 'paychek.ico';" ^
  "if (-not (Test-Path -LiteralPath $ico)) { $ico=Join-Path $kit 'paychek.ico' };" ^
  "if (Test-Path -LiteralPath $ico) { $s.IconLocation=$ico + ',0' };" ^
  "$s.Save();" ^
  "Write-Host 'Desktop shortcut created: Paychek Safeguard'"
if not errorlevel 1 (
  echo.>"%MARKER%"
  echo.
  echo  Desktop shortcut created: "Paychek Safeguard"
  echo.
)
exit /b 0

:Fail
set "PAYCHEK_ERR=%~1"
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "Add-Type -AssemblyName System.Windows.Forms;" ^
  "$t=($env:PAYCHEK_ERR -replace '\|\|',[Environment]::NewLine);" ^
  "[void][System.Windows.Forms.MessageBox]::Show($t,'Paychek Safeguard - Error','OK','Error')"
echo.
echo [ERROR]
echo %PAYCHEK_ERR:||= %
echo.
set "PAYCHEK_ERR="
pause
exit /b 1
