name: Update Weekly Activity Cache

on:
  schedule:
    - cron: '0 */2 * * *'  # Every 2 hours
  workflow_dispatch:

permissions:
  contents: write

jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Fetch commit activity with retries
        run: |
          MAX_RETRIES=5
          RETRY_DELAY=10
          OUTPUT_FILE="docs/public/weekly-activity-cache.json"
          
          for i in $(seq 1 $MAX_RETRIES); do
            echo "Attempt $i of $MAX_RETRIES..."
            
            HTTP_CODE=$(curl -s -w "%{http_code}" -o /tmp/activity.json \
              -H "Accept: application/vnd.github+json" \
              -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
              "https://api.github.com/repos/${{ github.repository }}/stats/commit_activity")
            
            if [ "$HTTP_CODE" = "200" ]; then
              # Verify it's valid JSON array with data
              if jq -e 'type == "array" and length > 0' /tmp/activity.json > /dev/null 2>&1; then
                echo "Success! Got $(jq 'length' /tmp/activity.json) weeks of data."
                cp /tmp/activity.json "$OUTPUT_FILE"
                exit 0
              else
                echo "Got 200 but empty or invalid data, retrying..."
              fi
            else
              echo "Got HTTP $HTTP_CODE, waiting ${RETRY_DELAY}s before retry..."
            fi
            
            sleep $RETRY_DELAY
          done
          
          echo "Failed to fetch valid data after $MAX_RETRIES attempts"
          exit 1

      - name: Commit if changed
        run: |
          git diff --quiet docs/public/weekly-activity-cache.json && echo "No changes" && exit 0
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add docs/public/weekly-activity-cache.json
          git commit -m "chore: update weekly activity cache [skip ci]"
          git push
