name: Build, Update History and Release

on:
  push:
    branches: [main]
  # Allow manual triggering
  workflow_dispatch:

permissions:
  contents: write
  issues: write
  pull-requests: write
  id-token: write

jobs:
  build-history-release:
    name: Build, Update History and Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22.14.0
          cache: 'npm'
          registry-url: 'https://registry.npmjs.org'
      - name: Use npm 11.6.0
        run: |
          corepack enable
          corepack prepare npm@11.6.0 --activate

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Test
        run: npm test

      - name: Generate history file
        run: npm run history

      - name: Check for changes
        id: git-check
        run: |
          git add README.md changes.svg
          git diff --staged --quiet || echo "changes=true" >> $GITHUB_OUTPUT

      - name: Commit changes if needed
        if: steps.git-check.outputs.changes == 'true'
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "GitHub Action"
          git commit --no-verify -m "docs: update README.md and changes.svg [skip ci]"
          git pull --rebase https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git main
          git push https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git HEAD:main
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: npx semantic-release
