$ErrorActionPreference = 'Stop'

function Select-Option {
    param(
        [string]$Title,
        [string[]]$Options
    )

    while ($true) {
        Write-Host ""
        Write-Host $Title
        for ($i = 0; $i -lt $Options.Length; $i++) {
            Write-Host ("{0}. {1}" -f ($i + 1), $Options[$i])
        }

        $inputValue = Read-Host "请输入序号"
        $index = 0
        if ([int]::TryParse($inputValue, [ref]$index) -and $index -ge 1 -and $index -le $Options.Length) {
            return $Options[$index - 1]
        }

        Write-Host "输入无效，请重新选择。"
    }
}

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '..')

if (-not (git -C $repoRoot rev-parse --is-inside-work-tree 2>$null)) {
    throw "当前目录不是 Git 仓库。"
}

git -C $repoRoot diff --cached --quiet
if ($LASTEXITCODE -eq 0) {
    throw "当前没有已暂存的改动，请先执行 git add。"
}

$stagedFiles = @(git -C $repoRoot diff --cached --name-only)

$types = @(
    'feat',
    'feat-wip',
    'fix',
    'docs',
    'typo',
    'style',
    'refactor',
    'perf',
    'optimize',
    'test',
    'build',
    'ci',
    'chore',
    'revert'
)

$scopes = @(
    'system',
    'gateway',
    'framework',
    'common',
    'security',
    'web',
    'mybatis',
    'redis',
    'mq',
    'rpc',
    'sql',
    'deps',
    'other'
)

$type = Select-Option -Title '请选择提交类型 type' -Options $types
$scope = Select-Option -Title '请选择提交范围 scope' -Options $scopes

while ($true) {
    $description = (Read-Host '请输入提交描述').Trim()
    if ($description) {
        break
    }
    Write-Host "描述不能为空，请重新输入。"
}

$message = "{0}({1}): {2}" -f $type, $scope, $description

Write-Host ""
Write-Host "提交信息预览：$message"
Write-Host ""
Write-Host "本次将提交以下已暂存文件："
foreach ($file in $stagedFiles) {
    Write-Host " - $file"
}

$confirm = Read-Host '确认提交请输入 y，取消请输入其他任意内容'
if ($confirm -ne 'y' -and $confirm -ne 'Y') {
    Write-Host '已取消提交。'
    exit 1
}

git -C $repoRoot commit -m $message
