// 画面に出ている英語を、長い順に拾う。抽出器が取りこぼした形を見つけるため。
import fs from 'fs';
import { spawn } from 'child_process';
const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const PORT = 9500, profile = 'C:/Users/ADMINI~1/AppData/Local/Temp/lm-en';
fs.rmSync(profile, { recursive: true, force: true });
const chrome = spawn(CHROME, ['--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run',
  '--remote-debugging-port=' + PORT, '--user-data-dir=' + profile, '--window-size=1400,900', 'about:blank'], { stdio: 'ignore' });
const sleep = ms => new Promise(r => setTimeout(r, ms));
let list = null;
for (let i = 0; i < 40; i++) { try { list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json(); if (list.length) break; } catch { } await sleep(300); }
const ws = new WebSocket(list.find(t => t.type === 'page').webSocketDebuggerUrl);
await new Promise(r => ws.addEventListener('open', r));
let id = 0; const pend = new Map();
ws.addEventListener('message', e => { const m = JSON.parse(e.data); if (m.id && pend.has(m.id)) { pend.get(m.id)(m.result); pend.delete(m.id); } });
const send = (m, p = {}) => new Promise(res => { const i = ++id; pend.set(i, res); ws.send(JSON.stringify({ id: i, method: m, params: p })); });
const ev = async x => (await send('Runtime.evaluate', { expression: x, returnByValue: true, awaitPromise: true })).result?.value;

await send('Page.enable'); await send('Runtime.enable');
await send('Page.navigate', { url: 'file:///' + process.cwd().replace(/\\/g, '/') + '/build/index-app.html' });
await sleep(4000);
for (let k = 0; k < 3; k++) { await ev('(function(){try{fastForward(3600);}catch(e){}})()'); await sleep(500); }
await sleep(2000);

const r = await ev(`(()=>{
  const runs = [];
  const walk = n => {
    if (n.nodeType === 3) {
      const t = n.textContent.trim();
      // 3語以上つながった英語だけを拾う（固有名は2語で終わることが多い）
      const m = t.match(/[A-Za-z][A-Za-z'’,.\\-]*(?:\\s+[A-Za-z][A-Za-z'’,.\\-]*){2,}/g);
      if (m) for (const x of m) if (x.length > 12) runs.push({ t: x, where: (n.parentElement && (n.parentElement.id || n.parentElement.className)) || '' });
      return;
    }
    if (n.nodeType !== 1) return;
    const cs = getComputedStyle(n);
    if (cs.display === 'none' || cs.visibility === 'hidden') return;
    for (const c of n.childNodes) walk(c);
  };
  walk(document.body);
  // 属性（ツールチップ）も見る
  for (const el of document.querySelectorAll('[data-help],[title],[aria-label]')) {
    for (const a of ['data-help','title','aria-label']) {
      const v = el.getAttribute(a); if (!v) continue;
      const m = v.match(/[A-Za-z][A-Za-z'’,.\\-]*(?:\\s+[A-Za-z][A-Za-z'’,.\\-]*){3,}/g);
      if (m) for (const x of m) if (x.length > 20) runs.push({ t: x, where: a + ':' + (el.id || el.className) });
    }
  }
  const seen = new Set(), out = [];
  for (const x of runs) { const k = x.t.slice(0, 60); if (seen.has(k)) continue; seen.add(k); out.push(x); }
  return out.sort((a, b) => b.t.length - a.t.length).slice(0, 40);
})()`);
console.log('画面に出ている英語（長い順）:', r.length, '件');
r.forEach(x => console.log('  [' + String(x.where).slice(0, 24).padEnd(24) + '] ' + x.t.slice(0, 100)));
fs.writeFileSync('screen-english.json', JSON.stringify(r, null, 1));
ws.close(); chrome.kill();
