# issue-create.ps1 - Create issues on Gitea or GitHub
# Usage: .\issue-create.ps1 -Title "Title" [-Body "Body"] [-Labels "label1,label2"] [-Milestone "milestone"]

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [Alias("t")]
    [string]$Title,

    [Alias("b")]
    [string]$Body,

    [Alias("l")]
    [string]$Labels,

    [Alias("m")]
    [string]$Milestone,

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

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

function Show-Usage {
    @"
Usage: issue-create.ps1 [OPTIONS]

Create an issue on the current repository (Gitea or GitHub).

Options:
    -Title, -t TITLE        Issue title (required)
    -Body, -b BODY          Issue body/description
    -Labels, -l LABELS      Comma-separated labels (e.g., "bug,feature")
    -Milestone, -m NAME     Milestone name to assign
    -Help, -h               Show this help message

Examples:
    .\issue-create.ps1 -Title "Fix login bug" -Labels "bug,priority-high"
    .\issue-create.ps1 -t "Add dark mode" -b "Implement theme switching" -m "0.2.0"
"@
    exit 1
}

if ($Help) {
    Show-Usage
}

$platform = Get-GitPlatform

switch ($platform) {
    "github" {
        $cmd = @("gh", "issue", "create", "--title", $Title)
        if ($Body) { $cmd += @("--body", $Body) }
        if ($Labels) { $cmd += @("--label", $Labels) }
        if ($Milestone) { $cmd += @("--milestone", $Milestone) }
        & $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
        }
        $cmd = @("tea", "issue", "create", "--title", $Title)
        if ($Body) { $cmd += @("--description", $Body) }
        if ($Labels) { $cmd += @("--labels", $Labels) }
        if ($Milestone) {
            # Try to get milestone ID by name
            $milestoneList = tea milestones list @repoArgs 2>$null
            $milestoneId = ($milestoneList | Select-String "^\s*(\d+).*$Milestone" | ForEach-Object { $_.Matches.Groups[1].Value } | Select-Object -First 1)
            if ($milestoneId) {
                $cmd += @("--milestone", $milestoneId)
            } else {
                Write-Warning "Could not find milestone '$Milestone', creating without milestone"
            }
        }
        $cmd += $repoArgs
        & $cmd[0] $cmd[1..($cmd.Length-1)]
    }
    default {
        Write-Error "Could not detect git platform"
        exit 1
    }
}
