name: Auto Release with Version Check

on:
  push:
    branches:
      - main

jobs:
  release:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Pobierz pełną historię Git (potrzebne do git log)

      - name: Extract base version from pyproject.toml
        id: version
        run: |
          base=$(grep '^version *= *"' pyproject.toml | sed -E 's/version *= *"([^"]+)"/\1/')
          echo "base_version=$base" >> $GITHUB_OUTPUT

      - name: Check if tag for this version already exists
        run: |
          TAG="v${{ steps.version.outputs.base_version }}"
          git fetch --tags
          if git rev-parse "$TAG" >/dev/null 2>&1; then
            echo "Tag $TAG already exists. Skipping release."
            exit 0
          fi

      - name: Set version tag
        id: unique_tag
        run: |
          echo "final_tag=v${{ steps.version.outputs.base_version }}" >> $GITHUB_OUTPUT

      # ZMIANA: Poprawione obsługa multi-line output (z delimiterem EOF, bez zastępowania \n)
      - name: Get commit history since last version tag
        id: commit_history
        run: |
          VERSION_TAG="v${{ steps.version.outputs.base_version }}"
          git fetch --tags

          if git rev-parse "$VERSION_TAG" >/dev/null 2>&1; then
            RANGE="$VERSION_TAG..HEAD"
          else
            RANGE="HEAD"
          fi

          HISTORY=$(git log --pretty=format:"%s" $RANGE | \
            grep -vE '^\s*(add|update|fix|change|edit|mod|modify|cleanup|misc|typo|readme|temp|test|debug)\b' | \
            grep -vE '^(\s*Update|Add|Fix|Change|Edit|Refactor|Bump|Minor|Misc|Readme|Test)[^a-zA-Z0-9]*$' | \
            sed 's/^/- /')

          if [ -z "$HISTORY" ]; then
            HISTORY="No significant changes since last release."
          fi

          echo "commit_history<<EOF" >> $GITHUB_OUTPUT
          echo "$HISTORY" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.unique_tag.outputs.final_tag }}
          name: Release ${{ steps.unique_tag.outputs.final_tag }}    
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}