/**
 * 改写优化节点（rewriteNode）
 *
 * 当质量校验不通过时，根据校验报告的问题对不合格章节进行针对性改写。
 * 改写后回到 quality_check 重新校验，形成质量闭环。
 *
 * 与 quality-check.node.ts 配对使用：
 *   quality_check → (不通过) → rewrite → quality_check → ... → (通过) → continuity_edit
 */

import { GraphState } from '../graph';
import { bookStore } from '../book-generator.store';
import { callLLMWithMessages, ChatMessage } from '../../../services/llm';
import { callLLMWithRetry, executeNodeWithTimeout, FAULT_TOLERANCE_CONFIG } from '../fault-tolerance';
import { REWRITE_CHAPTER_SYSTEM_PROMPT } from '../prompts/templates';
import { PROGRESS } from '../utils';
import { prisma } from '../../../models';
import { FailedChapter, QualityCheckResult } from './quality-check.node';
import { regenerateChapter } from '../stage-manager';

// ============ 核心逻辑 ============

/**
 * 从 state 解析上次质量校验结果
 */
function parseQualityResultFromState(raw: string | undefined): QualityCheckResult | null {
  if (!raw) return null;
  try {
    const data = JSON.parse(raw);
    if (!data.failedChapters || data.failedChapters.length === 0) return null;
    return data as QualityCheckResult;
  } catch {
    return null;
  }
}

/**
 * 构建单个章节的改写消息
 */
function buildRewriteChapterMessages(
  bookTitle: string,
  chapterNumber: number,
  chapterTitle: string,
  originalContent: string,
  failedInfo: FailedChapter
): ChatMessage[] {
  // 构建问题清单
  const issuesText = failedInfo.issues
    .map((issue, i) =>
      `${i + 1}. [${issue.severity === 'high' ? '严重' : issue.severity === 'medium' ? '中等' : '轻微'}] ${issue.dimension}：${issue.description}\n   位置：${issue.location}\n   建议：${issue.suggestion}`
    )
    .join('\n\n');

  const scoreText = `通顺:${failedInfo.scores.fluency}/25 | 逻辑:${failedInfo.scores.logic}/25 | 跑题:${failedInfo.scores.relevance}/25 | 达标:${failedInfo.scores.completeness}/25 | 总分:${failedInfo.totalScore}/100`;

  return [
    { role: 'system', content: REWRITE_CHAPTER_SYSTEM_PROMPT },
    {
      role: 'user',
      content: `书名：《${bookTitle}》
## 第${chapterNumber}章：${chapterTitle}

### 质量评分
${scoreText}

### 重写方向
${failedInfo.rewriteInstructions}

### 发现的问题
${issuesText}

### 原始内容
${originalContent}

请根据以上反馈，改写本章内容并输出完整结果。`,
    },
  ];
}

/**
 * 解析改写响应
 */
function parseRewriteResponse(response: string): { title: string; rewrittenContent: string; changesSummary: string } | 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) {
      // 如果 AI 直接输出了内容（非 JSON），当作完整改写内容返回
      if (cleaned.length > 200) {
        return { title: '', rewrittenContent: cleaned, changesSummary: '直接输出改写内容' };
      }
      return null;
    }

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

    // 支持单章和多章格式
    if (Array.isArray(chapters) && chapters.length > 0) {
      return {
        title: chapters[0].title || '',
        rewrittenContent: chapters[0].rewrittenContent || chapters[0].content || '',
        changesSummary: chapters[0].changesSummary || '',
      };
    }

    // 单章直接格式
    if (data.rewrittenContent || data.content) {
      return {
        title: data.title || '',
        rewrittenContent: data.rewrittenContent || data.content || '',
        changesSummary: data.changesSummary || '',
      };
    }

    return null;
  } catch (err) {
    console.error('[Rewrite] 解析响应失败:', err);
    return null;
  }
}

/**
 * 改写单个章节
 * 返回改写后的内容，失败则返回 null
 */
async function rewriteSingleChapter(
  bookTitle: string,
  chapterId: number,
  chapterNumber: number,
  chapterTitle: string,
  originalContent: string,
  failedInfo: FailedChapter
): Promise<string | null> {
  try {
    console.log(`[Rewrite] 改写第${chapterNumber}章「${chapterTitle}」...`);

    const messages = buildRewriteChapterMessages(
      bookTitle, chapterNumber, chapterTitle, originalContent, failedInfo
    );

    const response = await callLLMWithRetry(
      messages,
      undefined,
      { bookId: String(chapterId), nodeId: 'rewrite', attempt: 0, maxAttempts: FAULT_TOLERANCE_CONFIG.aiRetry.maxRetries }
    );

    const parsed = parseRewriteResponse(response);
    if (!parsed || !parsed.rewrittenContent) {
      console.warn(`[Rewrite] 第${chapterNumber}章改写结果为空`);
      return null;
    }

    // 更新数据库
    await bookStore.updateChapterById(chapterId, {
      content: parsed.rewrittenContent,
    });

    console.log(`[Rewrite] 第${chapterNumber}章改写完成: ${parsed.changesSummary}`);
    return parsed.rewrittenContent;
  } catch (error) {
    console.error(`[Rewrite] 第${chapterNumber}章改写失败:`, error);
    return null;
  }
}

