name: Auto Close Invalid Issues

on:
  issues:
    types: [opened]

jobs:
  check-issue:
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - uses: actions/github-script@v7
        env:
          ABUSIVE_WORDS: ${{ secrets.ABUSIVE_WORDS }}
        with:
          script: |
            const { owner, repo } = context.repo;
            const issue_number = context.payload.issue.number;
            const title = (context.payload.issue.title || '').toLowerCase();
            const body  = (context.payload.issue.body  || '').toLowerCase();
            const text  = title + ' ' + body;

            // --- 第一层：攻击性内容（词库存于 Secret: ABUSIVE_WORDS，逗号分隔）---
            const abusiveWords = (process.env.ABUSIVE_WORDS || '').split(',').map(w => w.trim()).filter(Boolean);
            const isAbusive = abusiveWords.some(w => w && text.includes(w.toLowerCase()));

            if (isAbusive) {
              await github.rest.issues.createComment({
                owner, repo, issue_number,
                body: [
                  '你好，',
                  '',
                  '此 Issue 包含不文明内容，已自动关闭。',
                  '',
                  '我们欢迎任何建设性的反馈，但请保持礼貌和尊重。',
                  '如有 Bug 或功能建议，请使用官方模板重新提交，谢谢。',
                ].join('\n'),
              });
              await github.rest.issues.update({
                owner, repo, issue_number,
                state: 'closed',
                state_reason: 'not_planned',
              });
              await github.rest.issues.addLabels({
                owner, repo, issue_number,
                labels: ['invalid'],
              });
              return;
            }

            // --- 第二层：未走模板 ---
            const templateMarkers = [
              '### 运行平台',
              '### 问题描述',
              '### 复现步骤',
              '### 需求背景',
              '### 建议方案',
            ];
            const isFromTemplate = templateMarkers.some(m => body.includes(m.toLowerCase()));

            if (!isFromTemplate) {
              await github.rest.issues.createComment({
                owner, repo, issue_number,
                body: [
                  '感谢你的反馈！',
                  '',
                  '此 Issue 未按照模板填写，已自动关闭。',
                  '',
                  '请使用以下方式重新提交：',
                  '- 🐛 **Bug 报告** → 使用 [Bug 报告模板](../../issues/new?template=bug_report.yml)',
                  '- 💡 **功能建议** → 使用 [功能建议模板](../../issues/new?template=feature_request.yml)',
                  '- 💬 **使用咨询** → 前往 [Discussions](../../discussions) 提问',
                ].join('\n'),
              });
              await github.rest.issues.update({
                owner, repo, issue_number,
                state: 'closed',
                state_reason: 'not_planned',
              });
              await github.rest.issues.addLabels({
                owner, repo, issue_number,
                labels: ['invalid'],
              });
            }
