const fs = require('fs');
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);

const chaptersArrayStart = aiResponse.indexOf('"chapters":[');
const arrayOpenPos = chaptersArrayStart + 11;

console.log('Starting from arrayOpenPos:', arrayOpenPos);
console.log('First 30 chars from arrayOpenPos:', JSON.stringify(aiResponse.substring(arrayOpenPos, arrayOpenPos + 30)));

let bracketDepth = 0;
let inString = false;
let escapeNext = false;
let arrayEnd = -1;

for (let i = arrayOpenPos; 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 === '[') { bracketDepth++; }
  else if (ch === ']') {
    bracketDepth--;
    if (bracketDepth === 0) { arrayEnd = i; console.log('Array end found at', i); break; }
  }
}

if (arrayEnd === -1) {
  console.log('Array end NOT FOUND');
  console.log('bracketDepth after full scan:', bracketDepth);
  console.log('Last 100 chars:', JSON.stringify(aiResponse.slice(-100)));

  // Scan from arrayOpenPos and find ALL ] positions with depth info
  let depth = 0;
  inString = false;
  escapeNext = false;
  const closeBrackets = [];
  for (let i = arrayOpenPos; 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 === '[') depth++;
    else if (ch === ']') {
      depth--;
      closeBrackets.push({ pos: i, depth });
    }
  }
  console.log('Close brackets found:', closeBrackets.slice(-10));
} else {
  console.log('arrayEnd:', arrayEnd);
  const arrayContent = aiResponse.substring(arrayOpenPos + 1, arrayEnd);
  console.log('arrayContent length:', arrayContent.length);
  console.log('arrayContent end:', JSON.stringify(aiResponse.substring(arrayEnd - 50, arrayEnd + 10)));
}