name: Build VSCode Extension

on:
  pull_request:
    paths:
      - 'js/VSC-Extension/**'
  workflow_dispatch:

jobs:
  check-min-version:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Extract MIN_CODEFLASH_VERSION from constants file
        id: extract-version
        run: |
          FILE="js/VSC-Extension/src/constants/cf_min_version.ts"
          VERSION=$(grep -oP 'MIN_CODEFLASH_VERSION\s*=\s*"\K[^"]+' $FILE)

          if [ -z "$VERSION" ]; then
            echo "❌ Could not find MIN_CODEFLASH_VERSION in $FILE"
            exit 1
          fi

          echo "✅ Found MIN_CODEFLASH_VERSION=$VERSION"
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Check version exists on PyPI
        run: |
          # Check if this version exists on PyPI
          VERSION="${{ steps.extract-version.outputs.version }}"
          if pip index versions codeflash | grep -q "Available versions: .*$VERSION"; then
            echo "✅ Version $VERSION exists on PyPI."
          else
            echo "❌ Version $VERSION not found on PyPI"
            exit 1
          fi
  build:
    runs-on: ubuntu-latest
    needs: check-min-version
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Use Node.js v20
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: "npm"
          cache-dependency-path: js/VSC-Extension/package-lock.json

      - name: Install dependencies
        working-directory: js/VSC-Extension
        run: npm ci

      - name: Package VSCode Extension
        working-directory: js/VSC-Extension
        run: npm run vsce

      - name: Upload VSIX artifact
        uses: actions/upload-artifact@v4
        with:
          name: vscode-extension
          path: js/VSC-Extension/*.vsix
