/**
 * 策略对比测试脚本
 * 直接调用三种策略生成同一本小书，对比结果
 *
 * 用法: npx ts-node test/strategy-compare.ts
 */

const BOOK_SCALE = '1000';  // 下10，约1千字
const BOOK_TITLE = '时间是什么';
const BOOK_DESC = '一本面向小学生的科普书，用简单有趣的语言解释时间的概念、历史和测量方法';

async function main() {
  const { setCurrentStrategy, getCurrentStrategyName } = await import('../strategies/selector');
  const { langGraphGenerator } = await import('../index');
  const { bookStore } = await import('../book-generator.store');
  const { resolveGenLevel } = await import('../index');

  const genLevel = resolveGenLevel(BOOK_SCALE);
  console.log(`\n========== 策略对比测试 ==========`);
  console.log(`书名: ${BOOK_TITLE}`);
  console.log(`规模: ${BOOK_SCALE} (约1千字)`);
  console.log(`大纲层级: ${genLevel}`);
  console.log(`===================================\n`);

  const results: Array<{ name: string; bookId: string; elapsed: number }> = [];
  const strategies = ['sequential', 'one-step-outline', 'per-chapter'];

  for (const strategyName of strategies) {
    console.log(`\n────── 测试策略: ${strategyName} ──────`);

    setCurrentStrategy(strategyName as any);

    // 创建书籍
    const book = await bookStore.create({
      userId: 1,
      title: BOOK_TITLE,
      description: BOOK_DESC,
      bookScale: BOOK_SCALE,
      totalChapters: 1,
      estimatedWords: 1000,
    });

    const bookId = book.id.toString();
    console.log(`创建书籍: id=${bookId}`);

    const startTime = Date.now();

    try {
      await langGraphGenerator.generate(bookId, BOOK_DESC, BOOK_SCALE);
      const elapsed = Date.now() - startTime;
      console.log(`✅ 策略 ${strategyName} 完成，耗时 ${(elapsed / 1000).toFixed(1)}s`);

      // 查看结果
      const result = await bookStore.getById(bookId);
      if (result) {
        const chapterCount = result.chapters?.length || 0;
        const completedChapters = result.chapters?.filter((c: any) => c.genStage === 'content_completed').length || 0;
        const hasContent = result.chapters?.some((c: any) => c.content) || false;
        console.log(`   章节: ${chapterCount}, 已完成: ${completedChapters}, 有内容: ${hasContent}`);
        if (result.bookAnalysis) {
          const plan = JSON.parse(result.bookAnalysis);
          console.log(`   规划: genLevel=${plan.genLevel}, 风格=${plan.writingStyle}, 结构=${plan.structureLogic}`);
        }
      }

      results.push({ name: strategyName, bookId, elapsed });
    } catch (err) {
      console.error(`❌ 策略 ${strategyName} 失败:`, err);
    }

    console.log(`────────────────────────────────\n`);
  }

  // 汇总
  console.log(`\n========== 汇总 ==========`);
  for (const r of results) {
    console.log(`  ${r.name.padEnd(18)} ${(r.elapsed / 1000).toFixed(1)}s  bookId=${r.bookId}`);
  }
  console.log(`=========================\n`);
}

main().catch(console.error);
