/**
 * 连贯性编辑节点（continuityEditNode）
 *
 * 在所有内容并行生成完后，执行一次全局编辑：
 * - 检查章节过渡是否自然
 * - 检查内容重复
 * - 术语统一
 * - 风格一致性
 * - 交叉引用正确性
 *
 * 输出评估报告和修正后的内容。
 */

import { GraphState } from '../graph';
import { bookStore } from '../book-generator.store';
import { callLLMWithMessages, ChatMessage } from '../../../services/llm';
import { CONTINUITY_EDIT_SYSTEM_PROMPT } from '../prompts/templates';
import { PROGRESS } from '../utils';
import { prisma } from '../../../models';

export interface ContinuityEditResult {
  overallAssessment: string;
  issues: Array<{
    type: 'transition' | 'duplicate' | 'terminology' | 'style' | 'crossref';
    location: string;
    description: string;
    suggestion: string;
    severity: 'high' | 'medium' | 'low';
  }>;
  fixedContent: Record<string, string>;
}

/**
 * 构建连贯性编辑消息
 */
function buildContinuityEditMessages(
  bookTitle: string,
  chapterContents: Array<{ title: string; content: string }>
): ChatMessage[] {
  const chaptersText = chapterContents
    .map((ch, i) => `### 第${i + 1}章：${ch.title}\n\n${ch.content}`)
    .join('\n\n---\n\n');

  return [
    { role: 'system', content: CONTINUITY_EDIT_SYSTEM_PROMPT },
    {
      role: 'user',
      content: `书名：《${bookTitle}》
      
以下是全书各章节的完整内容，请检查并修复连贯性问题：

${chaptersText}

请输出 JSON 格式的评估报告和修正内容。`,
    },
  ];
}

/**
 * 解析连贯性编辑结果
 */
function parseContinuityEditResponse(response: string): ContinuityEditResult | null {
  try {
    let cleaned = response.trim();
    const thinkEnd = cleaned.indexOf('</think>');
    if (thinkEnd !== -1) cleaned = cleaned.substring(thinkEnd + 8).trim();
    const match = cleaned.match(/\{[\s\S]*\}/);
    if (!match) return null;

    const data = JSON.parse(match[0]);

    return {
      overallAssessment: data.overallAssessment || '',
      issues: data.issues || [],
      fixedContent: data.fixedContent || {},
    };
  } catch {
    return null;
  }
}

/**
 * 连贯性编辑节点
 */
export async function continuityEditNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
  console.log('[ContinuityEdit] 开始连贯性编辑, bookId:', state.bookId);

  try {
    const book = await bookStore.getById(state.bookId);
    if (!book) {
      console.log('[ContinuityEdit] 书籍不存在，跳过');
      return { progress: PROGRESS.CONTENT_END };
    }

    const bookIdNum = parseInt(state.bookId);

    // 获取所有已完成内容的叶节点
    const leafChapters = await prisma.bookChapter.findMany({
      where: {
        bookId: bookIdNum,
        genStage: 'content_completed',
        content: { not: '' },
      },
      orderBy: { number: 'asc' },
    });

    if (leafChapters.length === 0) {
      console.log('[ContinuityEdit] 无已完成内容的章节，跳过');
      return { progress: PROGRESS.CONTENT_END };
    }

    // 只取 level=1 的章进行编辑（避免内容重复）
    const topChapters = await prisma.bookChapter.findMany({
      where: {
        bookId: bookIdNum,
        level: 1,
        genStage: 'content_completed',
        content: { not: '' },
      },
      orderBy: { number: 'asc' },
    });

    if (topChapters.length < 2) {
      console.log('[ContinuityEdit] 少于2章，无需连贯性编辑');
      return { progress: PROGRESS.CONTENT_END };
    }

    console.log(`[ContinuityEdit] 编辑 ${topChapters.length} 章内容`);

    const chapterInfos = topChapters.map(ch => ({
      title: ch.title,
      content: ch.content,
    }));

    const messages = buildContinuityEditMessages(book.title, chapterInfos);
    const response = await callLLMWithMessages(messages);
    const result = parseContinuityEditResponse(response);

    if (result) {
      console.log(`[ContinuityEdit] 评估: ${result.overallAssessment}`);
      console.log(`[ContinuityEdit] 问题数: ${result.issues.length}`);

      // 记录高严重性问题
      const highIssues = result.issues.filter(i => i.severity === 'high');
      if (highIssues.length > 0) {
        console.warn(`[ContinuityEdit] ⚠️ ${highIssues.length} 个高严重性问题:`);
        highIssues.forEach(i => console.warn(`  - [${i.type}] ${i.location}: ${i.description}`));
      }

      // 应用修正内容（如果有）
      const fixedKeys = Object.keys(result.fixedContent).filter(k => result.fixedContent[k]);
      if (fixedKeys.length > 0) {
        console.log(`[ContinuityEdit] 应用 ${fixedKeys.length} 处修正`);
        // 注意：这里简化处理，fixedContent 的 key 映射到章节索引
        for (const key of fixedKeys) {
          const match = key.match(/\d+/);
          if (match) {
            const chapterIdx = parseInt(match[0]) - 1;
            if (chapterIdx >= 0 && chapterIdx < topChapters.length) {
              const chapterId = topChapters[chapterIdx].id;
              await bookStore.updateChapterById(chapterId, {
                content: result.fixedContent[key],
              });
            }
          }
        }
      }

      // 持久化评估报告
      await bookStore.update(state.bookId, {
        errorMsg: `[连贯性编辑] ${result.overallAssessment} | 问题: ${result.issues.length}个`,
      } as any);
    } else {
      console.warn('[ContinuityEdit] 解析结果失败，跳过编辑');
    }

    console.log('[ContinuityEdit] 连贯性编辑完成');
    return { progress: PROGRESS.CONTENT_END };
  } catch (error) {
    console.error('[ContinuityEdit] 编辑失败:', error);
    await bookStore.update(state.bookId, { errorMsg: `连贯性编辑失败: ${error instanceof Error ? error.message : '未知'}` } as any);
    // 不阻塞流程
    return { progress: PROGRESS.CONTENT_END, error: '连贯性编辑失败' };
  }
}
