// 指定した原文について「訳はあるか」「あるなら patch のどの門で止まるか」を答える。
import fs from 'fs';
const src = fs.readFileSync('app/game/index.html', 'utf8');
const tm = JSON.parse(fs.readFileSync('tm.json', 'utf8'));
const ov = JSON.parse(fs.readFileSync('overrides.json', 'utf8'));
for (const k in ov) if (!k.startsWith('_')) tm[k] = ov[k];

const dotProps = new Set([...src.matchAll(/\.([A-Za-z_$][\w$]*)/g)].map(m => m[1]));
const unquotedKeys = new Set([...src.matchAll(/[{,][ \t\r\n]*([A-Za-z_$][\w$]*)[ \t]*:/g)].map(m => m[1]));
const runtimeCmp = new Set([
  ...[...src.matchAll(/[=!]==?\s*["']([^"']{1,40})["']/g)].map(m => m[1]),
  ...[...src.matchAll(/["']([^"']{1,40})["']\s*[=!]==?/g)].map(m => m[1]),
]);
const apiWords = new Set([
  ...[...src.matchAll(/(?:querySelector|querySelectorAll|classList\.\w+|setAttribute|getAttribute|addEventListener|createElement|getElementById|closest|matches)\(\s*["']([^"']+)["']/g)].map(m => m[1]),
  ...[...src.matchAll(/\.className\s*=\s*["']([^"']+)["']/g)].map(m => m[1]),
  ...[...src.matchAll(/\.dataset\.\w+\s*=\s*["']([^"']+)["']/g)].map(m => m[1]),
]);

for (const en of process.argv.slice(2)) {
  const ja = tm[en];
  const r = [];
  if (/^[A-Za-z_$][\w$]*$/.test(en) && dotProps.has(en)) r.push('identifier-property');
  if (apiWords.has(en)) r.push('browser-api-value');
  if (runtimeCmp.has(en)) r.push('runtime-compared');
  if (/^[A-Za-z_$][\w$]*$/.test(en) && unquotedKeys.has(en)) r.push('structural-key');
  const q = en.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const dq = (src.match(new RegExp('"' + q + '"', 'g')) || []).length;
  const sq = (src.match(new RegExp("'" + q + "'", 'g')) || []).length;
  const gt = (src.match(new RegExp('>' + q + '<', 'g')) || []).length;
  console.log(`${JSON.stringify(en)}`);
  console.log(`   訳: ${ja === undefined ? '（無し）' : JSON.stringify(ja)}`);
  console.log(`   リテラル "..":${dq} '..':${sq}  HTML >..<:${gt}   門: ${r.join(', ') || '通る'}`);
}
