param(
    [switch]$Force = $false
)

$ErrorActionPreference = "Stop"

Write-Host "====================================" -ForegroundColor Cyan
Write-Host "  Hua.Todo.Web 启动脚本" -ForegroundColor Cyan
Write-Host "====================================" -ForegroundColor Cyan
Write-Host ""

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

Write-Host "[1/2] 检查 Hua.Todo.Web 服务..." -ForegroundColor Yellow

$webProcess = Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like "*vite*" -or $_.CommandLine -like "*Hua.Todo.Web*" }

if ($webProcess) {
    Write-Host "⚠️  Hua.Todo.Web 服务已经在运行中" -ForegroundColor Yellow
    Write-Host "   进程 ID: ($($webProcess.ProcessId))" -ForegroundColor Gray
    
    if ($Force) {
        Write-Host ""
        Write-Host "🔄 强制重启..." -ForegroundColor Yellow
        try {
            Stop-Process -Id $webProcess.ProcessId -Force -ErrorAction Stop
            Write-Host "✅ 旧进程已停止" -ForegroundColor Green
            Start-Sleep -Seconds 1
        } catch {
            Write-Host "❌ 停止进程失败: $_" -ForegroundColor Red
            exit 1
        }
    } else {
        Write-Host "   如果需要重新启动，请使用 -Force 参数" -ForegroundColor Gray
        Write-Host ""
        Write-Host "====================================" -ForegroundColor Cyan
        Write-Host "  已在运行" -ForegroundColor Green
        Write-Host "====================================" -ForegroundColor Cyan
        Write-Host ""
        Write-Host "💡 访问地址:" -ForegroundColor Yellow
        Write-Host "   http://localhost:5174" -ForegroundColor Cyan
        Write-Host ""
        exit 0
    }
} else {
    Write-Host "✓ Hua.Todo.Web 服务未运行" -ForegroundColor Green
    Write-Host ""
}

Write-Host "[2/2] 启动 Hua.Todo.Web 服务..." -ForegroundColor Yellow

if (!(Test-Path $webProjectPath)) {
    Write-Host "❌ Web 项目路径不存在: $webProjectPath" -ForegroundColor Red
    exit 1
}

Write-Host "📂 工作目录: $webProjectPath" -ForegroundColor Gray
Write-Host "🚀 启动服务..." -ForegroundColor Green

try {
    $webProcess = Start-Process -FilePath "npm.cmd" -ArgumentList "run", "dev" -WorkingDirectory $webProjectPath -PassThru
    
    Write-Host "✅ Hua.Todo.Web 服务已启动" -ForegroundColor Green
    Write-Host "   进程 ID: ($($webProcess.Id))" -ForegroundColor Gray
    Write-Host ""
    Write-Host "====================================" -ForegroundColor Cyan
    Write-Host "  启动完成" -ForegroundColor Green
    Write-Host "====================================" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "💡 访问地址:" -ForegroundColor Yellow
    Write-Host "   http://localhost:5174" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "📝 提示:" -ForegroundColor Yellow
    Write-Host "   - 按 Ctrl+C 可以停止服务" -ForegroundColor Gray
    Write-Host "   - 运行 stop-web.ps1 可以关闭服务" -ForegroundColor Gray
    Write-Host "   - 使用 -Force 参数可以强制重启" -ForegroundColor Gray
    Write-Host ""
} catch {
    Write-Host "❌ 启动服务失败: $_" -ForegroundColor Red
    exit 1
}
