param(
    [switch]$Force = $false
)

$ErrorActionPreference = "Stop"

Write-Host "====================================" -ForegroundColor Cyan
Write-Host "  Hua.Todo.Web Restart Script" -ForegroundColor Cyan
Write-Host "====================================" -ForegroundColor Cyan
Write-Host ""

$webProjectPath = Join-Path $PSScriptRoot "src\Hua.Todo.Web"

if (!(Test-Path $webProjectPath)) {
    Write-Host "ERROR: Web project path not found: $webProjectPath" -ForegroundColor Red
    exit 1
}

function Get-Hua.TodoWebProcesses {
    param(
        [Parameter(Mandatory = $true)]
        [string]$WebProjectPath
    )

    Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {
        $_.CommandLine -and
        $_.CommandLine -like "*vite*" -and
        $_.CommandLine -like "*$WebProjectPath*"
    }
}

Write-Host "[1/3] Stopping existing service..." -ForegroundColor Yellow

$webProcesses = @(Get-Hua.TodoWebProcesses -WebProjectPath $webProjectPath)

if ($webProcesses.Count -eq 0) {
    Write-Host "OK: Hua.Todo.Web is not running" -ForegroundColor Green
} else {
    Write-Host "Found $($webProcesses.Count) process(es)" -ForegroundColor Yellow
    foreach ($process in $webProcesses) {
        $processId = $process.ProcessId
        Write-Host "Stopping PID: $processId" -ForegroundColor Gray
        try {
            Stop-Process -Id $processId -Force:$Force -ErrorAction Stop
            Write-Host "OK: Stopped PID: $processId" -ForegroundColor Green
        } catch {
            Write-Host "WARN: Failed to stop PID: $processId. $_" -ForegroundColor Yellow
        }
    }
}

Write-Host ""
Write-Host "[2/3] Waiting for processes to exit..." -ForegroundColor Yellow

$timeout = 10
$elapsed = 0

while ($elapsed -lt $timeout) {
    $webRunning = @(Get-Hua.TodoWebProcesses -WebProjectPath $webProjectPath)

    if ($webRunning.Count -eq 0) {
        Write-Host "OK: All processes exited" -ForegroundColor Green
        break
    }

    Start-Sleep -Seconds 1
    $elapsed++

    if ($elapsed -lt $timeout) {
        Write-Host "Waiting... ($elapsed/$timeout sec)" -ForegroundColor Gray
    }
}

if ($elapsed -ge $timeout) {
    Write-Host "WARN: Timeout reached, continuing to start..." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "[3/3] Starting service..." -ForegroundColor Yellow

try {
    Write-Host "Working directory: $webProjectPath" -ForegroundColor Gray
    Write-Host "Running: npm run dev" -ForegroundColor Green

    $webProcess = Start-Process -FilePath "npm.cmd" -ArgumentList @("run", "dev") -WorkingDirectory $webProjectPath -PassThru

    Write-Host "OK: Started Hua.Todo.Web" -ForegroundColor Green
    Write-Host "PID: $($webProcess.Id)" -ForegroundColor Gray
} catch {
    Write-Host "ERROR: Failed to start service. $_" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "====================================" -ForegroundColor Cyan
Write-Host "  Done" -ForegroundColor Green
Write-Host "====================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Notes:" -ForegroundColor Yellow
Write-Host "  - Vite will choose an available port automatically (no explicit port required)" -ForegroundColor Gray
Write-Host "  - Check the npm/vite output for the Local URL" -ForegroundColor Gray
