[CmdletBinding()]
param(
    [switch]$NoPush
)

$ErrorActionPreference = 'Stop'

$repositoryRoot = Split-Path -Parent $PSScriptRoot
$skillFile = Join-Path $repositoryRoot 'SKILL.md'

Set-Location -LiteralPath $repositoryRoot

$pendingChanges = git status --porcelain
if (-not $pendingChanges) {
    throw 'No skill changes are pending. Update the skill before creating a release.'
}

$content = Get-Content -LiteralPath $skillFile -Raw -Encoding UTF8
$match = [regex]::Match($content, '(?m)^Version:\s*(?<version>\d+\.\d+\.\d+)\s*$')
if (-not $match.Success) {
    throw "Could not find a 'Version: x.y.z' line in $skillFile."
}

$currentVersion = [version]$match.Groups['version'].Value
$nextVersion = '{0}.{1}.0' -f $currentVersion.Major, ($currentVersion.Minor + 1)
$updatedContent = [regex]::Replace(
    $content,
    '(?m)^Version:\s*\d+\.\d+\.\d+\s*$',
    "Version: $nextVersion",
    1
)
Set-Content -LiteralPath $skillFile -Value $updatedContent -Encoding UTF8

git add --all
if ($LASTEXITCODE -ne 0) {
    throw 'git add failed.'
}

git diff --cached --quiet
if ($LASTEXITCODE -eq 0) {
    throw 'No staged changes found after version update.'
}
if ($LASTEXITCODE -ne 1) {
    throw 'Could not inspect the staged Git diff.'
}

git commit -m "release: xinje-plc-programming v$nextVersion"
if ($LASTEXITCODE -ne 0) {
    throw 'git commit failed.'
}

if (-not $NoPush) {
    git push origin HEAD
    if ($LASTEXITCODE -ne 0) {
        throw 'Release commit was created, but git push failed. Resolve the remote issue and push the existing commit.'
    }
}

Write-Output "Released xinje-plc-programming v$nextVersion"
