import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

const burn = `import { Worker, isMainThread, workerData } from 'node:worker_threads';
import { writeFileSync } from 'node:fs';
const cpu = () => { const u = process.cpuUsage(); return (u.user + u.system) / 1e6; };
if (!isMainThread) {
  const { shared, target } = workerData;
  const a = new Int32Array(shared);
  while (cpu() < target - 0.20) { for(let i=0;i<1000;i++) Math.sqrt(i); }
  Atomics.add(a, 0, 1);
  Atomics.wait(a, 1, 0);
} else {
  const target = Number(process.argv[2]);
  const count = Number(process.argv[3]);
  const label = target < 60 ? 'cpu-minute' : 'cpu-hour';
  process.title = label;
  const shared = new SharedArrayBuffer(8);
  const a = new Int32Array(shared);
  for(let i=0;i<count;i++) new Worker(new URL(import.meta.url), { workerData: { shared, target }});
  const timer = setInterval(() => {
    if(Atomics.load(a,0) !== count) return;
    clearInterval(timer);
    while(cpu() < target) {}
    const measured = cpu();
    console.log(label + ' done: cpu=' + measured.toFixed(3) + 's target=' + target);
    writeFileSync(label + '.json', JSON.stringify({pid:process.pid, cpu:measured}));
    process.stdin.resume();
  }, 25);
}
`;

test("Diagnostics promotes rounded CPU time into minutes and hours", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("CPU diagnostics", {"burn.mjs": burn});
  const thread = await t3.thread({project, title:"CPU rounding reproduction", messages:["first"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer", {exact:true}).tap({timeout:120000});
  await browser.keyboard.type("sleep infinity | node burn.mjs 59.97 1 & sleep infinity | node burn.mjs 3599.7 6 &");
  await browser.keyboard.press("Enter");
  const ready = async (name: string) => {
    const deadline = Date.now()+1500000;
    while(Date.now()<deadline) {
      try { return JSON.parse(await readFile(`${project}/${name}.json`, "utf8")); } catch {}
      await new Promise(resolve=>setTimeout(resolve,1000));
    }
    throw new Error("CPU workload did not finish: " + name);
  };
  const minute = await ready("cpu-minute");
  const hour = await ready("cpu-hour");
  console.log("Measured workloads", JSON.stringify({minute,hour}));
  await t3.open("/settings/diagnostics");
  await screen.getByText("Live process tree", {exact:true}).tap();
  const values = () => browser.evaluate(({minute,hour}) => {
    const table = Array.from(document.querySelectorAll("table")).find(table=>Array.from(table.querySelectorAll("th")).some(cell=>cell.textContent?.trim()==="CPU"));
    return [minute,hour].map(pid=> {
      const row = Array.from(table?.querySelectorAll("tbody tr") ?? []).find(row=>Array.from(row.querySelectorAll("td")).some(cell=>cell.textContent?.trim()===String(pid)));
      return row?.querySelectorAll("td")[3]?.textContent?.trim() ?? "missing";
    });
  }, {minute:minute.pid,hour:hour.pid});
  // Wait for real telemetry to discover both completed, idle processes.
  const deadline = Date.now()+60000;
  while((await values()).includes("missing") && Date.now()<deadline) await new Promise(resolve=>setTimeout(resolve,1000));
  if((await values()).includes("missing")) throw new Error("Real process telemetry did not discover the workload PIDs");
  await browser.evaluate((pid) => {
    const table = Array.from(document.querySelectorAll("table")).find(table=>Array.from(table.querySelectorAll("th")).some(cell=>cell.textContent?.trim()==="CPU"));
    const row = Array.from(table?.querySelectorAll("tbody tr") ?? []).find(row=>Array.from(row.querySelectorAll("td")).some(cell=>cell.textContent?.trim()===String(pid)));
    row?.scrollIntoView({block:"center", behavior:"instant"});
  }, minute.pid);
  console.log("Live CPU TIME", JSON.stringify(await values()));
  await app.screenshot("live-cpu-time");
  await expect.poll(values).toEqual(["1m", "1h"]);
});
