# PicoBot Gateway management script
param(
    [ValidateSet("start", "stop", "status")]
    [string]$Action = "start",
    [int]$Port = 19876
)

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$ExePaths = @(
    "$ScriptDir\picobot.exe",                          # distribution: same dir
    "$ScriptDir\..\..\target\release\picobot.exe",     # dev: release build
    "$ScriptDir\..\..\target\debug\picobot.exe"        # dev: debug build
)
$Exe = $ExePaths | Where-Object { Test-Path $_ } | Select-Object -First 1

if (-not $Exe) {
    Write-Host "[ERROR] picobot.exe not found. Build first: cargo build --release" -ForegroundColor Red
    exit 1
}

Write-Host "[INFO] exe: $Exe" -ForegroundColor Gray

switch ($Action) {
    "start" {
        $existing = Get-Process -Name "picobot" -ErrorAction SilentlyContinue
        if ($existing) {
            Write-Host "[WARN] picobot already running (PID: $($existing.Id))" -ForegroundColor Yellow
            exit 0
        }

        $proc = Start-Process -FilePath $Exe `
            -ArgumentList "gateway", "--port", $Port `
            -WindowStyle Hidden `
            -PassThru

        Start-Sleep -Seconds 1
        if (-not $proc.HasExited) {
            Write-Host "[OK] Gateway started (PID: $($proc.Id))" -ForegroundColor Green
            Write-Host "     URL: http://127.0.0.1:$Port" -ForegroundColor Gray
            Write-Host "     WebSocket: ws://127.0.0.1:$Port/ws" -ForegroundColor Gray
        } else {
            Write-Host "[ERROR] Gateway failed to start (exit code: $($proc.ExitCode))" -ForegroundColor Red
        }
    }
    "stop" {
        $procs = Get-Process -Name "picobot" -ErrorAction SilentlyContinue
        if (-not $procs) {
            Write-Host "[INFO] picobot is not running" -ForegroundColor Gray
            exit 0
        }
        $procs | ForEach-Object {
            Write-Host "[INFO] Stopping picobot (PID: $($_.Id))" -ForegroundColor Yellow
            $_.Kill()
        }
        Write-Host "[OK] Stopped" -ForegroundColor Green
    }
    "status" {
        $procs = Get-Process -Name "picobot" -ErrorAction SilentlyContinue
        if ($procs) {
            $procs | ForEach-Object {
                Write-Host "[RUNNING] picobot (PID: $($_.Id), Mem: $([math]::Round($_.WorkingSet64/1MB, 1))MB)" -ForegroundColor Green
            }
        } else {
            Write-Host "[STOPPED] picobot is not running" -ForegroundColor Gray
        }
    }
}
