name: Update changelog

on:
  workflow_dispatch:
  push:
    branches: [develop]

jobs:
  update-changelog:
    name: Update changelog
    runs-on: ubuntu-latest
    steps:
    - name: Checkout the repo
      uses: actions/checkout@v4
      with:
        # Get history and tags for SCM versioning to work
        fetch-depth: 0
    - name: Install the latest version of uv with cache enabled
      uses: astral-sh/setup-uv@v3
      with:
        version: "latest"
        enable-cache: true
        cache-dependency-glob: ""
    - name: Install python-semantic-release and packaging in venv
      run: |
        uv venv
        source .venv/bin/activate
        uv pip install python-semantic-release packaging
    - name: Get expected new version, update changelog and documentation
      run: |
        source .venv/bin/activate
        EXPECTED_VERSION=$(semantic-release --noop version --print)
        EXPECTED_TAG="v$EXPECTED_VERSION"
        TODAY=$(date +"%Y-%m-%d")
        TITLE="$EXPECTED_TAG ($TODAY)"
        TITLE_LENGTH=${#TITLE}

        semantic-release changelog

        sed -i -e "/^\.\. _changelog-unreleased:$/d" \
              -e "/^Unreleased$/{
        s//${TITLE}/
        n
        s/^=*$/$(printf '%*s' "$TITLE_LENGTH" '' | tr ' ' '=')/
        }" CHANGES.rst

        NEXT_DEV_VERSION=$(python -c "from packaging.version import Version; v=Version('$EXPECTED_VERSION'); print(f'{v.major}.{v.minor}.{v.micro +1}.dev0')")

        sed -i "s/fallback_version = \".*\"/fallback_version = \"$NEXT_DEV_VERSION\"/" pyproject.toml

        echo "EXPECTED_TAG=$EXPECTED_TAG" >> $GITHUB_ENV

    - name: Create Pull Request
      uses: peter-evans/create-pull-request@v6
      with:
        branch: new-release
        delete-branch: true
        draft: true
        title: 'build: bump version'
        body: |
          `${{ env.EXPECTED_TAG }}` release.

          2 files were updated:

          [CHANGES.rst](https://github.com/CS-SI/eodag/blob/new-release/CHANGES.rst), and version updated in:
          - [pyproject.toml](https://github.com/CS-SI/eodag/blob/new-release/pyproject.toml?plain=1#L6)
        labels: |
          automated pr
