name: CI Monitor

on:
  schedule:
    # Run every 6 hours at 00:00, 06:00, 12:00, 18:00 UTC
    - cron: '0 */6 * * *'
  workflow_dispatch:
    inputs:
      limit:
        description: 'Number of CI runs to analyze'
        required: false
        default: '1000'
        type: string

concurrency:
  group: ci-monitor-${{ github.ref }}
  cancel-in-progress: true

jobs:
  ci-monitor:
    if: github.repository == 'sgl-project/sglang'|| github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.9'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install requests matplotlib pandas

      - name: Run CI Analysis
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT_FOR_NIGHTLY_CI }}
          PYTHONUNBUFFERED: 1
          PYTHONIOENCODING: utf-8
        run: |
          cd scripts/ci_monitor
          python ci_analyzer.py --token $GITHUB_TOKEN --limit ${{ github.event.inputs.limit || '1000' }} --output ci_analysis_$(date +%Y%m%d_%H%M%S).json

      - name: Run Performance Analysis
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT_FOR_NIGHTLY_CI }}
          PYTHONUNBUFFERED: 1
          PYTHONIOENCODING: utf-8
        run: |
          cd scripts/ci_monitor
          python ci_analyzer_perf.py --token $GITHUB_TOKEN --limit 500 --output-dir performance_tables_$(date +%Y%m%d_%H%M%S)

      - name: Upload Analysis Results
        uses: actions/upload-artifact@v4
        with:
          name: ci-analysis-results-${{ github.run_number }}
          path: |
            scripts/ci_monitor/ci_analysis_*.json
            scripts/ci_monitor/performance_tables_*
          retention-days: 30