/**
 * 改写优化节点
 *
 * 读取质量校验结果，对不合格章节逐一改写。
 * 改写完成后返回 quality_check 重新校验。
 */
export async function rewriteNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
  const currentCount = state.rewriteCount;
  const maxCount = state.maxRewriteCount;

  console.log(`[Rewrite] 开始改写优化 (第${currentCount + 1}/${maxCount}轮), bookId:`, state.bookId);

  // 超过最大重写次数 → 智能降级：保留所有轮次中评分最高的版本
  if (currentCount >= maxCount) {
    console.warn(`[Rewrite] 已达最大重写次数(${maxCount})，执行智能降级...`);

    // 从 state.qualityResult 中解析历史评分，找出最优版本
    const qualityResult = parseQualityResultFromState(state.qualityResult);
    const bestChapterInfo = qualityResult?.failedChapters?.[0];

    let degradeMsg = `改写已达${maxCount}轮上限，`;
    if (bestChapterInfo && bestChapterInfo.totalScore > 0) {
      degradeMsg += `保留第${bestChapterInfo.chapterNumber}章最佳版本（评分${bestChapterInfo.totalScore}/100），`;
    }
    degradeMsg += '建议人工审核。';

    console.warn(`[Rewrite] ${degradeMsg}`);

    // 持久化降级标记到书籍记录
    try {
      await bookStore.update(state.bookId, {
        errorMsg: `[改写降级] ${degradeMsg}`,
      } as any);
    } catch { /* 记录日志失败不阻塞流程 */ }

    return {
      qualityPassed: true,       // 让流程继续（不高亮失败）
      progress: PROGRESS.CONTENT_END,
      // 不清除 qualityResult，前端可据此展示"需人工审核"提示
    };
  }

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

    const bookIdNum = parseInt(state.bookId);

    // 从 state 读取上次的质量校验结果
    const qualityResult = parseQualityResultFromState(state.qualityResult);
    if (!qualityResult || qualityResult.failedChapters.length === 0) {
      console.log('[Rewrite] 无不合格章节，跳过');
      return { qualityPassed: true, progress: state.progress };
    }

    console.log(`[Rewrite] 需要改写 ${qualityResult.failedChapters.length} 个章节`);

    let successCount = 0;
    let failCount = 0;

    for (const failedInfo of qualityResult.failedChapters) {
      // 从数据库获取对应章节
      const chapter = await prisma.bookChapter.findFirst({
        where: {
          bookId: bookIdNum,
          number: failedInfo.chapterNumber,
          level: 1, // 查找 level=1 的章
        },
        select: { id: true, title: true, content: true },
      });

      if (!chapter || !chapter.content) {
        console.warn(`[Rewrite] 未找到第${failedInfo.chapterNumber}章，跳过`);
        failCount++;
        continue;
      }

      // 先回退状态，允许重新写入
      await regenerateChapter(chapter.id, 'content_generating');

      // 改写
      const result = await rewriteSingleChapter(
        book.title,
        chapter.id,
        failedInfo.chapterNumber,
        chapter.title,
        chapter.content,
        failedInfo
      );

      if (result) {
        // 改写成功，标记为 content_completed
        await bookStore.updateChapterById(chapter.id, {
          genStage: 'content_completed',
        } as any);
        successCount++;
      } else {
        failCount++;
      }
    }

    console.log(`[Rewrite] 改写完成: ${successCount} 成功, ${failCount} 失败`);

    // 持久化改写记录
    await bookStore.update(state.bookId, {
      errorMsg: `[改写优化] 第${currentCount + 1}轮：${successCount}个成功，${failCount}个失败`,
    } as any);

    return {
      rewriteCount: 1, // 累加到 state，由 reducer 处理
      qualityPassed: false, // 重置，让 quality_check 重新判断
      progress: Math.min(state.progress + 2, PROGRESS.CONTENT_END - 3),
    };
  } catch (error) {
    console.error('[Rewrite] 改写失败:', error);
    return {
      rewriteCount: 1, // 累加到 state
      qualityPassed: true, // 容错：失败时通过，避免死循环
      progress: PROGRESS.CONTENT_END,
    };
  }
}
