import { bookStore } from './src/modules/book-generator/book-generator.store.js';
import { callLLMWithMessages } from './src/services/llm/index.js';

async function main() {
  const bookId = process.argv[2] || '27';
  const book = await bookStore.getById(bookId);

  if (!book) {
    console.error('Book not found');
    return;
  }

  console.log('Title:', book.title);
  console.log('Description:', book.description);
  console.log('bookAnalysis:', book.bookAnalysis ? JSON.parse(book.bookAnalysis) : null);

  // Build messages as richOutlineNode does
  const bookPlan = book.bookAnalysis ? JSON.parse(book.bookAnalysis) : null;
  const genLevel = bookPlan?.genLevel || 2;

  const config = { chapters: 1, totalWords: 1000 };
  const levelDesc: Record<number, string> = {
    1: '仅章：只生成章节列表，不要节和小节。',
    2: '章→节：每章下生成若干节（2-4节），节下不要拆小节。',
    3: '章→节→小节：每章下生成节（2-4节），每节下生成小节（2-4小节），完整三层结构。',
  };

  let planSection = '';
  if (bookPlan) {
    const parts: string[] = [];
    if (bookPlan.goldenThread) parts.push(`黄金主线：${bookPlan.goldenThread}`);
    if (bookPlan.writingStyle) parts.push(`写作风格：${bookPlan.writingStyle}`);
    if (bookPlan.structureLogic) parts.push(`结构逻辑：${bookPlan.structureLogic}`);
    if (bookPlan.contentDepth) parts.push(`内容深度：${bookPlan.contentDepth}`);
    if (bookPlan.targetAudienceAnalysis) parts.push(`目标读者：${bookPlan.targetAudienceAnalysis}`);
    if (parts.length > 0) planSection = `\n\n## 前序深度规划参考\n${parts.join('\n')}`;
  }

  const systemPrompt = `你是一位专业的图书策划编辑。请为以下书籍生成富信息大纲。

## 本书约束
- 总字数约${config.totalWords}字，目标约${config.chapters}章
- 大纲层级：${levelDesc[genLevel] || levelDesc[2]}
- genLevel 当前值：${genLevel}
${planSection}

## 输出格式
必须返回合法的 JSON，不要包含任何 markdown 代码块标记或其他文字：

{
  "mainTheme": "主题一句话描述",
  "structureLogic": "章节组织逻辑说明",
  "chapters": [
    {
      "number": 1,
      "title": "章标题",
      "summary": "章摘要",
      "keyPoints": ["知识点1"],
      "estimatedWords": 2000,
      "sections": [
        {
          "number": 1,
          "title": "节标题",
          "summary": "节摘要",
          "keyPoints": ["知识点1"],
          "estimatedWords": 1000,
          "subsections": []
        }
      ]
    }
  ]
}

注意：genLevel=1 时每章不要 sections
      genLevel=2 时每章的 sections 下不要 subsections
      genLevel=3 时才需要完整的 sections + subsections`;

  const messages = [
    { role: 'system', content: systemPrompt },
    {
      role: 'user',
      content: `书名：《${book.title}》\n${book.description ? `需求描述：${book.description}\n` : ''}\n请生成完整的富信息大纲。`,
    },
  ];

  console.log('\n=== Calling LLM ===');
  console.log('System prompt length:', systemPrompt.length);
  console.log('User content:', messages[1].content);

  try {
    const response = await callLLMWithMessages(messages);
    console.log('\n=== LLM Response ===');
    console.log('Response length:', response.length);
    console.log('Response preview:', response.substring(0, 300));

    // Try to parse（修复：indexOf('') → indexOf('</think>')）
    const thinkEnd = response.indexOf('</think>');
    console.log('\nthinkEnd index:', thinkEnd);
    if (thinkEnd !== -1) {
      console.log('After think removal:', response.substring(thinkEnd + 8, thinkEnd + 100));
    } else {
      console.log('No </think> tag found');
    }

    // Try regex match
    const match = response.match(/\{[\s\S]*\}/);
    if (match) {
      console.log('Found JSON match, length:', match[0].length);
      try {
        const data = JSON.parse(match[0]);
        console.log('Parse successful, chapters:', data.chapters?.length);
      } catch (e) {
        console.log('Parse failed:', e.message);
      }
    } else {
      console.log('No JSON match found');
    }
  } catch (e) {
    console.error('LLM call failed:', e.message);
  }
}

main();
