param(
    [string]$OutputDirectory = "D:\EPproject\LabelReplaceServer\deployment\green",
    [string]$Version = (Get-Date -Format "yyyyMMdd-HHmmss"),
    [string]$Configuration = "Release"
)

$ErrorActionPreference = "Stop"

$projectPath = "D:\EPproject\LabelReplaceServer\src\CONTROLLER\CONTROLLER.csproj"
$logFile = "D:\EPproject\LabelReplaceServer\deployment\logs\deployment.log"
$backupDir = "D:\EPproject\LabelReplaceServer\deployment\backups"

function Log {
    param([string]$Message, [string]$Level = "INFO")
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] $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 "开始编译和发布应用..." "INFO"
    Log "版本: $Version" "INFO"
    Log "输出目录: $OutputDirectory" "INFO"
    Log "配置: $Configuration" "INFO"
    Log "========================================" "INFO"
    
    if (!(Test-Path $projectPath)) {
        throw "项目文件不存在: $projectPath"
    }
    
    if (Test-Path $OutputDirectory) {
        Log "创建输出目录备份..." "INFO"
        if (!(Test-Path $backupDir)) {
            New-Item -ItemType Directory -Path $backupDir -Force | Out-Null
        }
        
        $backupName = "backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
        $backupPath = Join-Path $backupDir $backupName
        Copy-Item -Path $OutputDirectory -Destination $backupPath -Recurse -Force
        Log "备份已保存到: $backupPath" "INFO"
    }
    
    Log "清理旧的输出目录..." "INFO"
    if (Test-Path $OutputDirectory) {
        Remove-Item -Path $OutputDirectory -Recurse -Force
    }
    
    Log "执行 dotnet clean..." "INFO"
    & dotnet clean $projectPath -c $Configuration --nologo
    if ($LASTEXITCODE -ne 0) {
        throw "dotnet clean 失败，退出代码: $LASTEXITCODE"
    }
    
    Log "执行 dotnet restore..." "INFO"
    & dotnet restore $projectPath --nologo
    if ($LASTEXITCODE -ne 0) {
        throw "dotnet restore 失败，退出代码: $LASTEXITCODE"
    }
    
    Log "执行 dotnet build..." "INFO"
    & dotnet build $projectPath -c $Configuration --nologo --no-restore
    if ($LASTEXITCODE -ne 0) {
        throw "dotnet build 失败，退出代码: $LASTEXITCODE"
    }
    
    Log "执行 dotnet publish..." "INFO"
    & dotnet publish $projectPath -c $Configuration -o $OutputDirectory --nologo --no-build
    if ($LASTEXITCODE -ne 0) {
        throw "dotnet publish 失败，退出代码: $LASTEXITCODE"
    }
    
    Log "========================================" "INFO"
    Log "编译和发布完成！" "INFO"
    Log "输出位置: $OutputDirectory" "INFO"
    Log "========================================" "INFO"
    
    return $true
}
catch {
    Log "编译和发布失败: $_" "ERROR"
    Log "错误详情: $($_.Exception.StackTrace)" "ERROR"
    return $false
}
