/**
 * 新策略 deep-plan-parallel 端到端验证
 *
 * 用法: cd server && npx tsx src/modules/book-generator/test/e2e-deep-plan.ts
 */
async function main() {
  const { getCurrentStrategyName } = await import('../strategies/selector.js');
  const { langGraphGenerator } = await import('../index.js');
  const { bookStore } = await import('../book-generator.store.js');

  const BOOK_TITLE = '端到端测试书';
  const BOOK_DESC = '一本测试用的小书，验证 DeepPlan+RichOutline+ParallelContent+ContinuityEdit';
  const BOOK_SCALE = '1000';

  console.log('═══════════════════════════════════════');
  console.log('  deep-plan-parallel 端到端测试');
  console.log('═══════════════════════════════════════');
  console.log(`  书名: ${BOOK_TITLE}`);
  console.log(`  规模: ${BOOK_SCALE} (~1千字)`);
  console.log(`  策略: ${getCurrentStrategyName()}`);
  console.log('═══════════════════════════════════════\n');

  // Step 1: 创建书籍
  console.log('[1/4] 创建书籍...');
  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}\n`);

  // Step 2: 运行生成
  const t0 = Date.now();
  console.log('[2/4] 运行 4 阶段生成...');
  console.log('  deep_plan → rich_outline → parallel_content → continuity_edit\n');

  await langGraphGenerator.generate(bookId, BOOK_DESC, BOOK_SCALE);
  const elapsed = ((Date.now() - t0) / 1000).toFixed(1);

  // Step 3: 检查结果
  console.log(`\n[3/4] 生成完成，${elapsed}s\n`);
  const result: any = await bookStore.getById(bookId);
  if (!result) { console.error('❌ 结果为空'); process.exit(1); }

  console.log('── 阶段产物检查 ──');

  // DeepPlan
  const hasPlan = !!result.bookAnalysis;
  let goldenThread = '';
  if (hasPlan) {
    try { goldenThread = JSON.parse(result.bookAnalysis).goldenThread?.substring(0, 50) || ''; } catch {}
  }
  console.log(`  DeepPlan(bookAnalysis): ${hasPlan ? '✅' : '❌'} ${goldenThread}`);

  // RichOutline
  const hasOutline = !!(result.outline);
  const chCount = result.outline?.chapters?.length || 0;
  console.log(`  RichOutline(outline):   ${hasOutline ? '✅' : '❌'} ${chCount}章`);

  // Content
  const chapters = result.chapters || [];
  let contentOk = 0;
  let words = 0;
  for (const ch of chapters) {
    if (ch.content) { contentOk++; words += ch.wordCount || 0; }
  }
  console.log(`  ParallelContent:        ${contentOk > 0 ? '✅' : '❌'} ${contentOk}/${chapters.length}有内容, ${words}字`);

  // ContinuityEdit (检查是否所有 content_completed)
  const allDone = chapters.every((c: any) => c.genStage === 'content_completed');
  console.log(`  ContinuityEdit(signal):  ${allDone ? '✅' : '⚠️'} allDone=${allDone}`);

  // 详情
  console.log('\n  章节详情:');
  for (const ch of chapters) {
    const contentPreview = ch.content ? `"${ch.content.substring(0, 40)}..."` : '(空)';
    console.log(`    L${ch.level || '?'} #${ch.number} "${ch.title?.substring(0, 25)}" ${ch.genStage} ${ch.wordCount || 0}字 ${contentPreview}`);
  }

  // Step 4: 汇总
  console.log('\n[4/4] ═══════════════════════════════');
  const pass = hasPlan && hasOutline && contentOk > 0;
  console.log(`  结果: ${pass ? '✅ 端到端验证通过' : '⚠️ 部分未完成'}`);
  console.log(`  耗时: ${elapsed}s | 阶段: 4/4 | 字数: ${words}`);
  console.log('═══════════════════════════════════════');
}

main().catch(err => { console.error('FATAL:', err); process.exit(1); });
