@echo off
setlocal enabledelayedexpansion

:: Autonomous AI Agent - Update Script (Windows)
:: Checks for and installs updates from the deployed site.

set UPDATE_URL=https://ai-do-site.pages.dev

echo.
echo   Autonomous AI Agent - Update Check
echo.

:: Get local version
set LOCAL_VERSION=0.0.0
if exist version.json (
    for /f %%i in ('node -e "console.log(JSON.parse(require('fs').readFileSync('version.json','utf-8')).version||'0.0.0')"') do set LOCAL_VERSION=%%i
)
echo   Local version:  !LOCAL_VERSION!

:: Fetch remote version using PowerShell (avoids temp file path issues)
echo   Checking for updates...

for /f %%i in ('powershell -NoProfile -Command "try { $r = Invoke-WebRequest -Uri '%UPDATE_URL%/version.json' -UseBasicParsing; ($r.Content | ConvertFrom-Json).version } catch { '0.0.0' }"') do set REMOTE_VERSION=%%i

if "!REMOTE_VERSION!"=="" set REMOTE_VERSION=0.0.0
if "!REMOTE_VERSION!"=="0.0.0" (
    echo   Could not reach update server.
    echo   URL: %UPDATE_URL%/version.json
    pause
    exit /b 1
)

echo   Remote version: !REMOTE_VERSION!

:: Compare versions
for /f %%i in ('node -e "const l='!LOCAL_VERSION!'.split('.').map(Number),r='!REMOTE_VERSION!'.split('.').map(Number);for(let i=0;i<3;i++){if((r[i]||0)>(l[i]||0)){console.log('yes');process.exit(0);}if((r[i]||0)<(l[i]||0)){console.log('no');process.exit(0);}}console.log('no');"') do set NEEDS_UPDATE=%%i

if "!NEEDS_UPDATE!" neq "yes" (
    echo.
    echo   You're up to date!
    echo.
    pause
    exit /b 0
)

echo.
echo   Update available: !LOCAL_VERSION! -^> !REMOTE_VERSION!
echo.

set /p CONFIRM="  Install update? (Y/n): "
if /i "!CONFIRM!"=="n" (
    echo   Update cancelled.
    exit /b 0
)

:: Stop agent if running
taskkill /f /fi "WINDOWTITLE eq node agent.mjs" >nul 2>&1

:: Download and extract using PowerShell (reliable temp path handling)
echo   Downloading update...
set ZIPFILE=%TEMP%\agent-update.zip
set EXTRACTDIR=%TEMP%\agent-update

powershell -NoProfile -Command "Invoke-WebRequest -Uri '%UPDATE_URL%/agent.zip' -OutFile '%ZIPFILE%'"

echo   Extracting...
if exist "%EXTRACTDIR%" rmdir /s /q "%EXTRACTDIR%"
powershell -NoProfile -Command "Expand-Archive -Force '%ZIPFILE%' '%EXTRACTDIR%'"

:: Apply update (code files only - preserves config.json, journal, workspace, db)
echo   Applying update...

set SRC=%EXTRACTDIR%

:: Copy core files
for %%f in (agent.mjs config.mjs db.mjs server.mjs skills.mjs memory.mjs inspiration.mjs workspace.mjs workspace-manager.mjs task-scheduler.mjs llm.mjs json-utils.mjs evolution.mjs voice-activation.mjs knowledge-graph.mjs entity-extraction.mjs semantic-search.mjs ingestion.mjs fetch-utils.mjs file-watcher.mjs personality.md loop-instructions.md tools.md setup.sh setup.bat update.sh update.bat reset.sh reset.bat watchdog.sh install.sh) do (
    if exist "!SRC!\%%f" copy /y "!SRC!\%%f" "%%f" >nul 2>&1
)

:: Copy directories
for %%d in (adapters skills scripts public cognitive multimodal electron) do (
    if exist "!SRC!\%%d" xcopy /s /y /q "!SRC!\%%d\*" "%%d\" >nul 2>&1
)

:: Update version.json
if exist "!SRC!\version.json" copy /y "!SRC!\version.json" "version.json" >nul

:: Update .claude/settings.json (tool policies)
if exist "!SRC!\.claude\settings.json" (
    if not exist .claude mkdir .claude
    copy /y "!SRC!\.claude\settings.json" ".claude\settings.json" >nul
)

:: Merge package.json dependencies using node (reads from current dir, no temp paths needed)
if exist "!SRC!\package.json" (
    copy /y "!SRC!\package.json" "package.json.new" >nul
    node -e "const fs=require('fs');const l=JSON.parse(fs.readFileSync('package.json','utf-8'));const r=JSON.parse(fs.readFileSync('package.json.new','utf-8'));l.dependencies={...l.dependencies,...r.dependencies};fs.writeFileSync('package.json',JSON.stringify(l,null,2)+'\n');"
    del "package.json.new" 2>nul
)

:: Reinstall dependencies
echo   Updating dependencies...
call npm install --silent 2>nul

:: Create directories that may be new in this version
if not exist workspaces\default mkdir workspaces\default
if not exist data\wake-words mkdir data\wake-words
if not exist data\wake-word-models mkdir data\wake-word-models

:: Cleanup
rmdir /s /q "%EXTRACTDIR%" 2>nul
del "%ZIPFILE%" 2>nul

echo.
echo   Updated to version !REMOTE_VERSION!!
echo.
echo   Restart your agent with: npm start
echo.

pause
