param(
    [switch]$Force = $false
)

$ErrorActionPreference = "Stop"

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

$hostProjectPath = Join-Path $PSScriptRoot "src\Hua.Todo.Host"
$hostProjectFile = Join-Path $hostProjectPath "Hua.Todo.Host.csproj"

if (!(Test-Path $hostProjectFile)) {
    Write-Host "❌ Host 项目文件不存在: $hostProjectFile" -ForegroundColor Red
    exit 1
}

if (!(Get-Command "dotnet" -ErrorAction SilentlyContinue)) {
    Write-Host "❌ 未找到 dotnet，请先安装 .NET SDK" -ForegroundColor Red
    exit 1
}

Write-Host "[1/2] 检查 Hua.Todo.Host 是否已在运行..." -ForegroundColor Yellow

$runningProcesses = Get-CimInstance Win32_Process -Filter "Name='dotnet.exe'" | Where-Object {
    $_.CommandLine -and (
        $_.CommandLine -like "*Hua.Todo.Host*" -or
        $_.CommandLine -like "*Hua.Todo.Host.dll*"
    )
}

if ($runningProcesses) {
    $pids = ($runningProcesses.ProcessId | Sort-Object) -join ", "
    Write-Host "⚠️  Hua.Todo.Host 可能已在运行中" -ForegroundColor Yellow
    Write-Host "   进程 ID: ($pids)" -ForegroundColor Gray

    if ($Force) {
        Write-Host ""
        Write-Host "🔄 强制关闭并重新启动..." -ForegroundColor Yellow
        try {
            $runningProcesses | ForEach-Object { Stop-Process -Id $_.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 "💡 API 地址:" -ForegroundColor Yellow
        Write-Host "   http://localhost:5173" -ForegroundColor Cyan
        Write-Host ""
        exit 0
    }
} else {
    Write-Host "✓ Hua.Todo.Host 未运行" -ForegroundColor Green
    Write-Host ""
}

Write-Host "[2/2] 启动 Hua.Todo.Host..." -ForegroundColor Yellow
Write-Host "📂 工作目录: $hostProjectPath" -ForegroundColor Gray
Write-Host "🚀 启动服务..." -ForegroundColor Green
Write-Host ""

try {
    $argumentList = @(
        "run",
        "--project", $hostProjectFile,
        "--launch-profile", "http"
    )

    $hostProcess = Start-Process -FilePath "dotnet" -ArgumentList $argumentList -WorkingDirectory $hostProjectPath -PassThru

    Write-Host "✅ Hua.Todo.Host 已启动" -ForegroundColor Green
    Write-Host "   进程 ID: ($($hostProcess.Id))" -ForegroundColor Gray
    Write-Host ""
    Write-Host "💡 API 地址:" -ForegroundColor Yellow
    Write-Host "   http://localhost:5173" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "📝 提示:" -ForegroundColor Yellow
    Write-Host "   - 使用 -Force 参数可以强制重启" -ForegroundColor Gray
    Write-Host ""
} catch {
    Write-Host "❌ 启动失败: $_" -ForegroundColor Red
    exit 1
}

