# ZeroGravity — Windows setup
# Creates config directories, builds the release binary, and optionally
# installs as a scheduled task for automatic startup.
# Run as: powershell -ExecutionPolicy Bypass -File scripts\setup-windows.ps1

$ErrorActionPreference = "Stop"
$ProjectDir = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if (-not $ProjectDir) { $ProjectDir = (Get-Location).Path }

# ── 1. Config directory ──
Write-Host "→ Setting up config directory…"
$ConfigDir = Join-Path $env:APPDATA "zerogravity"
New-Item -ItemType Directory -Force -Path $ConfigDir | Out-Null
Write-Host "  $ConfigDir"

# ── 2. Data directory ──
Write-Host "→ Setting up data directory…"
$DataDir = Join-Path $env:TEMP "zerogravity-standalone"
New-Item -ItemType Directory -Force -Path $DataDir | Out-Null
Write-Host "  $DataDir"

# ── 3. Build ──
Write-Host "→ Building release binary…"
Push-Location $ProjectDir
cargo build --release
Pop-Location

$Binary = Join-Path $ProjectDir "target\release\zerogravity.exe"
if (-not (Test-Path $Binary)) {
    Write-Error "Build failed — $Binary not found"
    exit 1
}
Write-Host "  Built: $Binary"

# ── 4. Scheduled task (optional) ──
$TaskName = "ZeroGravity Proxy"
$Existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue

if ($Existing) {
    Write-Host "→ Scheduled task '$TaskName' already exists. Updating…"
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}

Write-Host "→ Creating scheduled task '$TaskName'…"
$Action = New-ScheduledTaskAction `
    -Execute $Binary `
    -WorkingDirectory $ProjectDir

$Trigger = New-ScheduledTaskTrigger -AtLogOn
$Settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -RestartCount 3 `
    -RestartInterval (New-TimeSpan -Minutes 1)

Register-ScheduledTask `
    -TaskName $TaskName `
    -Action $Action `
    -Trigger $Trigger `
    -Settings $Settings `
    -Description "ZeroGravity OpenAI-compatible proxy" | Out-Null

Write-Host "  Installed as logon task."
Write-Host ""
Write-Host "✓ Setup complete."
Write-Host "  Start now:  schtasks /run /tn '$TaskName'"
Write-Host "  Stop:       schtasks /end /tn '$TaskName'"
Write-Host "  Or manually: .\target\release\zerogravity.exe"
