# Start-Dev.ps1 - Windows equivalent of start-go.sh

Write-Host "Starting Antigravity (Windows Mode)..." -ForegroundColor Green

# 1. Kill existing backend on port 36969 if running
$port = 36969
$process = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique
if ($process) {
    Write-Host "Killing existing backend process (PID: $process)..." -ForegroundColor Yellow
    Stop-Process -Id $process -Force -ErrorAction SilentlyContinue
}

# 2. Check for Go
if (-not (Get-Command "go" -ErrorAction SilentlyContinue)) {
    Write-Host "Go is not installed or not in PATH." -ForegroundColor Red
    exit 1
}

# 3. Check for pnpm or fallback
$pkgManager = "pnpm"
if (-not (Get-Command "pnpm" -ErrorAction SilentlyContinue)) {
    if (Get-Command "npm" -ErrorAction SilentlyContinue) {
        $pkgManager = "npm"
    }
    else {
        Write-Host "pnpm/npm not found." -ForegroundColor Red
        exit 1
    }
}

# 4. Start Backend in background
Write-Host "Starting Go Backend..." -ForegroundColor Cyan
$env:APP_ENV = "development"
$backendJob = Start-Process -FilePath "go" -ArgumentList "run backend/main.go" -NoNewWindow -PassThru
Write-Host "Backend started (Simple PID: $($backendJob.Id))" -ForegroundColor Gray

# 5. Start Frontend
Write-Host "Checking dependencies..." -ForegroundColor Cyan
if (-not (Test-Path "node_modules\.bin\vite.ps1") -and -not (Test-Path "node_modules\.bin\vite.cmd")) {
    Write-Host "Dependencies missing. Running install..." -ForegroundColor Yellow
    if ($pkgManager -eq "pnpm") {
        pnpm install
    }
    else {
        npm install
    }
}

Write-Host "Starting Frontend ($pkgManager run dev)..." -ForegroundColor Cyan
if ($pkgManager -eq "pnpm") {
    pnpm run dev
}
else {
    npm run dev
}
