name: Artifact Storage Check

on:
  schedule:
    # Run every 6 hours
    - cron: '0 */6 * * *'
  workflow_dispatch:

jobs:
  cleanup-expired:
    runs-on: ubuntu-latest

    steps:
      - name: Delete artifacts older than 3 days
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          echo "Fetching all artifacts..."
          gh api "repos/${{ github.repository }}/actions/artifacts" \
            --paginate -q '.artifacts[] | "\(.id)\t\(.created_at)\t\(.name)"' > /tmp/all_artifacts.txt

          total=$(wc -l < /tmp/all_artifacts.txt)
          echo "Found $total total artifacts"

          cutoff=$(date -u -d '3 days ago' '+%Y-%m-%dT%H:%M:%SZ')
          echo "Deleting artifacts created before $cutoff"

          deleted=0
          while IFS=$'\t' read -r id created_at name; do
            if [[ "$created_at" < "$cutoff" ]]; then
              gh api -X DELETE "repos/${{ github.repository }}/actions/artifacts/$id" 2>/dev/null && deleted=$((deleted + 1))
              if [ $((deleted % 50)) -eq 0 ]; then
                echo "Deleted $deleted artifacts so far..."
              fi
            fi
          done < /tmp/all_artifacts.txt

          echo "Cleanup complete. Deleted $deleted expired artifacts out of $total total."
          rm -f /tmp/all_artifacts.txt

  check-storage:
    needs: cleanup-expired
    runs-on: ubuntu-latest

    steps:
      - name: Check artifact storage size
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          # Calculate total artifact storage
          total_bytes=$(gh api "repos/${{ github.repository }}/actions/artifacts" \
            --paginate -q '.artifacts[].size_in_bytes' | awk '{sum+=$1} END {print sum}')

          total_mb=$((total_bytes / 1024 / 1024))
          echo "Total artifact storage: ${total_mb} MB"

          # Fail if over 500MB
          if [ "$total_mb" -gt 500 ]; then
            echo "::error::Artifact storage is ${total_mb} MB, which exceeds the 500 MB threshold!"
            echo ""
            echo "Largest artifacts:"
            # Save to temp file to avoid SIGPIPE/broken pipe errors with head
            gh api "repos/${{ github.repository }}/actions/artifacts" \
              --paginate -q '.artifacts[] | "\(.size_in_bytes)\t\(.name)\t\(.created_at)"' > /tmp/artifacts.txt
            sort -rn /tmp/artifacts.txt | head -20 | \
              awk -F'\t' '{printf "%d MB\t%s\t%s\n", $1/1024/1024, $2, $3}'
            rm -f /tmp/artifacts.txt
            exit 1
          fi

          echo "Storage is within acceptable limits."
