/**
 * 策略4 - DeepPlan + RichOutline + ParallelContent + QualityCheck + Rewrite + ContinuityEdit（推荐策略）
 *
 * 工作流：
 *   deep_plan → rich_outline → parallel_content → quality_check
 *                                                      ↓
 *                                          ┌── 通过 ──→ continuity_edit → END
 *                                          ↓ 不通过
 *                                        rewrite → quality_check (循环，最多3次)
 *
 * 特点：
 *   1. DeepPlan: AI深度分析书籍需求，规划goldenThread/narrativeArc/toneProfile/audienceCalibration
 *   2. RichOutline: 生成带writingInstructions的富信息大纲（每节点含opening/structure/mustCover等）
 *   3. ParallelContent: 并发8路生成所有叶节点内容
 *   4. QualityCheck: 四维质量校验（通顺/逻辑/跑题/达标）【新增】
 *   5. Rewrite: 不合格章节自动改写优化，形成质量闭环【新增】
 *   6. ContinuityEdit: 全局连贯性编辑，检查过渡/重复/术语/风格一致性
 *
 * 修复的问题：
 *   - issue #2: 内容生成纯串行 → 并发生成
 *   - issue #3: 基于正则的需求分析 → AI深度规划
 *   - issue #4: 暴力截断 → 智能段落边界截断
 *   - issue #5: 思考文本清理不彻底 → 多模式清洗
 *   - issue #6: 大纲空壳未填充 → writingInstructions引导
 *   - issue #7: 章节创建竞态 → upsert去重
 *   - issue #10: 无大纲质量评估 → 内置评分
 *   - issue #11: 正文无质量校验 → 四维评估 + 自动改写闭环【本次新增】
 */

import { StateGraph, END } from '@langchain/langgraph';
import { GraphState } from '../graph';
import { deepPlanBookNode } from '../nodes/deep-plan.node';
import { richOutlineNode } from '../nodes/rich-outline.node';
import { writeChaptersParallelNode } from '../nodes/content.node';
import { qualityCheckNode } from '../nodes/quality-check.node';
import { rewriteNode } from '../nodes/rewrite.node';
import { continuityEditNode } from '../nodes/continuity-edit.node';
import { runGraphWorkflow } from './base';
import { GenerationStrategy } from './types';

export class DeepPlanParallelStrategy implements GenerationStrategy {
  readonly name = 'deep-plan-parallel' as const;
  readonly description = 'DeepPlan+RichOutline+Concurrent+QualityCheck+Rewrite+Edit（推荐）：完整质量闭环';

  async generate(
    bookId: string,
    topic: string,
    bookScale: string,
    genLevel: number,
    userSpecifiedGenLevel?: number
  ): Promise<void> {
    console.log(`[Strategy-deep-plan-parallel] 开始, bookId=${bookId}, scale=${bookScale}, genLevel=${genLevel}, userSpecified=${userSpecifiedGenLevel}`);

    const workflow = new StateGraph(GraphState)
      .addNode('deep_plan', deepPlanBookNode)
      .addNode('rich_outline', richOutlineNode)
      .addNode('parallel_content', writeChaptersParallelNode)
      .addNode('quality_check', qualityCheckNode)
      .addNode('rewrite', rewriteNode)
      .addNode('continuity_edit', continuityEditNode)
      .setEntryPoint('deep_plan')
      .addEdge('deep_plan', 'rich_outline')
      .addEdge('rich_outline', 'parallel_content')
      .addEdge('parallel_content', 'quality_check')
      // 条件路由：质量校验通过 → 连续性编辑；不通过 → 改写优化
      .addConditionalEdges('quality_check', (state: typeof GraphState.State) => {
        if (!state.qualityPassed && state.rewriteCount < state.maxRewriteCount) {
          console.log(`[Strategy] 质量校验不通过 → 改写优化 (第${state.rewriteCount + 1}/${state.maxRewriteCount}轮)`);
          return 'rewrite';
        }
        if (!state.qualityPassed) {
          console.log(`[Strategy] 质量校验不通过，已达最大重写次数(${state.maxRewriteCount}) → 跳过改写`);
        }
        console.log('[Strategy] 质量校验通过 → 连贯性编辑');
        return 'continuity_edit';
      })
      // rewrite 完成后回到 quality_check 重新校验
      .addEdge('rewrite', 'quality_check')
      .addEdge('continuity_edit', END);

    const initialState: typeof GraphState.State = {
      bookId,
      topic,
      bookScale,
      genLevel,
      userSpecifiedGenLevel,
      userId: '',
      description: undefined,
      bookPlan: undefined,
      currentChapter: 0,
      completedChapters: [],
      finished: false,
      error: undefined,
      progress: 0,
      failedChapters: [],
      qualityPassed: true,
      rewriteCount: 0,
      maxRewriteCount: 3,
      qualityResult: undefined,
    };

    await runGraphWorkflow(bookId, initialState, workflow);
  }
}
