// 設定の「字体」が実際に効くか、切り替えて撮って確かめる。
import fs from 'fs';
import { spawn } from 'child_process';

const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const PORT = 9466, profile = 'C:/Users/ADMINI~1/AppData/Local/Temp/lm-ft';
const FACES = ['gothic', 'mincho', 'bizmincho', 'kyokasho', 'zenold', 'klee', 'dot'];

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=1370,820', '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(); const errs = [];
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); return; }
  if (m.method === 'Runtime.exceptionThrown') errs.push(m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text);
});
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;
const shot = async n => fs.writeFileSync(`shots/sw-${n}.png`, Buffer.from((await send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));

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(400); }
await sleep(1500);

// 設定を開いて、選択肢が出ているか
await ev('document.getElementById("m-options").click()');
await sleep(900);
const opts = await ev('(()=>{const s=document.getElementById("opt-jafont"); return s? [...s.options].map(o=>o.value+":"+o.textContent) : null;})()');
console.log('設定の選択肢:', opts ? opts.length + '件' : '無し');
await shot('options');
await ev('[...document.querySelectorAll(".win:not(.hidden) [data-win=close]")].forEach(b=>b.click())');
await sleep(400);

for (const f of FACES) {
  await ev(`(()=>{const s=document.getElementById("opt-jafont"); s.value=${JSON.stringify(f)};
    s.dispatchEvent(new Event("change"));})()`);
  await sleep(1400);
  const applied = await ev(`(()=>{const cs=getComputedStyle(document.body);
    return {face:cs.fontFamily.slice(0,60), size:cs.fontSize,
            saved:localStorage.getItem("lowmoor.jafont.v1")};})()`);
  console.log(f.padEnd(10), applied.size.padEnd(6), applied.saved === f ? '保存OK' : '保存NG', applied.face);
  await shot(f);
}

// 再読み込みしても選択が残るか
await send('Page.reload');
await sleep(4000);
const after = await ev('(()=>{const cs=getComputedStyle(document.body);'
  + 'return {sel:document.getElementById("opt-jafont")?.value, size:cs.fontSize, face:cs.fontFamily.slice(0,40)};})()');
console.log('再読込後:', JSON.stringify(after));
console.log('例外:', errs.length ? errs.slice(0, 3) : 'なし');
ws.close(); chrome.kill();
