@echo off
setlocal enabledelayedexpansion

:: Autonomous AI Agent - Setup Script (Windows)
:: Installs everything you need and configures your agent.
:: Run this after extracting the agent zip file.

echo.
echo   ========================================
echo   Autonomous AI Agent - Setup
echo   A mind that thinks, creates, ^& grows
echo   ========================================
echo.

:: -- Step 1: Node.js -----------------------------------------

echo Step 1 of 5 - Node.js
echo.

where node >nul 2>&1
if %errorlevel% neq 0 (
    echo   ! Node.js not found
    echo.
    echo   Node.js 20+ is required. The installer will open in your browser.
    echo.
    set /p INSTALL_NODE="  Install Node.js now? [Y]: "
    if "!INSTALL_NODE!"=="" set INSTALL_NODE=Y
    if /i "!INSTALL_NODE!"=="y" start https://nodejs.org/en/download
    echo   Download and run the installer, then re-run setup.bat
    pause
    exit /b 1
)

:: Check Node version
node -e "process.exit(parseInt(process.version.slice(1)) < 20 ? 1 : 0)"
if %errorlevel% neq 0 (
    echo   ! Node.js version too old - version 20+ required
    node -v
    start https://nodejs.org/en/download
    echo   Download the latest version, install it, then re-run setup.bat
    pause
    exit /b 1
)

for /f %%i in ('node -v') do echo   OK Node.js %%i

:: Git (optional)
set HAS_GIT=false
where git >nul 2>&1
if %errorlevel% equ 0 (
    set HAS_GIT=true
    echo   OK Git found
)

echo.

:: -- Step 2: Choose AI backend -------------------------------

echo Step 2 of 5 - Choose your AI backend
echo.
echo   Your agent needs an AI to think with. Pick one:
echo.
echo   1  Claude   - by Anthropic [recommended]
echo   2  Codex    - by OpenAI
echo   3  Gemini   - by Google
echo   4  Copilot  - by GitHub
echo   5  Gergy    - Direct API mode, supports multiple providers
echo.
echo   Options 1-4 use a CLI tool. Option 5 calls APIs directly.
echo.

set GERGY_MODE=false
set GERGY_PROVIDER=
set GERGY_API_KEY=
set SELECTED_CLI=claude
set CLI_PKG=@anthropic-ai/claude-code

set /p CLI_NUM="  Choose [1]: "
if "!CLI_NUM!"=="" set CLI_NUM=1

if "!CLI_NUM!"=="2" set SELECTED_CLI=codex& set CLI_PKG=@openai/codex
if "!CLI_NUM!"=="3" set SELECTED_CLI=gemini& set CLI_PKG=@google/gemini-cli
if "!CLI_NUM!"=="4" set SELECTED_CLI=copilot& set CLI_PKG=@github/copilot
if "!CLI_NUM!"=="5" set SELECTED_CLI=gergy& set CLI_PKG=& set GERGY_MODE=true

if not "!GERGY_MODE!"=="true" goto skip_gergy

echo.
echo   Choose your API provider:
echo.
echo   a  Anthropic  - Claude models [recommended]
echo   b  OpenAI     - GPT models
echo   c  xAI        - Grok models
echo   d  Gemini     - Google Gemini models
echo.

set GERGY_PROVIDER=anthropic
set KEY_URL=https://console.anthropic.com/settings/keys
set KEY_INSTRUCTIONS=Sign in or create an account, click 'Create Key', and copy it.

set /p PROVIDER_NUM="  Choose [a]: "
if "!PROVIDER_NUM!"=="" set PROVIDER_NUM=a

if /i "!PROVIDER_NUM!"=="b" set GERGY_PROVIDER=openai& set KEY_URL=https://platform.openai.com/api-keys& set KEY_INSTRUCTIONS=Sign in, click 'Create new secret key', and copy it.
if /i "!PROVIDER_NUM!"=="c" set GERGY_PROVIDER=xai& set KEY_URL=https://console.x.ai/team/default/api-keys& set KEY_INSTRUCTIONS=Sign in, click 'Create API Key', and copy it.
if /i "!PROVIDER_NUM!"=="d" set GERGY_PROVIDER=gemini& set KEY_URL=https://aistudio.google.com/apikey& set KEY_INSTRUCTIONS=Sign in with your Google account, click 'Create API key', and copy it.

