// 画面上の特定の語が、どの要素の中に出ているのかを実際に見る。
import fs from 'fs';
import { spawn } from 'child_process';
const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const PORT = 9517, profile = 'C:/Users/ADMINI~1/AppData/Local/Temp/lm-probe';
const WORD = process.argv[2] || 'none';
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=1500,1000', '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(4500);
for (let k = 0; k < 6; k++) { await ev('(function(){try{fastForward(7200);}catch(e){}})()'); await sleep(400); }

const menus = await ev(`[...document.querySelectorAll('[id^="m-"]')].map(b=>b.id)`);
const found = [];
for (const m of menus) {
  await ev(`(function(){const b=document.getElementById(${JSON.stringify(m)}); if(b) b.click();})()`);
  await sleep(700);
  const r = await ev(`(()=>{
    const out=[]; const W=${JSON.stringify(WORD)};
    const walk=n=>{
      if(n.nodeType===3){ if(n.textContent.trim()===W && n.parentElement){
        const p=n.parentElement;
        out.push({html:(p.parentElement||p).outerHTML.slice(0,240)});
      } 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);
    return out.slice(0,3);
  })()`);
  if (r && r.length) found.push({ menu: m, hits: r });
}
console.log(`「${WORD}」が出ている画面: ${found.length}`);
for (const f of found.slice(0, 6)) {
  console.log('\n## ' + f.menu);
  f.hits.forEach(h => console.log('   ' + h.html.replace(/\s+/g, ' ')));
}
ws.close(); chrome.kill();
