name: Auto Release Generator

on:
  push:
    branches:
      - main
    paths:
      - 'project_version'  # 确保路径准确，不使用通配符

jobs:
  check-version-and-release:
    runs-on: ubuntu-latest
    permissions:
      contents: write  # 用于创建 releases
      pull-requests: write  # 可能需要的额外权限
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # 获取完整历史以检查变更

      - name: Debug Environment
        run: |
          echo "工作目录内容:"
          ls -la
          echo "project_version 文件内容:"
          cat project_version || echo "文件不存在"

      - name: Check if version changed
        id: check-version
        run: |
          # 获取当前版本号
          if [ -f "project_version" ]; then
            CURRENT_VERSION=$(cat project_version)
            echo "Current version: $CURRENT_VERSION"
            
            # 获取上一个提交中的版本号
            git fetch origin main
            if git show HEAD~1:project_version &>/dev/null; then
              PREVIOUS_VERSION=$(git show HEAD~1:project_version)
              echo "Previous version from commit: $PREVIOUS_VERSION"
              
              if [[ "$CURRENT_VERSION" != "$PREVIOUS_VERSION" ]]; then
                echo "Version changed from $PREVIOUS_VERSION to $CURRENT_VERSION"
                echo "version_changed=true" >> $GITHUB_OUTPUT
                echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
              else
                echo "Version unchanged"
                echo "version_changed=false" >> $GITHUB_OUTPUT
              fi
            else
              echo "Cannot find previous version, assuming first release"
              echo "version_changed=true" >> $GITHUB_OUTPUT
              echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
            fi
          else
            echo "project_version file not found"
            echo "version_changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Set up Python
        if: steps.check-version.outputs.version_changed == 'true'
        uses: actions/setup-python@v4
        with:
          python-version: '3.10'

      - name: Install OpenAI SDK
        if: steps.check-version.outputs.version_changed == 'true'
        run: pip install openai

      - name: Get commits since last release
        if: steps.check-version.outputs.version_changed == 'true'
        id: get-commits
        run: |
          # 直接获取最近10个提交
          echo "Getting last 13 commits"
          COMMITS=$(git log -13 --pretty=format:"%s")
          
          echo "Commits to be included in release notes:"
          echo "$COMMITS"
          
          echo "commits<<EOF" >> $GITHUB_OUTPUT
          echo "$COMMITS" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Generate release notes with AI
        if: steps.check-version.outputs.version_changed == 'true'
        id: generate-notes
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          OPENAI_BASE_URL: https://api.siliconflow.cn/v1
          CURRENT_VERSION: ${{ steps.check-version.outputs.current_version }}
        run: |
          cat > generate_release_notes.py << 'EOF'
          import os
          import sys
          from openai import OpenAI

          # 设置OpenAI客户端
          client = OpenAI(
              api_key=os.environ.get("OPENAI_API_KEY"),
              base_url=os.environ.get("OPENAI_BASE_URL")
          )

          # 获取提交信息和版本号
          commits = sys.stdin.read()
          version = os.environ.get("CURRENT_VERSION")

          # 调用API生成发布说明
          try:
              response = client.chat.completions.create(
                  model="deepseek-ai/DeepSeek-V3",
                  messages=[
                      {"role": "system", "content": "你是一个专业的软件发布说明生成助手。请根据提供的git提交信息，生成一个结构化的发布说明，包括新功能、改进、修复的bug等类别。使用中文回复。"},
                      {"role": "user", "content": f"请根据以下git提交信息,生成一个版本{version}的发布说明,内容详细且完整,相似的提交信息不要重复出现: \n\n{commits}"}
                  ],
                  temperature=0.7,
              )
              release_notes = response.choices[0].message.content
              print(f"commits: \n{commits}")
              print(f"大模型总结的发布说明: \n{release_notes}")
          except Exception as e:
              print(f"Error calling OpenAI API: {e}")
              release_notes = f"# 版本 {version} 发布\n\n## 更新内容\n\n"
              # 简单处理提交信息
              for line in commits.strip().split("\n"):
                  if line:
                      release_notes += f"- {line}\n"
          
          # 输出生成的发布说明
          print(release_notes)
          
          # 保存到GitHub输出
          with open(os.environ.get("GITHUB_OUTPUT"), "a") as f:
              f.write("release_notes<<RELEASE_NOTES_EOF\n")
              f.write(release_notes)
              f.write("\nRELEASE_NOTES_EOF\n")
          EOF
          
          python generate_release_notes.py < <(echo "${{ steps.get-commits.outputs.commits }}")

      - name: Debug release notes
        if: steps.check-version.outputs.version_changed == 'true'
        run: |
          echo "Generated release notes:"
          echo "${{ steps.generate-notes.outputs.release_notes }}"

      - name: Create GitHub Release
        if: steps.check-version.outputs.version_changed == 'true'
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ steps.check-version.outputs.current_version }}
          name: v${{ steps.check-version.outputs.current_version }}
          body: ${{ steps.generate-notes.outputs.release_notes }}
          draft: false
          prerelease: false
          token: ${{ secrets.GIT_TOKEN }} 