const fs = require('fs');
const { repairJson } = require('jsonrepair');

const content = fs.readFileSync('temp/rich-outline-fail_57_1779023037497.txt', 'utf-8');
const marker = '========== AI 原始响应 ';
const markerIdx = content.indexOf(marker);
const headerEndIdx = content.indexOf(' ==========', markerIdx);
const aiStart = content.indexOf('\n', headerEndIdx) + 1;
const aiEnd = content.indexOf('\n\n', aiStart);
const aiResponse = content.substring(aiStart, aiEnd);

console.log('AI response length:', aiResponse.length);
console.log('Response end:', JSON.stringify(aiResponse.slice(-100)));

// Test strategy 1: jsonrepair directly
try {
  const repaired = repairJson(aiResponse);
  console.log('\nStrategy 1: repairJson length:', repaired.length);
  const data = JSON.parse(repaired);
  if (data.chapters && Array.isArray(data.chapters)) {
    console.log('Strategy 1 SUCCESS: chapters count =', data.chapters.length);
    console.log('First chapter:', JSON.stringify(data.chapters[0]).substring(0, 100));
  } else {
    console.log('Strategy 1: no chapters in parsed data');
  }
} catch(e) {
  console.log('\nStrategy 1 FAILED:', e.message.substring(0, 100));
}

// Check if response ends with complete structure
console.log('\nLast 200 chars:', JSON.stringify(aiResponse.slice(-200)));
console.log('Does it end with ]} ?', aiResponse.endsWith(']}'));
console.log('Does it end with ]}] ?', aiResponse.endsWith(']}]'));
console.log('Does it end with ]})] ?', aiResponse.endsWith(']})]'));