# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license

# Purge jsdelivr CDN cache when JavaScript files are updated to ensure users get latest versions immediately

name: Purge CDN Cache

on:
  push:
    branches: [main]
    paths:
      - "js/**"
  workflow_dispatch:
  workflow_run:
    workflows: ["Tag and Release"]
    types: [completed]

permissions:
  contents: read

jobs:
  purge:
    runs-on: ubuntu-latest
    steps:
      - name: Purge jsdelivr CDN
        run: |
          FILES=("js/chat.js" "js/chat.min.js")
          VERSIONS=("main" "master" "latest")

          echo "Purging jsdelivr CDN cache for ${{ github.repository }}..."
          SUCCESS=0
          FAILED=0

          for file in "${FILES[@]}"; do
            for version in "${VERSIONS[@]}"; do
              URL="https://purge.jsdelivr.net/gh/${{ github.repository }}@$version/$file"
              echo "Purging: $file@$version"
              echo "URL: $URL"
              
              # Capture both stdout and stderr, plus HTTP code
              HTTP_RESPONSE=$(mktemp)
              HTTP_CODE=$(curl -sS -w "%{http_code}" -o "$HTTP_RESPONSE" "$URL" 2>&1 || echo "000")
              BODY=$(cat "$HTTP_RESPONSE" 2>/dev/null || echo "")
              rm -f "$HTTP_RESPONSE"
              
              echo "HTTP Code: $HTTP_CODE"
              if [ -n "$BODY" ]; then
                echo "Response: $BODY"
              fi
              
              if [[ "$HTTP_CODE" =~ ^2[0-9]{2}$ ]]; then
                echo "✓ Success: $file@$version"
                SUCCESS=$((SUCCESS + 1))
              else
                echo "✗ Failed: $file@$version"
                FAILED=$((FAILED + 1))
              fi
              echo ""
              sleep 1
            done
          done

          echo "CDN purge summary: $SUCCESS successful, $FAILED failed"

          # Exit with error if all purges failed
          if [ $SUCCESS -eq 0 ]; then
            echo "Error: All CDN purges failed"
            exit 1
          elif [ $FAILED -gt 0 ]; then
            echo "Warning: Some purges failed but at least one succeeded"
          fi
