const fs = require('fs');
const content = fs.readFileSync('temp/rich-outline-fail_57_1779022210168.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);

// Count braces
let openBraces = 0, closeBraces = 0;
let inString = false, escapeNext = false;
for (let i = 0; i < aiResponse.length; i++) {
  const ch = aiResponse[i];
  if (escapeNext) { escapeNext = false; continue; }
  if (ch === '\\') { escapeNext = true; continue; }
  if (ch === '"') { inString = !inString; continue; }
  if (inString) continue;
  if (ch === '{') openBraces++;
  else if (ch === '}') closeBraces++;
}
console.log('Open braces:', openBraces, 'Close:', closeBraces, 'Diff:', openBraces - closeBraces);
console.log('Ends with }:', aiResponse.trim().endsWith('}'));

try {
  JSON.parse(aiResponse);
  console.log('Raw parse: SUCCESS');
} catch(e) {
  console.log('Raw parse FAILED:', e.message.substring(0, 100));
  const pos = parseInt(e.message.match(/position (\d+)/)?.[1] || '0');
  console.log('Error at position:', pos);
  if (pos > 0 && pos < aiResponse.length) {
    console.log('Context:', JSON.stringify(aiResponse.substring(Math.max(0,pos-50), pos+50)));
  }
}