# QwenClaw Full Installation Script (Windows PowerShell)
# 
# Usage: .\install.ps1

$ErrorActionPreference = "Stop"

# Colors
function Write-Color {
    param([string]$Text, [string]$Color)
    Write-Host $Text -ForegroundColor $Color
}

Write-Host ""
Write-Color "  ____                _      __ _ _           " "Cyan"
Write-Color " / ___|_ __ __ _  ___| | __ / _(_) | ___      " "Cyan"
Write-Color "| |   | '__/ _` |/ __| |/ /| |_| | |/ _ \     " "Cyan"
Write-Color " \____|_|  \__,_|\___|_|\_\|_| |_|_|\___|     " "Cyan"
Write-Host ""
Write-Color "Windows Installation Script" "Cyan"
Write-Host "============================="
Write-Host ""

$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $SCRIPT_DIR

$QWEN_DIR = Join-Path $env:USERPROFILE ".qwen"
$QWENCLAW_DATA_DIR = Join-Path $QWEN_DIR "qwenclaw"

# Step 1: Check prerequisites
Write-Color "[1/6] Checking prerequisites..." "Yellow"

# Check Git
try {
    $gitVersion = git --version 2>&1
    Write-Host "[OK] Git is installed" -ForegroundColor Green
} catch {
    Write-Host "[ERROR] Git is not installed. Install from: https://git-scm.com" -ForegroundColor Red
    exit 1
}

# Check Bun
try {
    $bunVersion = bun --version 2>&1
    Write-Host "[OK] Bun is installed (v$bunVersion)" -ForegroundColor Green
} catch {
    Write-Host "[INFO] Bun is not installed. Installing..." -ForegroundColor Yellow
    try {
        powershell -c "irm bun.sh/install.ps1 | iex"
        $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
        $bunVersion = bun --version 2>&1
        Write-Host "[OK] Bun installed successfully (v$bunVersion)" -ForegroundColor Green
    } catch {
        Write-Host "[ERROR] Failed to install Bun. Install manually from: https://bun.sh" -ForegroundColor Red
        exit 1
    }
}

# Step 2: Install dependencies
Write-Host ""
Write-Color "[2/6] Installing dependencies..." "Yellow"
bun install
Write-Host "[OK] Dependencies installed" -ForegroundColor Green

# Step 3: Create directories
Write-Host ""
Write-Color "[3/6] Creating directories..." "Yellow"

$dirs = @(
    $QWENCLAW_DATA_DIR,
    (Join-Path $QWENCLAW_DATA_DIR "jobs"),
    (Join-Path $QWENCLAW_DATA_DIR "logs"),
    (Join-Path $QWENCLAW_DATA_DIR "inbox"),
    (Join-Path $QWENCLAW_DATA_DIR "inbox\telegram")
)

foreach ($dir in $dirs) {
    if (-not (Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir -Force | Out-Null
        Write-Host "      Created: $dir" -ForegroundColor Green
    }
}

# Step 4: Create default settings
Write-Host ""
Write-Color "[4/6] Creating default configuration..." "Yellow"

$SETTINGS_FILE = Join-Path $QWENCLAW_DATA_DIR "settings.json"
if (-not (Test-Path $SETTINGS_FILE)) {
    $settings = @{
        model = ""
        api = ""
        autoStart = $true
        fallback = @{
            model = ""
            api = ""
        }
        timezone = "UTC"
        timezoneOffsetMinutes = 0
        heartbeat = @{
            enabled = $false
            interval = 15
            prompt = ""
            excludeWindows = @()
        }
        telegram = @{
            token = ""
            allowedUserIds = @()
        }
        security = @{
            level = "moderate"
            allowedTools = @()
            disallowedTools = @()
        }
        web = @{
            enabled = $true
            host = "127.0.0.1"
            port = 4632
        }
    }
    
    $settings | ConvertTo-Json -Depth 10 | Out-File -FilePath $SETTINGS_FILE -Encoding utf8
    Write-Host "[OK] Default settings created: $SETTINGS_FILE" -ForegroundColor Green
} else {
    Write-Host "[INFO] Settings already exist, skipping" -ForegroundColor Yellow
}

# Step 5: Set up auto-start
Write-Host ""
Write-Color "[5/6] Configuring Windows auto-start..." "Yellow"

$STARTUP_FOLDER = [Environment]::GetFolderPath("Startup")
$STARTUP_BAT = Join-Path $STARTUP_FOLDER "QwenClaw Daemon.bat"

# Create startup batch file
$startupContent = @"
@echo off
cd /d "$SCRIPT_DIR"
start /B bun run start --web
"@

$startupContent | Out-File -FilePath $STARTUP_BAT -Encoding ASCII
Write-Host "[OK] Windows auto-start configured" -ForegroundColor Green

# Step 6: Initialize git
Write-Host ""
Write-Color "[6/6] Finalizing installation..." "Yellow"

if (-not (Test-Path ".git")) {
    git init | Out-Null
    git checkout -b main 2>$null | Out-Null
    Write-Host "[OK] Git repository initialized" -ForegroundColor Green
} else {
    Write-Host "[INFO] Git repository already exists" -ForegroundColor Yellow
}

# Create example job
$EXAMPLE_JOB = Join-Path $QWENCLAW_DATA_DIR "jobs\example-daily-check.md"
if (-not (Test-Path $EXAMPLE_JOB)) {
    $jobContent = @"
---
schedule: 0 9 * * *
recurring: true
notify: true
---

Good morning! Here's your daily check-in:
1. What are today's priorities?
2. Any pending tasks from yesterday?
3. Weather and calendar summary.
"@
    $jobContent | Out-File -FilePath $EXAMPLE_JOB -Encoding utf8
    Write-Host "[OK] Example job created" -ForegroundColor Green
}

# Summary
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "  Installation Complete!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Color "What's configured:" "Cyan"
Write-Host "  [OK] Dependencies installed" -ForegroundColor Green
Write-Host "  [OK] Directories created" -ForegroundColor Green
Write-Host "  [OK] Default settings created" -ForegroundColor Green
Write-Host "  [OK] Windows auto-start configured" -ForegroundColor Green
Write-Host "  [OK] Example job created" -ForegroundColor Green
Write-Host ""
Write-Color "Quick Start:" "Cyan"
Write-Host "  bun run start --web     - Start daemon" -ForegroundColor White
Write-Host "  bun run status          - Check status" -ForegroundColor White
Write-Host "  bun run stop            - Stop daemon" -ForegroundColor White
Write-Host "  bun run send 'hello'    - Send prompt" -ForegroundColor White
Write-Host ""
Write-Color "Web Dashboard:" "Cyan"
Write-Host "  http://127.0.0.1:4632" -ForegroundColor White
Write-Host ""
Write-Color "Configuration:" "Cyan"
Write-Host "  Edit: $SETTINGS_FILE" -ForegroundColor Yellow
Write-Host "  Jobs: $QWENCLAW_DATA_DIR\jobs\" -ForegroundColor Yellow
Write-Host "  Logs: $QWENCLAW_DATA_DIR\logs\" -ForegroundColor Yellow
Write-Host ""
Write-Color "Documentation:" "Cyan"
Write-Host "  README.md      - Full documentation" -ForegroundColor White
Write-Host "  QUICKSTART.md  - Quick reference" -ForegroundColor White
Write-Host ""
Write-Host "The daemon will start automatically when you log in to Windows." -ForegroundColor Green
Write-Host ""