echo.
echo   To use !GERGY_PROVIDER!, you need an API key.
echo.
echo   !KEY_INSTRUCTIONS!
echo.
set /p OPEN_KEY_URL="  Open the !GERGY_PROVIDER! key page in your browser? [Y]: "
if "!OPEN_KEY_URL!"=="" set OPEN_KEY_URL=Y
if /i "!OPEN_KEY_URL!"=="y" start "" "!KEY_URL!"
echo.
echo   Copy the key from the page, then paste it here.
echo.

:ask_api_key
set /p GERGY_API_KEY="  Paste your API key here: "
if "!GERGY_API_KEY!"=="" (
    echo.
    echo   An API key is required for the agent to work.
    echo   Go to: !KEY_URL!
    echo.
    goto ask_api_key
)
echo   OK API key saved

:skip_gergy

echo.

:: -- Step 3: Install AI CLI ----------------------------------

echo Step 3 of 5 - Install !SELECTED_CLI! CLI
echo.

if "!GERGY_MODE!"=="true" (
    echo   OK Gergy uses direct API calls - no CLI installation needed
    goto skip_cli_install
)

where !SELECTED_CLI! >nul 2>&1
if %errorlevel% equ 0 (
    echo   OK !SELECTED_CLI! CLI already installed
    goto skip_cli_install
)

echo   Installing !SELECTED_CLI! CLI via npm...
echo.
call npm install -g !CLI_PKG!
echo.
where !SELECTED_CLI! >nul 2>&1
if %errorlevel% equ 0 (
    echo   OK !SELECTED_CLI! CLI installed
) else (
    echo   X Failed to install !SELECTED_CLI! CLI
    echo.
    echo   Try manually: npm install -g !CLI_PKG!
    echo   Then re-run setup.bat
    pause
    exit /b 1
)

:skip_cli_install

echo.

:: -- Step 4: Authenticate ------------------------------------

echo Step 4 of 5 - Authenticate with !SELECTED_CLI!
echo.

if "!GERGY_MODE!"=="true" echo   OK Already set up with your API key& goto skip_auth
if "!SELECTED_CLI!"=="claude" goto auth_claude
if "!SELECTED_CLI!"=="codex" goto auth_codex
if "!SELECTED_CLI!"=="gemini" goto auth_gemini
if "!SELECTED_CLI!"=="copilot" goto auth_copilot
goto skip_auth

:auth_claude
echo   Claude requires a one-time login with your Anthropic account.
echo   A browser window will open - sign in or create a free account.
echo.
echo   If you already have a Claude account (claude.ai), use that!
echo.
echo   NOTE: Logging in opens an interactive CLI session.
echo   After authenticating, you will need to re-run setup.bat to finish setup.
echo.
set /p DO_AUTH="  Open Claude login now? [N]: "
if "!DO_AUTH!"=="" set DO_AUTH=N
if /i not "!DO_AUTH!"=="y" echo   Skipped. Run 'claude' later to authenticate.& goto skip_auth
echo.
echo   Launching Claude... once authenticated, type /exit then re-run setup.bat
echo.
claude 2>nul
echo.
echo   Please re-run setup.bat to complete setup.
pause
exit /b 0

:auth_codex
echo   Codex requires authentication with OpenAI.
echo   You can log in with your ChatGPT account or an API key.
echo.
echo   NOTE: Logging in opens an interactive session.
echo   After authenticating, you will need to re-run setup.bat to finish setup.
echo.
set /p DO_AUTH="  Run 'codex login' now? [N]: "
if "!DO_AUTH!"=="" set DO_AUTH=N
if /i not "!DO_AUTH!"=="y" echo   Skipped. Run 'codex login' later.& goto skip_auth
echo.
codex login 2>nul
echo.
echo   Please re-run setup.bat to complete setup.
pause
exit /b 0

