param(
    [string]$Instance = "blue",
    [int]$Port = 5000,
    [int]$GracefulTimeoutSeconds = 30
)

$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] [StopInstance:$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
}

try {
    Log "========== 优雅关闭实例 ==========" "INFO"
    Log "实例: $Instance, 端口: $Port" "INFO"
    Log "优雅超时: $GracefulTimeoutSeconds 秒" "INFO"
    
    $controller = Get-Process -Name CONTROLLER -ErrorAction SilentlyContinue
    
    if ($null -eq $controller) {
        Log "CONTROLLER 进程未找到" "WARN"
        return $true
    }
    
    Log "找到 CONTROLLER 进程 (PID: $($controller.Id))" "INFO"
    Log "等待进程优雅退出..." "INFO"
    
    if ($controller.WaitForExit($GracefulTimeoutSeconds * 1000)) {
        Log "进程已优雅退出" "INFO"
        return $true
    }
    
    Log "进程未在 $GracefulTimeoutSeconds 秒内退出，强制终止..." "WARN"
    
    try {
        $controller | Stop-Process -Force -ErrorAction Stop
        Log "进程已强制终止" "INFO"
    }
    catch {
        Log "强制终止失败: $_" "ERROR"
        return $false
    }
    
    return $true
}
catch {
    Log "优雅关闭异常: $_" "ERROR"
    return $false
}
