name: Create Version Release

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Release version (SemVer format, e.g., 1.2.3 or 2.0.0-rc.1)'
        required: true
        type: string

permissions:
  contents: write

env:
  CURRENT_BRANCH_NAME: ${{ github.head_ref || github.ref_name }}

jobs:
  create-release-branch:
    name: Create Release Branch
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v5
        with:
          token: ${{ secrets.PUBLISHER_TOKEN }}
          fetch-depth: 0

      - name: Extract version
        id: extract
        run: .github/scripts/extract_version.sh

      - name: Validate version format and range
        id: validate
        run: .github/scripts/validate_semver.sh "${{ github.event.inputs.version }}" ">${{ steps.extract.outputs.version }}"

      - name: Check if branch exists
        run: |
          BRANCH_NAME="release/${{ steps.validate.outputs.version }}"

          if git ls-remote --heads origin "$BRANCH_NAME" | grep -q "$BRANCH_NAME"; then
            echo "Error: Branch '$BRANCH_NAME' already exists"
            exit 1
          fi

          echo "Branch '$BRANCH_NAME' does not exist, proceeding..."

      - name: Auto-generate release notes if missing
        run: .github/scripts/generate_release_notes.sh -v "${{ steps.validate.outputs.version }}" -k "${{ secrets.GEMINI_API_KEY }}" -p

      - name: Create release branch and update version
        run: .github/scripts/create_release.sh "${{ steps.validate.outputs.version }}" "${{ env.CURRENT_BRANCH_NAME }}"
