@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/n) [Y]: "
    if "!INSTALL_NODE!"=="" set INSTALL_NODE=Y
    if /i "!INSTALL_NODE!"=="y" (
        echo.
        echo   Opening Node.js download page...
        echo   Download and run the installer, then re-run setup.bat
        echo.
        start https://nodejs.org/en/download
        echo   After installing Node.js, close this window and run setup.bat again.
        pause
        exit /b 1
    ) else (
        echo   Please install Node.js 20+ from https://nodejs.org and 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
    echo   Current version:
    node -v
    echo.
    echo   Opening Node.js download page...
    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, best creative output)
echo   2) Codex    - by OpenAI (GPT-powered)
echo   3) Gemini   - by Google
echo   4) Copilot  - by GitHub (uses your GitHub Copilot subscription)
echo.
echo   All four are free to start with (just need an account).
echo.

set /p CLI_NUM="  Choose (1/2/3/4) [1]: "
if "!CLI_NUM!"=="" set CLI_NUM=1

if "!CLI_NUM!"=="2" (
    set SELECTED_CLI=codex
    set CLI_PKG=@openai/codex
) else if "!CLI_NUM!"=="3" (
    set SELECTED_CLI=gemini
    set CLI_PKG=@google/gemini-cli
) else if "!CLI_NUM!"=="4" (
    set SELECTED_CLI=copilot
    set CLI_PKG=@github/copilot
) else (
    set SELECTED_CLI=claude
    set CLI_PKG=@anthropic-ai/claude-code
)

echo.

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

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

where !SELECTED_CLI! >nul 2>&1
if %errorlevel% equ 0 (
    echo   OK !SELECTED_CLI! CLI already installed
) else (
    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
    )
)

echo.

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

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

if "!SELECTED_CLI!"=="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.
    set /p DO_AUTH="  Open Claude login now? (Y/n) [Y]: "
    if "!DO_AUTH!"=="" set DO_AUTH=Y
    if /i "!DO_AUTH!"=="y" (
        echo.
        echo   Launching Claude... (once authenticated, type /exit to continue^)
        echo.
        claude 2>nul || echo   (Claude will authenticate on first real use^)
        echo.
    ) else (
        echo   Skipped. You can authenticate later by running: claude
    )
)

if "!SELECTED_CLI!"=="codex" (
    echo   Codex requires authentication with OpenAI.
    echo   You can log in with your ChatGPT account or an API key.
    echo.
    echo   If you have a ChatGPT account (chatgpt.com^), you can use that!
    echo.
    set /p DO_AUTH="  Run 'codex login' now? (Y/n) [Y]: "
    if "!DO_AUTH!"=="" set DO_AUTH=Y
    if /i "!DO_AUTH!"=="y" (
        echo.
        codex login 2>nul || echo   (Codex will authenticate on first real use^)
        echo.
    ) else (
        echo   Skipped. You can authenticate later by running: codex login
    )
)

if "!SELECTED_CLI!"=="gemini" (
    echo   Gemini requires a Google account login.
    echo   A browser window will open - sign in with your Google account.
    echo.
    echo   Any Google account works (Gmail, Workspace, etc^).
    echo.
    set /p DO_AUTH="  Open Gemini login now? (Y/n) [Y]: "
    if "!DO_AUTH!"=="" set DO_AUTH=Y
    if /i "!DO_AUTH!"=="y" (
        echo.
        echo   Launching Gemini... (once authenticated, type /exit to continue^)
        echo.
        gemini 2>nul || echo   (Gemini will authenticate on first real use^)
        echo.
    ) else (
        echo   Skipped. You can authenticate later by running: gemini
    )
)

if "!SELECTED_CLI!"=="copilot" (
    echo   Copilot requires a GitHub account with an active Copilot subscription.
    echo   (Copilot Individual, Business, or Enterprise^)
    echo.
    echo   A browser window will open - sign in with your GitHub account.
    echo.
    set /p DO_AUTH="  Open Copilot login now? (Y/n) [Y]: "
    if "!DO_AUTH!"=="" set DO_AUTH=Y
    if /i "!DO_AUTH!"=="y" (
        echo.
        echo   Launching Copilot... (type /login, authenticate, then /exit to continue^)
        echo.
        copilot 2>nul || echo   (Copilot will authenticate on first real use^)
        echo.
    ) else (
        echo   Skipped. You can authenticate later by running: copilot
        echo   (then type /login inside the CLI^)
    )
)

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}};fs.writeFileSync('config.json',JSON.stringify(cfg,null,2)+'\n');"

echo   OK config.json created (using tier defaults^)

:: 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 "!HAS_GIT!"=="true" (
    if not exist .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
    )
)

echo.
echo   ========================================
echo   Setup complete!
echo   ========================================
echo.
echo   Web UI:  http://localhost:!PORT!?token=!AUTH_TOKEN!
echo.
echo   Other commands:
echo     update.bat  - Check for updates
echo.
echo   Have fun! Your agent is ready to think.
echo.

set /p START_NOW="  Start your agent now? (Y/n) [Y]: "
if "!START_NOW!"=="" set START_NOW=Y
if /i "!START_NOW!"=="y" (
    echo.
    echo   Starting agent...
    echo.
    npm start
) else (
    echo.
    echo   To start later, run: npm start
    echo.
    pause
)
