const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'enhancedAIAssistant.js');
console.log('Reading file from:', filePath);

let content = fs.readFileSync(filePath, 'utf8');

// Find and fix all unescaped double quotes inside double-quoted strings
// We'll use a regex that looks for patterns like: "some text "word" more text"
const quotePattern = /"([^"\\]*(\\.[^"\\]*)*)"(?![^"]*"(?:\w+=|[:,]))/g;

let fixedCount = 0;
let lastIndex = 0;
let result = '';

// More targeted approach - find specific problematic lines
const lines = content.split('\n');
const fixedLines = lines.map(line => {
  // Check if line has reply: "..." with unescaped quotes
  if (line.includes('reply: "') && line.match(/"[^"]*"[^"]*"/)) {
    // Replace inner unescaped quotes with escaped ones
    const fixed = line.replace(/"([^"]*)"([^"]*)"/g, (match, p1, p2) => {
      // Escape quotes in p1
      const escaped = p1.replace(/"/g, '\\"');
      return `"${escaped}"${p2}"`;
    });
    fixedCount++;
    console.log(`Fixed line: ${line.substring(0, 60)}...`);
    return fixed;
  }
  return line;
});

content = fixedLines.join('\n');

// Also fix specific known patterns
const replacements = [
  // Pattern: "text "word" more text"
  { pattern: /"(I couldn't pull products right now\. Try a keyword like )"([^"]+)"( or a SKU\.)"/g, replacement: '"$1\\"$2\\"$3"' },
  { pattern: /"(I don't have a previous list to add\. Search first \(e\.g\. )"([^"]+)"(, then say )"([^"]+)"(\.)"/g, replacement: '"$1\\"$2\\"$3\\"$4\\"$5"' },
  { pattern: /"(Tell me the SKU or say )"([^"]+)"(\.)"/g, replacement: '"$1\\"$2\\"$3"' },
  { pattern: /"(Tell me the SKU \(or say )"([^"]+)"(\)\.)"/g, replacement: '"$1\\"$2\\"$3"' },
];

for (const {pattern, replacement} of replacements) {
  const matches = content.match(pattern);
  if (matches) {
    console.log(`Found pattern: ${pattern}`);
    content = content.replace(pattern, replacement);
    fixedCount += matches.length;
  }
}

// Write the fixed content back
fs.writeFileSync(filePath, content);
console.log(`Fixed ${fixedCount} lines with quote issues`);
