name: Create Daily Release

on:
  schedule:
    - cron: '1 0 * * *'  # Runs daily at 00:01 UTC
  workflow_dispatch:

jobs:
  create-daily-release:
    runs-on: runner-cluster-htl-set
    permissions:
      contents: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Extract first 5000 characters from CHANGELOG.md
        run: head -c 5000 CHANGELOG.md > changelog_cropped.md

      - name: Debugging - Show extracted changelog
        run: |
          echo "=== CHANGELOG EXCERPT ==="
          cat changelog_cropped.md
          echo "========================="

      - name: Parse CHANGELOG.md and create release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          YESTERDAY=$(date -u --date="yesterday" +%Y-%m-%d)
          echo "Checking for changes on: $YESTERDAY"

          # Ensure yesterday's date exists in the changelog
          if ! grep -q "## $YESTERDAY" changelog_cropped.md; then
            echo "No entry found for $YESTERDAY, skipping release."
            exit 0
          fi

          # Extract section for yesterday's date
          awk -v date="## $YESTERDAY" '
            $0 ~ date {found=1; next} 
            found && /^## [0-9]{4}-[0-9]{2}-[0-9]{2}/ {exit} 
            found
          ' changelog_cropped.md > changelog_tmp.md

          echo "=== Extracted Changelog ==="
          cat changelog_tmp.md
          echo "==========================="

          # Skip if no content was found
          if [ ! -s changelog_tmp.md ]; then
            echo "No changes found for $YESTERDAY, skipping release."
            exit 0
          fi

          # Create GitHub release
          gh release create "$YESTERDAY" -t "$YESTERDAY" -F changelog_tmp.md
