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

// Check for all missing opening quotes on property names
// Pattern: ,{word": should be ,{"word":
// Common property names that might be affected

const badPatterns = [
  /,\{number":/g,
  /,\{title":/g,
  /,\{summary":/g,
  /,\{opening":/g,
  /,\{structure":/g,
  /,\{mustCover":/g,
  /,\{mustNotRepeat":/g,
  /,\{toneAdjustment":/g,
  /,\{keyTakeaway":/g,
  /,\{keyPoints":/g,
  /,\{estimatedWords":/g,
  /,\{writingInstructions":/g,
];

for (const pattern of badPatterns) {
  const matches = aiResponse.match(pattern);
  if (matches) {
    console.log(pattern.toString(), '-> found', matches.length, 'times');
  }
}

// Can we fix by adding the missing quote?
// The fix would be: ,{word": -> ,{"word":
let fixed = aiResponse;

// Apply fixes for common patterns
fixed = fixed.replace(/,(\{[^"]+":)/g, ',{"'.slice(1) + '$1'.slice(1));
// Wait that's confusing, let me do it simpler
fixed = fixed.replace(/\{number":/g, '{"number":');
fixed = fixed.replace(/\{title":/g, '{"title":');
fixed = fixed.replace(/\{summary":/g, '{"summary":');
fixed = fixed.replace(/\{opening":/g, '{"opening":');
fixed = fixed.replace(/\{structure":/g, '{"structure":');
fixed = fixed.replace(/\{mustCover":/g, '{"mustCover":');
fixed = fixed.replace(/\{mustNotRepeat":/g, '{"mustNotRepeat":');
fixed = fixed.replace(/\{toneAdjustment":/g, '{"toneAdjustment":');
fixed = fixed.replace(/\{keyTakeaway":/g, '{"keyTakeaway":');
fixed = fixed.replace(/\{keyPoints":/g, '{"keyPoints":');
fixed = fixed.replace(/\{estimatedWords":/g, '{"estimatedWords":');
fixed = fixed.replace(/\{writingInstructions":/g, '{"writingInstructions":');

try {
  const data = JSON.parse(fixed);
  console.log('\nAfter fix: Valid JSON! chapters:', data.chapters?.length);
} catch(e) {
  console.log('\nAfter fix: Still invalid:', e.message.substring(0, 100));
  // Check remaining issues
  let inString = false;
  let escapeNext = false;
  let i = 0;
  const str = fixed;
  while (i < str.length) {
    const ch = str[i];
    if (escapeNext) { escapeNext = false; i++; continue; }
    if (ch === '\\') { escapeNext = true; i++; continue; }
    if (ch === '"') { inString = !inString; i++; continue; }
    if (!inString && ch === '{') {
      // Check if next non-space char is a quote
      let j = i + 1;
      while (j < str.length && str[j] === ' ') j++;
      if (str[j] && str[j] !== '"') {
        console.log('Missing quote before property at position', i, '->', JSON.stringify(str.substring(i, i+20)));
        break;
      }
    }
    i++;
  }
}