@echo off
setlocal EnableExtensions
set "WA_DIR=%LOCALAPPDATA%\Workaistra"
if not exist "%WA_DIR%" mkdir "%WA_DIR%"
echo Updating Workaistra AI Intelligence integration...

REM Stop only Workaistra's old worker(s) and dedicated browser profile. Build exact paths first so PowerShell wildcard matching uses real single-backslash Windows paths.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$wa=[IO.Path]::Combine($env:LOCALAPPDATA,'Workaistra'); $bridge=[IO.Path]::Combine($wa,'bridge.ps1'); $legacy=[IO.Path]::Combine($wa,'workaistra-bridge.ps1'); $profile=[IO.Path]::Combine($wa,'browser-profile'); Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and (($_.CommandLine -like ('*'+$bridge+'*')) -or ($_.CommandLine -like ('*'+$legacy+'*')) -or ($_.CommandLine -like ('*--user-data-dir=*'+$profile+'*'))) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }" >nul 2>&1
timeout /t 1 /nobreak >nul

REM Store this device's scoped Workaistra bridge configuration locally.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "[IO.File]::WriteAllText((Join-Path $env:LOCALAPPDATA 'Workaistra\config.json'),[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('eyJiYXNlVXJsIjoiaHR0cHM6Ly8wLjAuMC4wOjMwMDAiLCJ0b2tlbiI6InFXUmRqWUE0dzlCVkFaUE1IYlVSLTdMcWFvNXd4V3huNGktT0JBbkhNSVUiLCJkZWJ1Z1BvcnQiOjkyMjN9')))"
if errorlevel 1 goto :configfail

REM Install the current visible-UI browser launcher and Intelligence worker.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -UseBasicParsing -Uri 'https://0.0.0.0:3000/open-chatgpt.ps1' -OutFile (Join-Path $env:LOCALAPPDATA 'Workaistra\open-chatgpt.ps1'); Invoke-WebRequest -UseBasicParsing -Uri 'https://0.0.0.0:3000/workaistra-bridge.ps1' -OutFile (Join-Path $env:LOCALAPPDATA 'Workaistra\bridge.ps1')"
if errorlevel 1 goto :downloadfail

REM Refuse to start a stale/legacy helper. The current worker must contain this marker.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "if (-not (Select-String -Quiet -Path (Join-Path $env:LOCALAPPDATA 'Workaistra\bridge.ps1') -SimpleMatch 'Workaistra Intelligence bridge started')) { exit 2 }"
if errorlevel 1 goto :stalefail

REM Register workaistra:// only for the dedicated ChatGPT login/profile launcher.
reg add "HKCU\Software\Classes\workaistra" /ve /d "URL:Workaistra Protocol" /f >nul
reg add "HKCU\Software\Classes\workaistra" /v "URL Protocol" /d "" /f >nul
reg add "HKCU\Software\Classes\workaistra\shell\open\command" /ve /d "powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"%LOCALAPPDATA%\Workaistra\open-chatgpt.ps1\" \"%%1\"" /f >nul

REM Start one hidden worker at Windows login.
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v WorkaistraBridge /t REG_SZ /d "powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File \"%LOCALAPPDATA%\Workaistra\bridge.ps1\"" /f >nul

REM Mark the reinstall boundary in diagnostics, then start the fresh worker now.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Add-Content -Path (Join-Path $env:LOCALAPPDATA 'Workaistra\bridge.log') -Value ('----- reinstall '+[DateTime]::Now.ToString('s')+' -----')" >nul 2>&1
start "WorkaistraBridge" /min powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "%LOCALAPPDATA%\Workaistra\bridge.ps1"
timeout /t 3 /nobreak >nul

REM Verify a current worker process exists instead of silently claiming success.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$p=[IO.Path]::Combine($env:LOCALAPPDATA,'Workaistra','bridge.ps1'); $running=Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like ('*'+$p+'*') }; if (-not $running) { exit 3 }"
if errorlevel 1 goto :startfail

start "Workaistra ChatGPT" powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%LOCALAPPDATA%\Workaistra\open-chatgpt.ps1"

echo.
echo Workaistra AI Intelligence integration installed and worker process started.
echo Keep the dedicated Workaistra ChatGPT profile signed in.
echo Refresh Workaistra after a few seconds; Intelligence Worker should show Online.
echo Diagnostics: %LOCALAPPDATA%\Workaistra\bridge.log
timeout /t 7 /nobreak >nul
exit /b 0

:configfail
echo.
echo FAILED: Could not write Workaistra worker configuration.
goto :fail

:downloadfail
echo.
echo FAILED: Could not download the current Workaistra worker files.
echo If this project uses Vercel Deployment Protection, the background installer download must be allowed or bypassed.
goto :fail

:stalefail
echo.
echo FAILED: The downloaded bridge file is not the current Intelligence worker.
goto :fail

:startfail
echo.
echo FAILED: The Intelligence worker exited immediately after launch.
goto :fail

:fail
echo See %LOCALAPPDATA%\Workaistra\bridge.log for diagnostics.
echo Keep this window open and report the message above.
pause
exit /b 1
