name: Publish Pre-Release Extension

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'ODD minor version (e.g., 1.1.0). Leave empty to auto-detect from latest release.'
        required: false
        type: string
        default: ''
      dry-run:
        description: 'Dry run (package only, do not publish)'
        required: false
        type: boolean
        default: false

permissions:
  contents: read

jobs:
  validate-version:
    name: Validate Pre-Release Version
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.validate.outputs.version }}
    steps:
      - name: Validate ODD minor version
        id: validate
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          VERSION="${{ inputs.version }}"
          # Strip leading 'v' if present
          VERSION="${VERSION#v}"

          # Auto-detect from latest release tag when no version specified
          if [ -z "$VERSION" ]; then
            TAG=$(gh release view --json tagName -q '.tagName' -R "${{ github.repository }}")
            VERSION="${TAG#hve-core-v}"

            MAJOR=$(echo "$VERSION" | cut -d. -f1)
            MINOR=$(echo "$VERSION" | cut -d. -f2)
            PATCH=$(echo "$VERSION" | cut -d. -f3)

            # Derive ODD minor: if even, bump minor by 1 and reset patch
            if (( MINOR % 2 == 0 )); then
              MINOR=$((MINOR + 1))
              PATCH=0
            fi
            VERSION="${MAJOR}.${MINOR}.${PATCH}"
            echo "📦 Auto-derived pre-release version from latest release: $VERSION"
          fi

          # Validate format
          if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "::error::Invalid version format: $VERSION. Expected semantic version (e.g., 1.1.0)"
            exit 1
          fi

          # Extract minor version
          MINOR=$(echo "$VERSION" | cut -d. -f2)

          # Check if ODD (pre-release channel uses ODD minor versions)
          if (( MINOR % 2 == 0 )); then
            echo "::error::Pre-release requires ODD minor version. Got: $VERSION (minor=$MINOR is EVEN)"
            echo "::error::Use version like 1.1.0, 1.3.0, 2.1.0 for pre-release channel"
            exit 1
          fi

          echo "✅ Valid pre-release version: $VERSION (minor=$MINOR is ODD)"
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"

  package:
    name: Package Pre-Release Extensions
    needs: validate-version
    uses: ./.github/workflows/extension-package.yml
    with:
      version: ${{ needs.validate-version.outputs.version }}
      channel: PreRelease
    permissions:
      contents: read

  publish:
    name: Publish ${{ matrix.id }}
    needs: [package]
    if: ${{ !inputs.dry-run }}
    runs-on: ubuntu-latest
    environment: marketplace
    strategy:
      fail-fast: false
      matrix: ${{ fromJson(needs.package.outputs.collections-matrix) }}
    permissions:
      contents: read
      id-token: write
    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4.2.2
        with:
          persist-credentials: false

      - name: Azure Login (OIDC)
        uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
        with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}

      - name: Setup Node.js
        uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v4.1.0
        with:
          node-version: '20'

      - name: Install VSCE
        run: npm install -g @vscode/vsce@3.7.1

      - name: Download VSIX artifact
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
        with:
          name: extension-vsix-${{ matrix.id }}
          path: ./dist

      - name: Publish pre-release to VS Code Marketplace
        id: publish
        run: |
          VSIX_FILE=$(find dist -name '*.vsix' -printf '%T@ %p\n' | sort -rn | head -1 | cut -d' ' -f2)
          if [ -z "$VSIX_FILE" ]; then
            echo "::error::No VSIX file found for collection ${{ matrix.id }}"
            exit 1
          fi
          VSIX_VERSION=$(basename "$VSIX_FILE" .vsix | grep -oE '[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.]+)?$')
          echo "version=$VSIX_VERSION" >> "$GITHUB_OUTPUT"
          echo "📦 Publishing pre-release ${{ matrix.id }}: $VSIX_FILE (v$VSIX_VERSION)"
          vsce publish --packagePath "$VSIX_FILE" --pre-release --azure-credential

      - name: Summary
        run: |
          {
            echo "## 🚀 Pre-Release Extension Published: ${{ matrix.name }}"
            echo ""
            echo "**Collection:** ${{ matrix.id }}"
            echo "**Version:** ${{ steps.publish.outputs.version }}"
            echo "**Channel:** Pre-Release (ODD minor)"
            echo ""
            echo "Users can install via **Switch to Pre-Release Version** in VS Code."
            echo ""
            echo "View on [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=ise-hve-essentials.${{ matrix.name }})"
          } >> "$GITHUB_STEP_SUMMARY"
