param(
    [string]$Instance = "blue",
    [int]$Port = 5000,
    [int]$MaxRetries = 30,
    [int]$RetryDelayMs = 1000,
    [int]$TimeoutSeconds = 10
)

$ErrorActionPreference = "Continue"

$logFile = "D:\EPproject\LabelReplaceServer\deployment\logs\deployment.log"

function Log {
    param([string]$Message, [string]$Level = "INFO")
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [HealthCheck:$Instance] $Message"
    Write-Host $logEntry
    
    $logDirPath = Split-Path -Parent $logFile
    if (!(Test-Path $logDirPath)) {
        New-Item -ItemType Directory -Path $logDirPath -Force | Out-Null
    }
    Add-Content -Path $logFile -Value $logEntry
}

function CheckHealth {
    param([int]$CurrentAttempt)
    
    try {
        $url = "http://localhost:$Port/api/health"
        $response = Invoke-WebRequest -Uri $url -Method Get -TimeoutSec $TimeoutSeconds -ErrorAction Stop
        
        if ($response.StatusCode -eq 200) {
            Log "健康检查成功 (尝试 $CurrentAttempt/$MaxRetries)" "INFO"
            
            $content = $response.Content | ConvertFrom-Json
            Log "实例状态: $($content.status), 环境: $($content.environment)" "INFO"
            
            return $true
        }
    }
    catch {
        Log "健康检查失败 (尝试 $CurrentAttempt/$MaxRetries): $($_.Exception.Message)" "WARN"
    }
    
    return $false
}

try {
    Log "开始健康检查 - 实例: $Instance, 端口: $Port" "INFO"
    Log "最大重试次数: $MaxRetries, 重试间隔: ${RetryDelayMs}ms, 超时: ${TimeoutSeconds}s" "INFO"
    
    for ($i = 1; $i -le $MaxRetries; $i++) {
        if (CheckHealth -CurrentAttempt $i) {
            Log "健康检查通过" "INFO"
            return $true
        }
        
        if ($i -lt $MaxRetries) {
            Log "等待 ${RetryDelayMs}ms 后重试..." "INFO"
            Start-Sleep -Milliseconds $RetryDelayMs
        }
    }
    
    Log "健康检查失败: 在 $MaxRetries 次重试后仍未响应" "ERROR"
    return $false
}
catch {
    Log "健康检查执行异常: $_" "ERROR"
    Log "错误详情: $($_.Exception.StackTrace)" "ERROR"
    return $false
}
