# Start Local Development Servers
# This script starts the backend and frontend services

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

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Starting Institutional Trader Services" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Check if Node.js is available
try {
    $nodeVersion = node --version 2>&1
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ Node.js: $nodeVersion" -ForegroundColor Green
    } else {
        throw "Node.js not found"
    }
} catch {
    Write-Host "✗ Node.js not found. Please install Node.js first." -ForegroundColor Red
    exit 1
}

# Start Backend
Write-Host ""
Write-Host "Starting Backend (port 3010)..." -ForegroundColor Yellow
$backendJob = Start-Job -ScriptBlock {
    Set-Location $using:scriptPath
    Set-Location backend
    npm run dev
}

# Start Frontend  
Write-Host "Starting Frontend (port 5010)..." -ForegroundColor Yellow
$frontendJob = Start-Job -ScriptBlock {
    Set-Location $using:scriptPath
    Set-Location frontend
    npm run dev
}

# Wait a bit for services to start
Start-Sleep -Seconds 5

# Check if services are running
Write-Host ""
Write-Host "Checking service status..." -ForegroundColor Yellow
$backendPort = Get-NetTCPConnection -LocalPort 3010 -ErrorAction SilentlyContinue
$frontendPort = Get-NetTCPConnection -LocalPort 5010 -ErrorAction SilentlyContinue

if ($backendPort) {
    Write-Host "✓ Backend is running on http://localhost:3010" -ForegroundColor Green
} else {
    Write-Host "✗ Backend not detected on port 3010" -ForegroundColor Yellow
    Write-Host "  Check backend job output for errors" -ForegroundColor Gray
}

if ($frontendPort) {
    Write-Host "✓ Frontend is running on http://localhost:5010" -ForegroundColor Green
} else {
    Write-Host "✗ Frontend not detected on port 5010" -ForegroundColor Yellow
    Write-Host "  Check frontend job output for errors" -ForegroundColor Gray
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Services started in background jobs" -ForegroundColor Cyan
Write-Host ""
Write-Host "To view logs:" -ForegroundColor Yellow
Write-Host "  Receive-Job -Id $($backendJob.Id)  # Backend logs" -ForegroundColor White
Write-Host "  Receive-Job -Id $($frontendJob.Id)  # Frontend logs" -ForegroundColor White
Write-Host ""
Write-Host "To stop services:" -ForegroundColor Yellow
Write-Host "  Stop-Job -Id $($backendJob.Id), $($frontendJob.Id)" -ForegroundColor White
Write-Host "  Remove-Job -Id $($backendJob.Id), $($frontendJob.Id)" -ForegroundColor White
Write-Host "========================================" -ForegroundColor Cyan

