# AgntSpace installer for Windows
# Usage: irm https://www.agntspace.com/install.ps1 | iex

Write-Host ""
Write-Host "  AGNTSPACE - Your AI partner" -ForegroundColor Cyan
Write-Host ""

# Step 1: Find Python 3.11+
Write-Host "  [1/3] Checking Python..." -ForegroundColor White -NoNewline
$pyCmd = $null
foreach ($cmd in @("python", "python3")) {
    try {
        $out = (& $cmd --version 2>&1) | Out-String
        if ($out -match "(\d+)\.(\d+)") {
            if ([int]$Matches[1] -ge 3 -and [int]$Matches[2] -ge 11) {
                $pyCmd = $cmd; break
            }
        }
    } catch {}
}
if (-not $pyCmd) {
    Write-Host " MISSING" -ForegroundColor Red
    Write-Host ""
    Write-Host "  Python 3.11+ required: https://www.python.org/downloads/" -ForegroundColor Yellow
    Write-Host ""; return
}
$pyVer = (& $pyCmd --version 2>&1) | Out-String
Write-Host " $($pyVer.Trim())" -ForegroundColor Green

# Step 2: Install
Write-Host "  [2/3] Installing agntspace..." -ForegroundColor White -NoNewline
& $pyCmd -m pip install --upgrade --quiet agntspace 2>&1 | Out-Null

# Verify module is importable
$installed = $false
try {
    $check = & $pyCmd -c "import agntspace; print('ok')" 2>&1 | Out-String
    if ($check -match "ok") { $installed = $true }
} catch {}
if (-not $installed) {
    Write-Host " FAILED" -ForegroundColor Red
    Write-Host ""
    Write-Host "  pip install failed. Check your internet connection and that" -ForegroundColor Yellow
    Write-Host "  pip is up to date:" -ForegroundColor Yellow
    Write-Host "    $pyCmd -m pip install --upgrade pip" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "  For help: https://agntspace.com" -ForegroundColor Yellow
    Write-Host ""; return
}
Write-Host " OK" -ForegroundColor Green

# Step 3: Initialize
Write-Host "  [3/3] Initializing..." -ForegroundColor White -NoNewline
& $pyCmd -m agntspace.cli init --minimal 2>&1 | Out-Null
Write-Host " OK" -ForegroundColor Green

# Create a launcher script in a PATH-friendly location
$launcherDir = Join-Path $env:LOCALAPPDATA "AgntSpace"
$launcher = Join-Path $launcherDir "agntspace.cmd"
if (-not (Test-Path $launcherDir)) { New-Item -ItemType Directory -Path $launcherDir -Force | Out-Null }
Set-Content -Path $launcher -Value "@echo off`r`n$pyCmd -m agntspace.cli %*" -Force

if ($env:PATH -notlike "*$launcherDir*") {
    $env:PATH = "$launcherDir;$env:PATH"
}

Write-Host ""
Write-Host "  Ready! Run:" -ForegroundColor Green
Write-Host "    agntspace start" -ForegroundColor Cyan
Write-Host "  Then open http://localhost:8000" -ForegroundColor Gray
Write-Host ""
