name: Generate changelog
on:
  workflow_call:
    inputs:
      previous_version:
        type: string
        required: false
        description: 'The release version (semver, git tag, branch or commit) to use for comparison'
      version:
        type: string
        required: true
        description: 'Target release version (semver, git tag, branch or commit)'
      target:
        required: true
        type: string
        description: 'The base branch that these changes are being merged into'
      dry_run:
        required: false
        default: false
        type: boolean
      latest:
        required: false
        default: false
        type: boolean
      work_branch:
        required: false
        type: string
        description: "Use specific branch for changelog"

  workflow_dispatch:
    inputs:
      previous_version:
        type: string
        required: false
        description: 'The release version (semver, git tag, branch or commit) to use for comparison'
      version:
        type: string
        required: true
        description: 'Target release version (semver, git tag, branch or commit)'
      target:
        required: true
        type: string
        description: 'The base branch that these changes are being merged into'
      dry_run:
        required: false
        default: false
        type: boolean
      latest:
        required: false
        default: false
        type: boolean
      work_branch:
        required: false
        type: string
        description: "Use specific branch for changelog"

permissions: {}

jobs:
  main:
    env:
      RUN_ID: ${{ github.run_id }}
      VERSION: ${{ inputs.version }}
      PREVIOUS_VERISON: ${{ inputs.previous_version }}
      TARGET: ${{ inputs.target }}
      DRY_RUN: ${{ inputs.dry_run }}
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: write
      pull-requests: write
    steps:
      - name: Get GitHub App token
        id: get-github-app-token
        uses: grafana/shared-workflows/actions/create-github-app-token@259ba21cb3ff07724f331e26d926d655d24b317b # create-github-app-token/v0.2.3
        with:
          github_app: grafana-delivery-bot
      - name: "Checkout Grafana repo"
        uses: "actions/checkout@v5"
        with:
          ref: main
          sparse-checkout: |
            .github/workflows
            .github/actions
            CHANGELOG.md
            .nvmrc
            .prettierignore
            .prettierrc.js
          fetch-depth: 0
          fetch-tags: true
      - name: Setup Node.js
        uses: ./.github/actions/setup-node
      - name: "Configure git user"
        run: |
          git config --local user.name "github-actions[bot]"
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local --add --bool push.autoSetupRemote true
      - name: "Create branch"
        run: |
          if [[ "$WORK_BRANCH" == '' ]]; then
            git switch -c "changelog/${RUN_ID}/${VERSION}"
            exit 0
          fi

          # Checkout the changelog branch if exists, otherwise create a new one
          if git show-ref --verify --quiet "refs/remotes/origin/$WORK_BRANCH"; then
            git switch --track "origin/$WORK_BRANCH"
          else
            git switch -c "$WORK_BRANCH"
          fi
        env:
          WORK_BRANCH: ${{ inputs.work_branch }}
      - name: "Generate changelog"
        id: changelog
        uses: ./.github/actions/changelog
        with:
          previous: ${{ inputs.previous_version }}
          github_token: ${{ steps.get-github-app-token.outputs.token }}
          target: v${{ inputs.version }}
          output_file: changelog_items.md
      - name: "Patch CHANGELOG.md"
        run: |
          # Prepare CHANGELOG.md content with version delimiters
          (
            echo
            echo "# ${VERSION} ($(date '+%F'))"
            echo
            cat changelog_items.md
          ) > CHANGELOG.part

          # Check if a version exists in the changelog
          if grep -q "<!-- ${VERSION} START" CHANGELOG.md ; then
            # Replace the content between START and END delimiters
            echo "Version ${VERSION} is found in the CHANGELOG.md, patching contents..."
            sed -i -e "/${VERSION} START/,/${VERSION} END/{//!d;}" \
                   -e "/${VERSION} START/r CHANGELOG.part" CHANGELOG.md
          else
            # Prepend changelog part to the main changelog file
            echo "Version $VERSION not found in the CHANGELOG.md"
            (
              echo "<!-- ${VERSION} START -->"
              cat CHANGELOG.part
              echo "<!-- ${VERSION} END -->"
              cat CHANGELOG.md
            ) > CHANGELOG.tmp
            mv CHANGELOG.tmp CHANGELOG.md
          fi

          git diff CHANGELOG.md

      - name: "Prettify CHANGELOG.md"
        run: npx prettier --write CHANGELOG.md
      - name: "Commit changelog changes"
        run: git add CHANGELOG.md && git commit --allow-empty -m "Update changelog" CHANGELOG.md
      - name: "git push"
        if: inputs.dry_run != true
        run: git push
      - name: "Create changelog PR"
        run: |
          if gh pr view &>/dev/null; then
            echo "Changelog pr has already been created"
          else

            gh pr create \
              --dry-run="${DRY_RUN}" \
              --draft \
              --label "no-backport" \
              --label "no-changelog" \
              -B "${TARGET}" \
              --title "Release: update changelog for ${TARGET}" \
              --body "Changelog changes for release versions:"
          fi
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: "Add release version to PR description"
        if: inputs.dry_run != true
        run: |
          gh pr view --json body --jq .body > pr_body.md
          echo " -  ${VERSION}" >> pr_body.md
          gh pr edit --body-file pr_body.md
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
