name: Release PyPI Nightly Wheels

on:
  # Run daily at 2 AM UTC
  schedule:
    - cron: '0 2 * * *'
  # Triggered by nightly Docker workflow to use same commit
  repository_dispatch:
    types: [nightly-release]
  # Manual trigger for testing
  workflow_dispatch:
    inputs:
      commit_sha:
        description: 'Specific commit SHA to build (leave empty for latest)'
        required: false
        type: string
      cuda_version:
        description: 'CUDA version (e.g., 129 or 130)'
        required: false
        default: '129'
        type: string

concurrency:
  group: release-pypi-nightly-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-nightly-wheel:
    if: github.repository == 'sgl-project/sglang'
    runs-on: ubuntu-latest
    outputs:
      nightly_version: ${{ steps.build.outputs.nightly_version }}
      commit_hash: ${{ steps.build.outputs.commit_hash }}
      build_date: ${{ steps.build.outputs.build_date }}
    steps:
      - uses: actions/checkout@v4
        with:
          # Use commit from: 1) Docker workflow, 2) manual input, 3) latest main
          ref: ${{ github.event.client_payload.commit_sha || inputs.commit_sha || github.sha }}
          fetch-depth: 0  # Need full history for setuptools-scm

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"

      - name: Install build dependencies
        run: |
          pip install build wheel setuptools setuptools-scm

      - name: Build wheel
        id: build
        run: |
          cd python
          cp ../README.md ../LICENSE .

          # Parse git describe output to get latest tag
          # Use same command as pyproject.toml to ensure version consistency
          DESC=$(git tag --list --sort=-version:refname 'v*.*.*' | head -1 | xargs git describe --tags --long 2>/dev/null || echo 'v0.0.0-0-g0000000')
          TAG=$(echo "$DESC" | cut -d- -f1)
          HASH="g$(git rev-parse --short HEAD)"
          BUILD_DATE=$(date -u +%Y%m%d)

          # Increment patch version for nightlies (e.g., v0.5.9 -> 0.5.10)
          # Must always increment so nightly > latest tag per PEP 440 ordering:
          #   X.Y.Z.devN < X.Y.Z.rcN < X.Y.Z < X.Y.(Z+1).devN
          VERSION=${TAG#v}  # Remove 'v' prefix
          MAJOR=$(echo "$VERSION" | cut -d. -f1)
          MINOR=$(echo "$VERSION" | cut -d. -f2)
          PATCH_RAW=$(echo "$VERSION" | cut -d. -f3)
          # Strip pre-release suffixes (rc0, post1, etc.) to get numeric patch
          PATCH=$(echo "$PATCH_RAW" | sed 's/[^0-9].*//')
          NEXT_PATCH=$((PATCH + 1))
          NEXT_VERSION="${MAJOR}.${MINOR}.${NEXT_PATCH}"

          # Use date-based dev number for correct chronological sorting
          # e.g., 0.5.9.dev20260215+g4cf4f0859 > 0.5.9.dev20260214+g45a4697d4
          FORCE_VERSION="${NEXT_VERSION}.dev${BUILD_DATE}+${HASH}"
          echo "Forcing nightly version to: $FORCE_VERSION"
          export SETUPTOOLS_SCM_PRETEND_VERSION="$FORCE_VERSION"

          # Build wheel
          python3 -m build --wheel

          # Extract version from built wheel filename
          WHEEL_FILE=$(ls dist/*.whl)
          NIGHTLY_VERSION=$(echo "$WHEEL_FILE" | sed 's/.*sglang-\(.*\)-py3.*/\1/')

          # Get commit info
          COMMIT_HASH=$(git rev-parse --short HEAD)
          BUILD_DATE=$(date -u +%Y-%m-%d)

          echo "Built wheel: $WHEEL_FILE"
          echo "Nightly version: ${NIGHTLY_VERSION}"
          echo "Commit: ${COMMIT_HASH}"
          echo "Build date: ${BUILD_DATE}"

          echo "nightly_version=${NIGHTLY_VERSION}" >> $GITHUB_OUTPUT
          echo "commit_hash=${COMMIT_HASH}" >> $GITHUB_OUTPUT
          echo "build_date=${BUILD_DATE}" >> $GITHUB_OUTPUT

      - name: Upload wheel artifact
        uses: actions/upload-artifact@v4
        with:
          name: nightly-wheel
          path: python/dist/*.whl
          retention-days: 7

  release-nightly:
    needs: build-nightly-wheel
    runs-on: ubuntu-latest
    environment: 'prod'
    steps:
      - uses: actions/checkout@v4

      - name: Download wheel artifact
        uses: actions/download-artifact@v4
        with:
          name: nightly-wheel
          path: dist/

      - name: List downloaded wheels
        run: |
          echo "Downloaded wheel:"
          ls -lh dist/

      - name: Create GitHub Release for nightly wheel
        uses: softprops/action-gh-release@v2
        with:
          tag_name: nightly-${{ needs.build-nightly-wheel.outputs.build_date }}-${{ needs.build-nightly-wheel.outputs.commit_hash }}
          name: Nightly Build ${{ needs.build-nightly-wheel.outputs.build_date }} (${{ needs.build-nightly-wheel.outputs.commit_hash }})
          repository: sgl-project/whl
          token: ${{ secrets.GH_PAT_FOR_WHL_RELEASE }}
          prerelease: true
          body: |
            Nightly build from commit ${{ github.sha }}
            Build date: ${{ needs.build-nightly-wheel.outputs.build_date }}
            Version: ${{ needs.build-nightly-wheel.outputs.nightly_version }}
          files: |
            dist/*.whl

      - name: Clone wheel index repository
        run: |
          git clone https://oauth2:${WHL_TOKEN}@github.com/sgl-project/whl.git sgl-whl
          cd sgl-whl
          git config --local user.name "sglang-bot"
          git config --local user.email "sglangbot@gmail.com"
        env:
          WHL_TOKEN: ${{ secrets.GH_PAT_FOR_WHL_RELEASE }}

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"

      - name: Update wheel index
        run: |
          python3 scripts/update_nightly_whl_index.py \
            --commit-hash ${{ needs.build-nightly-wheel.outputs.commit_hash }} \
            --nightly-version ${{ needs.build-nightly-wheel.outputs.nightly_version }} \
            --cuda-version ${{ inputs.cuda_version || '129' }} \
            --build-date ${{ needs.build-nightly-wheel.outputs.build_date }}

      - name: Push wheel index
        run: |
          cd sgl-whl
          git add -A
          git diff --staged --quiet || git commit -m "Update nightly wheel index for commit ${{ needs.build-nightly-wheel.outputs.commit_hash }}"
          git push
