const http = require('http');

const bookId = 1;

console.log(`开始重新生成书籍 #${bookId} 的大纲...`);

const data = JSON.stringify({
  bookScale: '130000'
});

const options = {
  hostname: 'localhost',
  port: 3000,
  path: `/api/book-generator/langgraph/books/${bookId}/generate`,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data)
  }
};

function makeRequest(retryCount = 0) {
  const req = http.request(options, (res) => {
    let body = '';
    
    res.on('data', (chunk) => {
      body += chunk;
    });
    
    res.on('end', () => {
      if (res.statusCode === 429 && retryCount < 3) {
        const retryAfter = res.headers['retry-after'] || 2;
        console.log(`⚠️  请求过于频繁，${retryAfter}秒后重试... (第${retryCount + 1}次)`);
        setTimeout(() => makeRequest(retryCount + 1), retryAfter * 1000);
        return;
      }
      
      console.log('响应状态:', res.statusCode);
      try {
        const responseData = JSON.parse(body);
        console.log('响应数据:', responseData);
        
        if (res.statusCode === 200) {
          console.log('\n✅ 生成任务已启动！');
          console.log('请等待几分钟，生成过程包括：');
          console.log('  1. 生成一级大纲（章）');
          console.log('  2. 生成二级大纲（节）');
          console.log('  3. 生成三级大纲（小节）');
          console.log('  4. 生成章节内容');
          console.log('  5. 生成前言和后记');
          console.log('\n你可以通过以下方式查看进度：');
          console.log(`  - 访问: http://localhost:5173/#/pages/book-generator/index?id=${bookId}`);
          console.log('  - 或查看服务器日志');
        } else {
          console.log('\n❌ 请求失败:', responseData.message);
        }
      } catch (e) {
        console.log('响应体:', body);
      }
    });
  });

  req.on('error', (e) => {
    console.error('请求失败:', e.message);
  });

  req.write(data);
  req.end();
}

makeRequest();
