name: Artifact Storage Check

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

jobs:
  check-storage:
    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."
