name: Clean Old Nightly Releases
on:
  schedule:
    - cron: '* 6 * * *'
permissions:
  contents: write
jobs:
  cleanup:
    name: Delete old nightly releases and tags
    runs-on: ubuntu-latest
    if: github.repository == 'nunchaku-tech/nunchaku'
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      - name: List all nightly releases
        id: list
        run: |
          gh release list --limit 100 --json tagName,isPrerelease,publishedAt \
            --jq '.[] | select(.isPrerelease == true) | .tagName' > nightly_tags.txt
          echo "Found $(wc -l < nightly_tags.txt) nightly releases."
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: Trim to old tags beyond latest 15
        id: filter
        run: |
          tail -n +16 nightly_tags.txt > to_delete.txt || true
          echo "Tags to delete:"
          cat to_delete.txt || echo "(none)"
      - name: Delete releases and tags
        run: |
          while read tag; do
            echo "Deleting release and tag: $tag"
            gh release delete "$tag" -y || true
            git push origin --delete "$tag" || true
          done < to_delete.txt
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: Done
        run: echo "Nightly cleanup completed."
