# pr-merge.ps1 - Merge pull requests on Gitea or GitHub
# Usage: .\pr-merge.ps1 -Number PR_NUMBER [-Method squash] [-DeleteBranch]

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [Alias("n")]
    [int]$Number,

    [Alias("m")]
    [string]$Method = "squash",

    [Alias("d")]
    [switch]$DeleteBranch,

    [switch]$SkipQueueGuard,

    [Alias("h")]
    [switch]$Help
)

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$ScriptDir\detect-platform.ps1"

function Show-Usage {
    @"
Usage: pr-merge.ps1 [OPTIONS]

Merge a pull request on the current repository (Gitea or GitHub).

Options:
    -Number, -n NUMBER      PR number to merge (required)
    -Method, -m METHOD      Merge method: squash only (default: squash)
    -DeleteBranch, -d       Delete the head branch after merge
    -SkipQueueGuard         Skip CI queue guard wait before merge
    -Help, -h               Show this help message

Examples:
    .\pr-merge.ps1 -n 42                    # Merge PR #42
    .\pr-merge.ps1 -n 42 -m squash          # Squash merge
    .\pr-merge.ps1 -n 42 -d                 # Squash merge and delete branch
"@
    exit 1
}

if ($Help) {
    Show-Usage
}

if ($Method -ne "squash") {
    Write-Error "Mosaic policy enforces squash merge only. Received '$Method'."
    exit 1
}

$platform = Get-GitPlatform

switch ($platform) {
    "github" {
        $baseRef = (& gh pr view $Number --json baseRefName --jq ".baseRefName").Trim()
        if ($baseRef -ne "main") {
            Write-Error "Mosaic policy allows merges only for PRs targeting 'main' (found '$baseRef')."
            exit 1
        }

        if (-not $SkipQueueGuard) {
            $timeout = if ($env:MOSAIC_CI_QUEUE_TIMEOUT_SEC) { [int]$env:MOSAIC_CI_QUEUE_TIMEOUT_SEC } else { 900 }
            $interval = if ($env:MOSAIC_CI_QUEUE_POLL_SEC) { [int]$env:MOSAIC_CI_QUEUE_POLL_SEC } else { 15 }
            & "$ScriptDir\ci-queue-wait.ps1" -Purpose merge -Branch $baseRef -TimeoutSeconds $timeout -IntervalSeconds $interval
            if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
        }

        $cmd = @("gh", "pr", "merge", $Number, "--squash")
        if ($DeleteBranch) { $cmd += "--delete-branch" }
        & $cmd[0] $cmd[1..($cmd.Length-1)]
    }
    "gitea" {
        $repoArgs = @(Get-GiteaRepoArgs)
        if ($repoArgs.Length -eq 0) {
            Write-Error "Could not resolve Gitea repo/login for remote host"
            exit 1
        }
        if (-not $SkipQueueGuard) {
            $timeout = if ($env:MOSAIC_CI_QUEUE_TIMEOUT_SEC) { [int]$env:MOSAIC_CI_QUEUE_TIMEOUT_SEC } else { 900 }
            $interval = if ($env:MOSAIC_CI_QUEUE_POLL_SEC) { [int]$env:MOSAIC_CI_QUEUE_POLL_SEC } else { 15 }
            & "$ScriptDir\ci-queue-wait.ps1" -Purpose merge -Branch "main" -TimeoutSeconds $timeout -IntervalSeconds $interval
            if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
        }

        $cmd = @("tea", "pr", "merge", $Number, "--style", "squash")

        if ($DeleteBranch) {
            Write-Warning "Branch deletion after merge may need to be done separately with tea"
        }

        $cmd += $repoArgs
        & $cmd[0] $cmd[1..($cmd.Length-1)]
    }
    default {
        Write-Error "Could not detect git platform"
        exit 1
    }
}

Write-Host "PR #$Number merged successfully"
