name: AI Issue Helper

on:
  issue_comment:
    types: [created]

permissions:
  issues: write
  contents: read
  models: read

jobs:
  ai-helper:
    runs-on: ubuntu-latest
    # 只在真实用户提到 @ai-helper 时触发，忽略机器人评论
    if: |
      contains(github.event.comment.body, '@ai-helper') &&
      github.event.comment.user.type != 'Bot'
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Get Issue Details
        id: issue
        uses: actions/github-script@v7
        with:
          script: |
            const issue = await github.rest.issues.get({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number
            });

            // 限制长度，避免超过 token 限制
            const maxLength = 1000;
            const truncate = (str, max) => {
              if (!str) return '';
              return str.length > max ? str.substring(0, max) + '...[内容过长已截断]' : str;
            };

            core.exportVariable('ISSUE_TITLE', truncate(issue.data.title || '', 200));
            core.exportVariable('ISSUE_BODY', truncate(issue.data.body || '', maxLength));
            core.exportVariable('COMMENT_BODY', truncate(context.payload.comment.body || '', 500));
            core.exportVariable('ISSUE_NUMBER', context.issue.number);

      - name: Create Prompt
        id: prompt
        run: |
          cat > prompt.txt << 'PROMPT_EOF'
          Issue #${{ env.ISSUE_NUMBER }}

          标题: ${{ env.ISSUE_TITLE }}

          内容: ${{ env.ISSUE_BODY }}

          评论: ${{ env.COMMENT_BODY }}

          请搜索项目代码并提供解决方案。
          PROMPT_EOF

      - name: AI Analysis
        uses: actions/ai-inference@v1
        id: ai
        with:
          model: 'gpt-4o'
          enable-github-mcp: true
          max-tokens: 1500
          system-prompt: |
            你是 ECS Framework (TypeScript ECS 框架) 的 AI 助手。
            主要代码在 packages/core/src。
            搜索相关代码后，用中文简洁回答问题，包含问题分析、解决方案和代码引用。
          prompt-file: prompt.txt

      - name: Post AI Response
        env:
          AI_RESPONSE: ${{ steps.ai.outputs.response }}
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: process.env.AI_RESPONSE
            });
