// 直った箇所を確かめるための画面写真。
import fs from 'fs';
import { spawn } from 'child_process';
const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const PORT = 9519, profile = 'C:/Users/ADMINI~1/AppData/Local/Temp/lm-shot';
fs.rmSync(profile, { recursive: true, force: true });
fs.mkdirSync('shots', { recursive: 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 < 8; k++) { await ev('(function(){try{fastForward(7200);}catch(e){}})()'); await sleep(400); }
await sleep(1200);

// 入会の問答が前に出ているので、選べる答えを押して抜ける
for (let i = 0; i < 14; i++) {
  const done = await ev(`(()=>{
    const dlg=[...document.querySelectorAll('.win,.dialog,[role=dialog]')].find(d=>d.offsetParent);
    const scope = dlg || document;
    const bs=[...scope.querySelectorAll('button')].filter(b=>b.offsetParent && !b.disabled);
    const pick = bs.find(b=>/次|始|署名|決定|OK/.test(b.textContent)) || bs[bs.length-1];
    if(!pick) return true;
    pick.click(); return false;
  })()`);
  await sleep(500);
  if (done) break;
}
for (let k = 0; k < 6; k++) { await ev('(function(){try{fastForward(7200);}catch(e){}})()'); await sleep(400); }
await sleep(1500);

// まず素の主画面（呪文表・シート・装備が見える）
{
  const r0 = await send('Page.captureScreenshot', { format: 'png' });
  if (r0 && r0.data) { fs.writeFileSync('shots/after-主画面.png', Buffer.from(r0.data, 'base64')); console.log('shots/after-主画面.png'); }
}
for (const [menu, name] of [['m-honour', '名誉録'], ['m-armoury', '武具庫']]) {
  await ev(`(function(){const b=document.getElementById(${JSON.stringify(menu)}); if(b) b.click();})()`);
  await sleep(1200);
  const r = await send('Page.captureScreenshot', { format: 'png' });
  if (r && r.data) { fs.writeFileSync(`shots/after-${name}.png`, Buffer.from(r.data, 'base64')); console.log('shots/after-' + name + '.png'); }
}
ws.close(); chrome.kill();
