/**
 * 策略3 - Per-Chapter（逐章内聚）
 *
 * 工作流：
 *   plan_book → generate_outline → per_chapter (批量并行)
 *
 * 特点：
 *   先生成章大纲（仅章节列表），然后每章独立生成内部结构+内容
 *   各章可并行执行（并发数可配置）
 *   调用量：~1(规划) + 1(大纲) + N(章节数) 次 AI
 */

import { StateGraph, END } from '@langchain/langgraph';
import { GraphState } from '../graph';
import { planBookNode } from '../nodes/plan.node';
import { generateOutlineNode } from '../nodes/outline.node';
import { perChapterNode } from '../nodes/per-chapter.node';
import { runGraphWorkflow } from './base';
import { GenerationStrategy } from './types';

export class PerChapterStrategy implements GenerationStrategy {
  readonly name = 'per-chapter' as const;
  readonly description = '逐章内聚：先生成章大纲，然后每章独立并行生成结构+内容';

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

    const workflow = new StateGraph(GraphState)
      .addNode('plan_book', planBookNode)
      .addNode('generate_outline', generateOutlineNode)
      .addNode('per_chapter', perChapterNode)
      .setEntryPoint('plan_book')
      .addEdge('plan_book', 'generate_outline')
      .addEdge('generate_outline', 'per_chapter')
      .addEdge('per_chapter', 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);
  }
}
