/**
 * 策略1 - Sequential（当前方案）
 *
 * 工作流：
 *   plan_book → generate_outline → generate_sections → generate_subsections → write_chapters
 *
 * 特点：
 *   各环节串行执行，每个环节独立 AI 调用
 *   调用量较大（~457 次 AI 调用/65章3层书）
 */

import { StateGraph, END } from '@langchain/langgraph';
import { GraphState } from '../graph';
import { planBookNode } from '../nodes/plan.node';
import { generateOutlineNode } from '../nodes/outline.node';
import { generateSectionsNode, generateSubsectionsNode } from '../nodes/sections.node';
import { writeChaptersNode } from '../nodes/content.node';
import { runGraphWorkflow } from './base';
import { GenerationStrategy } from './types';

export class SequentialStrategy implements GenerationStrategy {
  readonly name = 'sequential' as const;
  readonly description = '逐环节串行（当前方案）：plan→outline→sections→subsections→content';

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

    const workflow = new StateGraph(GraphState)
      .addNode('plan_book', planBookNode)
      .addNode('generate_outline', generateOutlineNode)
      .addNode('generate_sections', generateSectionsNode)
      .addNode('generate_subsections', generateSubsectionsNode)
      .addNode('write_chapters', writeChaptersNode)
      .setEntryPoint('plan_book')
      .addEdge('plan_book', 'generate_outline')
      .addEdge('generate_outline', 'generate_sections')
      .addEdge('generate_sections', 'generate_subsections')
      .addEdge('generate_subsections', 'write_chapters')
      .addEdge('write_chapters', 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);
  }
}
