param(
    [switch]$StartMaui = $false,
    [switch]$Force = $false
)

$ErrorActionPreference = "Stop"

Write-Host "====================================" -ForegroundColor Cyan
Write-Host "  TodoList 服务重启脚本" -ForegroundColor Cyan
Write-Host "====================================" -ForegroundColor Cyan
Write-Host ""

Write-Host "[1/3] 停止现有服务..." -ForegroundColor Yellow

$stopScriptPath = Join-Path $PSScriptRoot "stop-service.ps1"

if (!(Test-Path $stopScriptPath)) {
    Write-Host "❌ 停止脚本不存在: $stopScriptPath" -ForegroundColor Red
    exit 1
}

try {
    if ($Force) {
        & $stopScriptPath -Force
    } else {
        & $stopScriptPath
    }
    Write-Host "✅ 服务已停止" -ForegroundColor Green
} catch {
    Write-Host "❌ 停止服务失败: $_" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "[2/3] 等待进程完全关闭..." -ForegroundColor Yellow

$timeout = 10
$elapsed = 0

while ($elapsed -lt $timeout) {
    $apiRunning = Get-Process -Name "dotnet" -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowTitle -like "*TodoList.Api*" }
    $mauiRunning = Get-Process -Name "TodoList.Maui" -ErrorAction SilentlyContinue
    
    if (-not $apiRunning -and -not $mauiRunning) {
        Write-Host "✅ 所有进程已关闭" -ForegroundColor Green
        break
    }
    
    Start-Sleep -Seconds 1
    $elapsed++
    
    if ($elapsed -lt $timeout) {
        Write-Host "   等待中... ($elapsed/$timeout 秒)" -ForegroundColor Gray
    }
}

if ($elapsed -ge $timeout) {
    Write-Host "⚠️  等待超时，继续启动..." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "[3/3] 启动服务..." -ForegroundColor Yellow

$startScriptPath = Join-Path $PSScriptRoot "start-service.ps1"

if (!(Test-Path $startScriptPath)) {
    Write-Host "❌ 启动脚本不存在: $startScriptPath" -ForegroundColor Red
    exit 1
}

try {
    if ($StartMaui) {
        & $startScriptPath -StartMaui
    } else {
        & $startScriptPath
    }
    Write-Host "✅ 服务已启动" -ForegroundColor Green
} catch {
    Write-Host "❌ 启动服务失败: $_" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "====================================" -ForegroundColor Cyan
Write-Host "  重启完成" -ForegroundColor Green
Write-Host "====================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "💡 提示:" -ForegroundColor Yellow
Write-Host "   - 按 Ctrl+C 可以停止服务" -ForegroundColor Gray
Write-Host "   - 运行 stop-service.bat 可以关闭服务" -ForegroundColor Gray
Write-Host "   - 运行 restart-service.bat 可以重启服务" -ForegroundColor Gray
Write-Host ""