/// <reference lib="dom" />
import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import { runPromise, test, WEB } from "./t3.ts";

const PREFIX = "n".repeat(38);
test("Diagnostics keeps the emoji boundary well formed", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("diagnostics-demo");
  const thread = await t3.thread({ project, title: "Process diagnostics", messages: ["hello"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await terminal.waitFor();
  await runPromise(Effect.tryPromise(async () => {
    await terminal.focus();
    await browser.keyboard.type("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    await readFile(`${project}/shell-ready`, "utf8");
  }).pipe(Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 30 })));
  await terminal.focus();
  await browser.keyboard.type(String.raw`name=$(printf 'n%.0s' {1..38})$(printf '\360\237\230\200')-long-process-name; cp /usr/bin/sleep "$name"; "./$name" 600 & echo $! > child-pid`);
  await browser.keyboard.press("Enter");
  await runPromise(Effect.tryPromise(() => readFile(`${project}/child-pid`, "utf8")).pipe(
    Effect.retry({ schedule: Schedule.spaced("100 millis"), times: 100 })
  ));
  await t3.open("/settings/diagnostics");
  const row = browser.locator(`[aria-label^="Child process ${PREFIX}"]`);
  await row.waitFor({ state: "attached", timeout: 60000 });
  await browser.evaluate(() => {
    const el = [...document.querySelectorAll("[aria-label]")].find(e => e.getAttribute("aria-label")?.startsWith("Child process " + "n".repeat(38)))!;
    const section = el.closest("section")!;
    const table = el.closest("table")!;
    (table.querySelector("col") as HTMLElement).style.width = "420px";
    table.style.width = "1250px";
    section.scrollIntoView({ block: "start" });
    const name = el.querySelector(".truncate");
    name?.classList.remove("truncate");
    // Commands contain local checkout paths; the name and its accessibility label stay intact.
    document.querySelectorAll("table td:nth-child(7)").forEach(cell => (cell as HTMLElement).style.visibility = "hidden");
    return null;
  });
  await app.screenshot("diagnostics-process-name");
  const observed = await browser.evaluate(() => {
    const el = [...document.querySelectorAll("[aria-label]")].find(e => e.getAttribute("aria-label")?.startsWith("Child process " + "n".repeat(38)))!;
    return { label: el.getAttribute("aria-label"), name: el.textContent };
  });
  expect(observed).toEqual({ label: `Child process ${PREFIX}...`, name: `${PREFIX}...` });
});
