import { spawn } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { setTimeout as wait } from "node:timers/promises";

const CHROME = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
const PORT = 9333;
const PROFILE = "C:\\Users\\10419\\AppData\\Local\\Temp\\cs-top12-verify";

const proc = spawn(
  CHROME,
  [
    `--headless=new`,
    `--disable-gpu`,
    `--remote-debugging-port=${PORT}`,
    `--user-data-dir=${PROFILE}`,
    `--window-size=1500,900`,
    `--hide-scrollbars`,
    `--no-first-run`,
    `about:blank`,
  ],
  { stdio: "ignore", detached: true },
);
proc.unref();
for (let i = 0; i < 30; i++) {
  try {
    const r = await fetch(`http://127.0.0.1:${PORT}/json/version`);
    if (r.ok) break;
  } catch {}
  await wait(300);
}

const t = await (await fetch(`http://127.0.0.1:${PORT}/json/new?about:blank`, { method: "PUT" })).json();
const ws = new WebSocket(t.webSocketDebuggerUrl);
await new Promise((r) => ws.addEventListener("open", () => r(), { once: true }));
let id = 0;
const pending = new Map();
ws.addEventListener("message", (e) => {
  const m = JSON.parse(e.data);
  if (m.id && pending.has(m.id)) {
    const { resolve, reject } = pending.get(m.id);
    pending.delete(m.id);
    if (m.error) reject(new Error(m.error.message));
    else resolve(m.result);
  }
});
const cmd = (method, params = {}) =>
  new Promise((resolve, reject) => {
    pending.set(++id, { resolve, reject });
    ws.send(JSON.stringify({ id, method, params }));
  });

await cmd("Emulation.setDeviceMetricsOverride", {
  width: 1500, height: 900, deviceScaleFactor: 1, mobile: false,
});
await cmd("Page.navigate", { url: "http://localhost:3000" });
await wait(3000);
await cmd("Runtime.evaluate", {
  expression: `document.querySelectorAll('video').forEach(v => { try { v.pause(); } catch{} });`,
});
// 滚到 Top12 区
await cmd("Runtime.evaluate", {
  expression: `window.scrollTo(0, window.innerHeight);`,
});
await wait(1500);
// 多等一下 useRanking 拉到数据
await wait(2500);

const r = await cmd("Page.captureScreenshot", { format: "png" });
await writeFile(
  "d:/ClaudeProjects/虚拟明星/UI-UX/docs/screenshots/top12-fix-verify.png",
  Buffer.from(r.data, "base64"),
);
console.log("✓ saved");
ws.close();
try { process.kill(proc.pid); } catch {}
spawn("taskkill", ["/F", "/PID", String(proc.pid), "/T"], { stdio: "ignore" });
