<#
    Hua.Todo Linux 发布脚本（产出 .tar.gz）

    目标：
    - 为 Linux 提供可分发的目录产物（dotnet publish 输出）
    - 在 Windows 开发机上也能交叉发布 linux-x64（便于 CI 前的本地验证）

    约束：
    - Avalonia Linux 入口项目需先落地（参见 docs/project/v1.2.0-tasks/01-*）
    - 仅打包为 tar.gz；Flatpak/AppImage 需要在 Linux 环境执行相关工具链
#>

param(
    [ValidateSet("linux-x64", "linux-arm64")]
    [string]$RuntimeIdentifier = "linux-x64",

    [switch]$SelfContained,

    [string]$Configuration = "Release"
)

$ErrorActionPreference = "Stop"

$ScriptPath = $PSScriptRoot

function Get-FirstExistingFilePath {
    param(
        [Parameter(Mandatory = $true)]
        [string[]]$Candidates
    )

    foreach ($candidate in $Candidates) {
        if (Test-Path $candidate) {
            return $candidate
        }
    }

    return $null
}

function Read-ProjectVersion {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ProjectFile
    )

    $currentVersion = "0.0.0"
    [xml]$csproj = Get-Content $ProjectFile -Raw

    $versionNode = $csproj.SelectSingleNode("//Version")
    if ($null -ne $versionNode -and -not [string]::IsNullOrWhiteSpace($versionNode.InnerText)) {
        return $versionNode.InnerText.Trim()
    }

    $versionNode = $csproj.SelectSingleNode("//ApplicationDisplayVersion")
    if ($null -ne $versionNode -and -not [string]::IsNullOrWhiteSpace($versionNode.InnerText)) {
        return $versionNode.InnerText.Trim()
    }

    return $currentVersion
}

$candidateProjects = @(
    (Join-Path $ScriptPath "src\Hua.Todo.Avalonia\Hua.Todo.Avalonia.csproj"),
    (Join-Path $ScriptPath "src\Hua.Todo.Desktop.Avalonia\Hua.Todo.Desktop.Avalonia.csproj")
)

$ProjectFile = Get-FirstExistingFilePath -Candidates $candidateProjects
if ($null -eq $ProjectFile) {
    $candidatesText = ($candidateProjects | ForEach-Object { "  - $_" }) -join "`n"
    Write-Error @"
未找到 Avalonia Linux 入口项目（无法生成 Linux 交付产物）。

请先完成 docs/project/v1.2.0-tasks/01-Linux-Avalonia入口与WebView.md 对应实现，并确保下列路径之一存在：
$candidatesText
"@
    exit 1
}

$version = Read-ProjectVersion -ProjectFile $ProjectFile
$artifactRoot = Join-Path $ScriptPath "artifacts\linux\$RuntimeIdentifier"
$publishDir = Join-Path $artifactRoot "publish"

if (Test-Path $artifactRoot) {
    Remove-Item -Recurse -Force $artifactRoot
}
New-Item -ItemType Directory -Path $publishDir | Out-Null

$selfContainedValue = if ($SelfContained.IsPresent) { "true" } else { "false" }

Write-Host "Publishing (RID=$RuntimeIdentifier, SelfContained=$selfContainedValue)..." -ForegroundColor Cyan

dotnet publish $ProjectFile `
    -c $Configuration `
    -r $RuntimeIdentifier `
    --self-contained $selfContainedValue `
    -o $publishDir

if ($LASTEXITCODE -ne 0) {
    Write-Error "dotnet publish failed"
    exit 1
}

$packageName = "hua.todo-$version-$RuntimeIdentifier.tar.gz"
$packagePath = Join-Path $artifactRoot $packageName

Write-Host "Creating tar.gz: $packageName" -ForegroundColor Cyan
tar -C $publishDir -czf $packagePath .

if ($LASTEXITCODE -ne 0) {
    Write-Error "tar.gz packaging failed"
    exit 1
}

Write-Host "Linux artifact created: $packagePath" -ForegroundColor Green
