<#
.SYNOPSIS
    Build, tag, and publish a release to Gitea.

.DESCRIPTION
    1. Builds a self-contained single-file EXE
    2. Packages it with example CSVs into a zip
    3. Creates a git tag and pushes it
    4. Creates a Gitea Release and uploads the zip

.PARAMETER Version
    Version tag (e.g. "v2.0.0"). Required.

.PARAMETER Token
    Gitea API token. If not provided, reads from GITEA_TOKEN env var.

.EXAMPLE
    .\release.ps1 -Version v2.0.0
    .\release.ps1 -Version v2.1.0 -Token "your_token_here"
#>
param(
    [Parameter(Mandatory)][string]$Version,
    [string]$Token = $env:GITEA_TOKEN
)

$ErrorActionPreference = "Stop"

$GiteaUrl  = "https://git.azuze.fr"
$Repo      = "kawa/Sharepoint-Toolbox"
$Project   = "SharepointToolbox/SharepointToolbox.csproj"
$PublishDir = "publish"
$ZipName   = "SharePoint_Toolbox_$Version.zip"

# ── Validate ──────────────────────────────────────────────────────────────────
if (-not $Token) {
    Write-Error "No token provided. Pass -Token or set GITEA_TOKEN env var."
    exit 1
}

if (git tag -l $Version) {
    Write-Error "Tag $Version already exists."
    exit 1
}

# ── Build ─────────────────────────────────────────────────────────────────────
Write-Host "`n>> Building Release..." -ForegroundColor Cyan
dotnet publish $Project -c Release -p:PublishSingleFile=true -o $PublishDir
if ($LASTEXITCODE -ne 0) { exit 1 }

# ── Package ───────────────────────────────────────────────────────────────────
Write-Host "`n>> Packaging $ZipName..." -ForegroundColor Cyan
$staging = "release_staging"
if (Test-Path $staging) { Remove-Item $staging -Recurse -Force }
New-Item -ItemType Directory -Path $staging | Out-Null
New-Item -ItemType Directory -Path "$staging/examples" | Out-Null

Copy-Item "$PublishDir/SharepointToolbox.exe" "$staging/"
Copy-Item "SharepointToolbox/Resources/*.csv" "$staging/examples/"

if (Test-Path $ZipName) { Remove-Item $ZipName }
Compress-Archive -Path "$staging/*" -DestinationPath $ZipName
Remove-Item $staging -Recurse -Force

$zipSize = [math]::Round((Get-Item $ZipName).Length / 1MB, 1)
Write-Host "   Created $ZipName ($zipSize MB)" -ForegroundColor Green

# ── Tag & Push ────────────────────────────────────────────────────────────────
Write-Host "`n>> Tagging $Version and pushing..." -ForegroundColor Cyan
git tag $Version
git push kawa main --tags

# ── Create Release ────────────────────────────────────────────────────────────
Write-Host "`n>> Creating Gitea release..." -ForegroundColor Cyan
$headers = @{
    "Authorization" = "token $Token"
    "Content-Type"  = "application/json"
}

$body = @{
    tag_name = $Version
    name     = "SharePoint Toolbox $Version"
    body     = @"
## Installation

1. Download **$ZipName** below
2. Extract the archive
3. Launch **SharepointToolbox.exe** (requires .NET 10 runtime)

## Included

- ``SharepointToolbox.exe`` — desktop application
- ``examples/`` — sample CSV templates for bulk operations
"@
} | ConvertTo-Json -Compress

$release = Invoke-RestMethod `
    -Uri "$GiteaUrl/api/v1/repos/$Repo/releases" `
    -Method Post `
    -Headers $headers `
    -Body $body

$releaseId = $release.id
Write-Host "   Release created (ID: $releaseId)" -ForegroundColor Green

# ── Upload Asset ──────────────────────────────────────────────────────────────
Write-Host "`n>> Uploading $ZipName..." -ForegroundColor Cyan
$uploadUrl = "$GiteaUrl/api/v1/repos/$Repo/releases/$releaseId/assets"

# Use curl for multipart upload (Invoke-RestMethod multipart is clunky)
curl.exe -sf `
    -X POST $uploadUrl `
    -H "Authorization: token $Token" `
    -F "attachment=@$ZipName" | Out-Null

if ($LASTEXITCODE -ne 0) {
    Write-Error "Asset upload failed."
    exit 1
}

# ── Cleanup ───────────────────────────────────────────────────────────────────
Remove-Item $ZipName
Remove-Item $PublishDir -Recurse -Force

Write-Host "`n>> Done! Release published at:" -ForegroundColor Green
Write-Host "   $GiteaUrl/$Repo/releases/tag/$Version" -ForegroundColor Yellow