:auth_gemini
echo   Gemini requires a Google account login.
echo   A browser window will open - sign in with your Google account.
echo.
echo   NOTE: Logging in opens an interactive CLI session.
echo   After authenticating, you will need to re-run setup.bat to finish setup.
echo.
set /p DO_AUTH="  Open Gemini login now? [N]: "
if "!DO_AUTH!"=="" set DO_AUTH=N
if /i not "!DO_AUTH!"=="y" echo   Skipped. Run 'gemini' later to authenticate.& goto skip_auth
echo.
echo   Launching Gemini... once authenticated, type /exit then re-run setup.bat
echo.
gemini 2>nul
echo.
echo   Please re-run setup.bat to complete setup.
pause
exit /b 0

:auth_copilot
echo   Copilot requires a GitHub account with an active Copilot subscription.
echo.
echo   NOTE: Logging in opens an interactive CLI session.
echo   After authenticating, you will need to re-run setup.bat to finish setup.
echo.
set /p DO_AUTH="  Open Copilot login now? [N]: "
if "!DO_AUTH!"=="" set DO_AUTH=N
if /i not "!DO_AUTH!"=="y" echo   Skipped. Run 'copilot' later, then type /login& goto skip_auth
echo.
echo   Launching Copilot... type /login, authenticate, then /exit and re-run setup.bat
echo.
copilot 2>nul
echo.
echo   Please re-run setup.bat to complete setup.
pause
exit /b 0

:skip_auth

echo.

:: -- Step 5: Configure and install ---------------------------

echo Step 5 of 5 - Configure your agent
echo.

set /p AGENT_NAME="  Give your agent a name [my-agent]: "
if "!AGENT_NAME!"=="" set AGENT_NAME=my-agent

set /p PORT="  Web UI port [4000]: "
if "!PORT!"=="" set PORT=4000

echo.
echo   Installing dependencies...
call npm install
echo.

echo   Writing configuration...

:: Generate auth token
for /f %%i in ('node -e "console.log(require('crypto').randomBytes(24).toString('hex'))"') do set AUTH_TOKEN=%%i
set WORKSPACE_ROOT=!CD!\workspaces
node -e "const fs=require('fs');const cfg={cli:process.env.SELECTED_CLI||'claude',port:Number(process.env.PORT)||4000,loopMinutes:5,compactThreshold:40,compactKeepRecent:10,agentName:process.env.AGENT_NAME||'my-agent',workspaceRoot:process.env.WORKSPACE_ROOT,models:{},maxUserTaskConcurrency:2,autonomyActiveChatPauseMs:180000,dailyBudget:null,authToken:process.env.AUTH_TOKEN,activeWorkspace:'default',workspaces:{},ingestion:{enabled:true,maxConcurrent:2},cognitive:{plannerEnabled:true,reflectorEnabled:true,reflectorInterval:6,thinkerDepth:'balanced'},multimodal:{sttEnabled:false,ttsEnabled:false,visionEnabled:false},kgEnabled:true,voice:{enabled:false,wakeWords:['gergy'],sensitivity:0.5,nativeMode:true,browserMode:true},agentic:{provider:process.env.GERGY_MODE==='true'?(process.env.GERGY_PROVIDER||'anthropic'):null,apiKey:process.env.GERGY_API_KEY||null,baseUrl:null,maxTurns:50,maxTokens:16384}};fs.writeFileSync('config.json',JSON.stringify(cfg,null,2)+'\n');"

echo   OK config.json created

:: Create directories
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
echo   OK Directories created

:: Git init
if not "!HAS_GIT!"=="true" goto skip_git
if exist .git goto skip_git
git init -q
(
echo node_modules/
echo *.db
echo *.db-wal
echo *.db-shm
echo .heartbeat
echo agent.log
echo watchdog.log
echo site/
echo workspace/
echo workspaces/
echo .claude/settings.local.json
echo config.json
echo vendor/
echo data/wake-word-models/*.onnx
echo evolution.yaml
echo journal.md
echo wake-state.md
) > .gitignore
git add -A
git commit -q -m "Initial agent setup"
echo   OK Git repository initialized

:skip_git

echo.
echo   ========================================
echo   Setup complete!
echo   ========================================
echo.
echo   Web UI:  http://localhost:!PORT!?token=!AUTH_TOKEN!
echo.
echo   Other commands:
echo     npm start       - Launch desktop app
echo     npm run server  - Run server only (no desktop)
echo     update.bat      - Check for updates
echo.
echo   Have fun! Your agent is ready to think.
echo.
echo   Launching your agent...
echo.
npm start
