##
## =====================================================================================
##  C O P Y R I G H T
## -------------------------------------------------------------------------------------
##  Copyright (c) 2023 by Robert Bosch GmbH. All rights reserved.
##
##  Author(s):
##  - Markus Braun, :em engineering methods AG (contracted by Robert Bosch GmbH)
## =====================================================================================
##

name: CI

on:
  push:
    branches:
      - main
  pull_request:

permissions:
  contents: write

env:
  python-version: 3.9

jobs:
  ci:
    runs-on: ubuntu-latest

    steps:
    - name: "Checkout Code"
      uses: actions/checkout@v4
      with:
        submodules: false
        fetch-depth: 0

    - name: "Ensure Python/Build Environment"
      uses: ./.github/actions/init
      with:
        python-version: ${{ env.python-version }}

    - name: "Run Tests"
      run: |
        mkdir -p docs/doxygen
        poetry run pytest --emoji -v -s --md $GITHUB_STEP_SUMMARY

    - name: "cache pre-commit"
      uses: actions/cache@v4
      with:
        path: ~/.cache/pre-commit
        key: ${{ runner.os }}-py${{ env.python-version }}-precommit-${{ hashFiles('.pre-commit-config.yaml') }}
        restore-keys: |
          ${{ runner.os }}-py${{ env.python-version }}

    - name: "Run quality checks"
      run: |
        SKIP=poetry-lock poetry run pre-commit run --all-files

    - name: "Update version, changelog"
      if: github.event_name == 'push' && github.ref == 'refs/heads/main' && !contains(github.event.head_commit.message, 'chore(release):')
      id: versionbump
      run: |
        git config user.email "actions@github.com"
        git config user.name "github-actions"
        poetry run cz bump --changelog
        git push
        git push --tags
        export VERSION=$(poetry version -s)
        poetry run cz changelog --dry-run $VERSION
        poetry run cz changelog --file-name RELEASE_NOTES.md $VERSION
        echo "::set-output name=new_version_tag::v$VERSION"
        git switch --detach v$VERSION
      env:
        GH_TOKEN: ${{ secrets.GITHUBTOKEN }}

    - name: "Create Release (will be filled in cd)"
      if: github.event_name == 'push' && github.ref == 'refs/heads/main' && !contains(github.event.head_commit.message, 'chore(release):')
      uses: softprops/action-gh-release@v1
      with:
        body_path: RELEASE_NOTES.md
        tag_name: ${{ steps.versionbump.outputs.new_version_tag }}
        token: ${{ secrets.GITHUBTOKEN }}
