const fs = require('fs');
const content = fs.readFileSync('temp/rich-outline-fail_57_1779014018760.txt', 'utf-8');

// Check the ORIGINAL tail (last 500 chars as stored in file)
const tailMarker = '========== 响应结尾500字符 ';
const tailIdx = content.indexOf(tailMarker);
const tailStart = content.indexOf('\n', tailIdx) + 1;
const tail = content.substring(tailStart).trim();

console.log('=== File tail (last 500 chars of original response) ===');
console.log(JSON.stringify(tail.substring(0, 500)));

// Now let's try to see if we can manually fix the JSON by:
// 1. Finding the incomplete last object and completing it
const aiResponse = content.split('========== AI 原始响应 ')[1].split('==========')[0].trim();

console.log('\n=== Checking if truncation is the issue ===');
console.log('Saved length:', aiResponse.length, 'File says: 9867');

const lastCompleteProp = '"estimatedWords": 800';
const lastCompleteIdx = aiResponse.lastIndexOf(lastCompleteProp);
console.log('Last complete estimatedWords at:', lastCompleteIdx);

// The response seems to be truncated mid-property
// Let's count levels to see where we are
let braceLevel = 0;
let bracketLevel = 0;
let inString = false;
let escapeNext = false;
let lastCompletePos = lastCompleteIdx + lastCompleteProp.length;

for (let i = 0; i < lastCompleteIdx + lastCompleteProp.length; i++) {
  const ch = aiResponse[i];
  if (escapeNext) { escapeNext = false; continue; }
  if (ch === '\\') { escapeNext = true; continue; }
  if (ch === '"') { inString = !inString; continue; }
  if (!inString) {
    if (ch === '{') braceLevel++;
    else if (ch === '}') braceLevel--;
    else if (ch === '[') bracketLevel++;
    else if (ch === ']') bracketLevel--;
  }
}
console.log('At end of last complete prop - Brace level:', braceLevel, 'Bracket level:', bracketLevel);

// Now check what the full structure looks like
// If braceLevel = 0, we need to close several }
console.log('\n=== Simulating truncated JSON completion ===');

// The incomplete part ends with:
// "estimated" (incomplete "estimatedWords": <number>)
const incomplete = ', "estimated"; // truncated here'

// Try to count what we'd need to close
console.log('Missing closing brackets/braces to make valid JSON:');

// Count open structures at truncation point
inString = false;
escapeNext = false;
braceLevel = 0;
bracketLevel = 0;
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) {
    if (ch === '{') braceLevel++;
    else if (ch === '}') braceLevel--;
    else if (ch === '[') bracketLevel++;
    else if (ch === ']') bracketLevel--;
  }
}
console.log('At truncation - Open braces:', braceLevel, 'Open brackets:', bracketLevel);