$ErrorActionPreference = "Stop"
$ProjectRoot = $PSScriptRoot
$LogDir = Join-Path $ProjectRoot "log"

if (-not (Test-Path $LogDir)) {
    New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
}

if (Test-Path (Join-Path $ProjectRoot ".env")) {
    Write-Host "Loading environment variables from .env"
    Get-Content (Join-Path $ProjectRoot ".env") | Where-Object { $_ -match "^[^#]" -and $_ -match "=" } | ForEach-Object {
        $name, $value = $_.Split("=", 2)
        [System.Environment]::SetEnvironmentVariable($name, $value)
    }
}

Write-Host "=========================================="
Write-Host "Cleaning up existing processes..."
Write-Host "=========================================="
foreach ($port in 9331, 9332, 9333) {
    $netstat = netstat -ano | Select-String "LISTENING" | Select-String ":$port"
    if ($netstat) {
        foreach ($line in $netstat) {
            $parts = $line -split '\s+'
            $pidToKill = $parts[-1]
            if ($pidToKill -and $pidToKill -ne "0") {
                Write-Host "Killing process on port $port (PID: $pidToKill)..."
                Stop-Process -Id $pidToKill -Force -ErrorAction SilentlyContinue
            }
        }
    }
}

Get-WmiObject Win32_Process | Where-Object { $_.CommandLine -like "*nodemon*$ProjectRoot*" } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Get-WmiObject Win32_Process | Where-Object { $_.CommandLine -like "*MavenWrapperMain*$ProjectRoot*" } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }


Write-Host "=========================================="
Write-Host "Starting Loyalty Agent Services"
Write-Host "=========================================="

# 1. Start MCP Server
Write-Host "Starting loyalty-mcp-server..."
$mcpLog = Join-Path $LogDir "loyalty-mcp-server.log"
$mcpProcess = Start-Process -FilePath "cmd.exe" -ArgumentList "/c ..\mvnw.cmd spring-boot:run -Dmaven.test.skip=true > `"$mcpLog`" 2>&1" -WorkingDirectory (Join-Path $ProjectRoot "loyalty-mcp-server") -PassThru -WindowStyle Hidden
Write-Host "loyalty-mcp-server started with PID: $($mcpProcess.Id)"

Write-Host "Waiting for loyalty-mcp-server to initialize..."
while ($true) {
    $netstat = netstat -ano | Select-String "LISTENING" | Select-String ":9331"
    if ($netstat) { break }
    Start-Sleep -Seconds 2
}
Write-Host "loyalty-mcp-server is up!"

# 2. Start Agent Service
Write-Host "Starting loyalty-agent..."
$agentLog = Join-Path $LogDir "loyalty-agent.log"
$agentProcess = Start-Process -FilePath "cmd.exe" -ArgumentList "/c ..\mvnw.cmd spring-boot:run -Dmaven.test.skip=true > `"$agentLog`" 2>&1" -WorkingDirectory (Join-Path $ProjectRoot "loyalty-agent") -PassThru -WindowStyle Hidden
Write-Host "loyalty-agent started with PID: $($agentProcess.Id)"

Write-Host "Waiting for loyalty-agent to initialize..."
while ($true) {
    $netstat = netstat -ano | Select-String "LISTENING" | Select-String ":9332"
    if ($netstat) { break }
    Start-Sleep -Seconds 2
}
Write-Host "loyalty-agent is up!"

# 3. Start Frontend UI
Write-Host "Starting Frontend UI..."
$uiLog = Join-Path $LogDir "frontend.log"
$uiProcess = Start-Process -FilePath "cmd.exe" -ArgumentList "/c pnpm dev > `"$uiLog`" 2>&1" -WorkingDirectory $ProjectRoot -PassThru -WindowStyle Hidden
Write-Host "Frontend UI started with PID: $($uiProcess.Id)"

Write-Host "=========================================="
Write-Host "All services started successfully!"
Write-Host "Log files are stored in: $LogDir"
Write-Host "- $mcpLog"
Write-Host "- $agentLog"
Write-Host "- $uiLog"
Write-Host "=========================================="

