const fs = require('fs');

const curPath = 'c:/Users/Mobin/Desktop/wizwiz/wizwizxui-timebot/bot.php';
const upPath = 'c:/Users/Mobin/Desktop/wizwiz/wizwizxui-timebot/bot.php.upstream';

const curLines = fs.readFileSync(curPath, 'utf8').split(/\r?\n/);
const upLines = fs.readFileSync(upPath, 'utf8').split(/\r?\n/);

function asciiPrefix(line, n = 60) {
  let s = '';
  for (const ch of line) {
    if (ch.charCodeAt(0) < 128 && ch !== '?') s += ch;
    if (s.length >= n) break;
  }
  return s.replace(/\s+/g, ' ').trim();
}

const upMap = new Map();
for (const line of upLines) {
  const p = asciiPrefix(line);
  if (p.length < 12) continue;
  if (!upMap.has(p)) upMap.set(p, []);
  upMap.get(p).push(line);
}

let fixed = 0;
let ambiguous = 0;
let unmatched = 0;

const out = curLines.map((line) => {
  if (!line.includes('\uFFFD')) return line;
  const p = asciiPrefix(line);
  const candidates = upMap.get(p);
  if (candidates && candidates.length === 1) {
    fixed++;
    return candidates[0];
  }
  if (candidates && candidates.length > 1) ambiguous++;
  else unmatched++;
  return line;
});

fs.writeFileSync(curPath, out.join('\n'), 'utf8');
const remaining = (out.join('\n').match(/\uFFFD/g) || []).length;
console.log(JSON.stringify({ fixed, ambiguous, unmatched, remaining }, null, 2));
