name: AI CHANGELOG Update

on:
  workflow_dispatch:
    inputs:
      PR:
        description: 'Creat Pull Request'
        default: false
        type: boolean

jobs:
  changelog_update:
    permissions:
      contents: write
      pull-requests: write
      models: read

    runs-on: ubuntu-latest

    env:
      CURRENT_TAG: ''
      DIFF_DATA: ''

    steps:
      - name: Checkout repository (main branch and all commits)
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          ref: main

      - name: Install Go
        uses: actions/setup-go@v6
        with:
          go-version: 1.25

      - name: Get app version for diff
        run: |
          CURRENT_TAG=$(go run main.go -v)
          echo "CURRENT_TAG=$CURRENT_TAG" >> $GITHUB_ENV

      - name: Get diff from git
        id: get_diff
        run: |
          LATEST_TAG=$(git describe --tags --abbrev=0)
          if [ -z "$LATEST_TAG" ]; then
            DIFF=$(git log --oneline -n 100)
          else
            DIFF=$(git log "$LATEST_TAG..HEAD" --oneline)
          fi
          {
            echo "DIFF_DATA<<EOF"
            echo "$DIFF"
            echo "EOF"
          } >> $GITHUB_ENV

      - name: Generate CHANGELOG using AI
        id: ai_query
        uses: actions/ai-inference@v2
        with:
          model: gpt-4.1
          max-tokens: 2048
          system-prompt: |
            You are a technical writer.
            Analyze the Git commit log and create a summary of the changes.
            Focus on changes in the code and ignore any changes related to the GitHub Actions system.
            The summary must be in Markdown format in English and contain two key headings: "### New features" and "### Fixes"
            There is no need to add a release title and commit numbers.
          prompt: |
            Analyze these changes for release ${{ env.CURRENT_TAG }}:
            ${{ env.DIFF_DATA }}

      - name: Update CHANGELOG file
        env:
          AI_RESPONSE: ${{ steps.ai_query.outputs.response }}
        run: |
          REPORT_ORIGIN_FILE="CHANGELOG.md"
          REPORT_TEMP_FILE="CHANGELOG.tmp"
          echo -e "## Release ${{ env.CURRENT_TAG }}\n" > $REPORT_TEMP_FILE
          echo -e "$AI_RESPONSE\n" >> $REPORT_TEMP_FILE
          cat "$REPORT_TEMP_FILE" >> $GITHUB_STEP_SUMMARY
          if [ -f "$REPORT_ORIGIN_FILE" ]; then
            cat "$REPORT_ORIGIN_FILE" >> $REPORT_TEMP_FILE
          fi
          mv $REPORT_TEMP_FILE $REPORT_ORIGIN_FILE

      - name: Create PR
        if: ${{ github.event.inputs.PR == 'true' }}
        uses: peter-evans/create-pull-request@v8
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: "update changelog file using ai for ${{ env.CURRENT_TAG }} release"
          branch: "docs/changelog"
          title: "CHANGELOG update"
          body: "AI-powered CHANGELOG file update"
          add-paths: |
            CHANGELOG.md