<#
.SYNOPSIS
  Ermittelt das nächste offene Ticket aus dem GitHub Project Board.
.DESCRIPTION
  Sortierung: priority:high (0) → normal (1) → priority:low (2), dann Order aufsteigend.
  Gibt Nummer, Typ-Label, Titel und Order aus.
.PARAMETER IssueNumber
  Optional: Direkt eine Issue-Nummer abfragen statt Board-Suche.
#>
param([int]$IssueNumber)

$repo = "jreinemann-euris/krisenvorrat"

if ($IssueNumber -gt 0) {
    # Variante A: Explizite Issue-Nummer
    $json = gh issue view $IssueNumber --repo $repo --json number,title,labels | ConvertFrom-Json
    $labels = $json.labels | ForEach-Object { $_.name }
    $type = if ($labels -contains "block-planning") { "[B]" }
    elseif ($labels -contains "migration") { "[M]" }
    elseif ($labels -contains "feature") { "[F]" }
    elseif ($labels -contains "refactoring") { "[F]" }
    elseif ($labels -contains "tech-decision") { "[T]" }
    elseif ($labels -contains "infrastructure") { "[I]" }
    elseif ($labels -contains "planning") { "[P]" }
    elseif ($labels -contains "test") { "[X]" }
    else { "[?]" }
    Write-Host "#$($json.number) $type $($json.title)"
}
else {
    # Variante B: Nächstes Ticket per Board-Query (client-seitig auf Todo gefiltert)
    $raw = gh project item-list 2 --owner jreinemann-euris --format json --limit 200 | ConvertFrom-Json
    if ($null -eq $raw -or $null -eq $raw.items) {
        Write-Host "Keine offenen Tickets gefunden."
        return
    }
    $todos = $raw.items | Where-Object { $_.status -eq "Todo" } | ForEach-Object {
        $labels = $_.labels
        $prio = if ($labels -contains "priority:high") { 0 }
        elseif ($labels -contains "priority:low") { 2 }
        else { 1 }
        $type = if ($labels -contains "block-planning") { "[B]" }
        elseif ($labels -contains "migration") { "[M]" }
        elseif ($labels -contains "feature") { "[F]" }
        elseif ($labels -contains "refactoring") { "[F]" }
        elseif ($labels -contains "tech-decision") { "[T]" }
        elseif ($labels -contains "infrastructure") { "[I]" }
        elseif ($labels -contains "planning") { "[P]" }
        elseif ($labels -contains "test") { "[X]" }
        else { "[?]" }
        [PSCustomObject]@{
            Number = $_.content.number
            Title  = $_.content.title
            Order  = if ($null -ne $_.order) { $_.order } else { 999999 }
            Prio   = $prio
            Type   = $type
        }
    } | Sort-Object Prio, Order | Select-Object -First 1

    if ($todos) {
        Write-Host "#$($todos.Number) $($todos.Type) $($todos.Title) (Order: $($todos.Order))"
    }
    else {
        Write-Host "Keine offenen Tickets gefunden."
    }
}
