/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const warning = "Build workstation for the integration and release engineering team is almost out of disk space";

test("A truncated machine pressure warning reveals its full text on hover and keeps details and dismissal", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("release-check");
  const thread = await t3.thread({ project, title: "Check machine health", messages: ["Hello"] });
  const volume = `${T3_HOME}/worktrees`;
  mkdirSync(volume, { recursive: true });
  // A real nearly-full filesystem: the server samples statfs, with no mocked telemetry.
  execFileSync("sudo", ["-n", "mount", "-t", "tmpfs", "-o", "size=16m,mode=777", "tmpfs", volume]);
  try {
    writeFileSync(`${volume}/pressure.bin`, Buffer.alloc(16 * 1024 * 1024 - 256 * 1024));
    await browser.emulateMedia({ colorScheme: "dark" });
    await t3.open(thread);
    await browser.evaluate(() => localStorage.setItem("chat_thread_sidebar_width", "208"));
    await t3.open(thread);
    const button = screen.getByRole("button", warning, { exact: true });
    await button.waitFor();
    const clipped = await browser.evaluate(() => {
      const label = document.querySelector("[data-host-pressure] span");
      return !!label && label.scrollWidth > label.clientWidth;
    });
    if (!clipped) throw new Error("Setup failed: warning label is not truncated");
    await button.hover();
    let hoverFailure: unknown;
    try {
      await expect(browser.locator('[data-slot="tooltip-popup"][data-open]')).toHaveText(warning);
    } catch (error) { hoverFailure = error; }
    await browser.evaluate(async () => { await Promise.allSettled(document.getAnimations().filter((a) => a.effect?.getTiming().iterations !== Infinity).map((a) => a.finished)); });
    await app.screenshot("warning-hover");
    await button.tap();
    await screen.getByRole("dialog").waitFor();
    await browser.evaluate(async () => { await Promise.allSettled(document.getAnimations().filter((a) => a.effect?.getTiming().iterations !== Infinity).map((a) => a.finished)); });
    await app.screenshot("warning-details");
    await browser.keyboard.press("Escape");
    await button.hover();
    await screen.getByRole("button", "Dismiss notice", { exact: true }).tap();
    await button.waitFor({ state: "hidden" });
    await browser.evaluate(async () => { await Promise.allSettled(document.getAnimations().filter((a) => a.effect?.getTiming().iterations !== Infinity).map((a) => a.finished)); });
    await app.screenshot("warning-dismissed");
    if (hoverFailure) throw hoverFailure;
  } finally {
    execFileSync("sudo", ["-n", "umount", volume]);
  }
});
