import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Open subscription lifetimes do not fill Slowest Spans", WEB, async ({ t3, app, screen, browser }) => {
  // Redact unrelated failure details that expose local paths in recordings.
  await browser.addInitScript(() => {
    const addRedaction = () => {
      const style = document.createElement("style");
      style.textContent = 'td[class*="max-w-[360px]"] { visibility: hidden !important; }';
      document.head.append(style);
    };
    if (document.head) addRedaction();
    else document.addEventListener("DOMContentLoaded", addRedaction, { once: true });
  });
  const project = await t3.project("trace-proof");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some((provider) => provider.instanceId === "devReplay" && provider.models?.some((model) => model.slug === "multi-turn"));
      }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const first = await t3.thread({ project, title: "First replay", messages: ["Start"] });
  const second = await t3.thread({ project, title: "Second replay", messages: ["Start"] });
  await t3.open(first);
  await screen.getByRole("textbox").waitFor({ timeout: 120_000 });
  // These are real subscription lifetimes: keep each thread open past the 1 s threshold.
  await new Promise((resolve) => setTimeout(resolve, 6000));
  await t3.open(second);
  await screen.getByRole("textbox").waitFor({ timeout: 120_000 });
  await new Promise((resolve) => setTimeout(resolve, 6000));
  const environment = await runPromise(environmentId(app.baseUrl ?? ""));
  await t3.open(`/settings/diagnostics?machine=${encodeURIComponent(environment)}`);
  await screen.getByRole("button", "Refresh trace diagnostics", { exact: true }).waitFor({ timeout: 120_000 });
  await new Promise((resolve) => setTimeout(resolve, 3000));
  await screen.getByRole("button", "Refresh trace diagnostics", { exact: true }).tap();
  await new Promise((resolve) => setTimeout(resolve, 2000));
  await browser.evaluate(() => {
    const heading = [...document.querySelectorAll("*")].find((el) => el.children.length === 0 && el.textContent === "Trace Diagnostics");
    heading?.scrollIntoView({ block: "start" });
  });
  await app.screenshot("trace-diagnostics-counts");
  await browser.evaluate(() => {
    const heading = [...document.querySelectorAll("*")].find((el) => el.children.length === 0 && el.textContent === "Slowest Spans");
    heading?.scrollIntoView({ block: "start" });
  });
  await app.screenshot("slowest-spans");
  await expect(screen.getByRole("cell", /^(?:ws\.rpc\.)?(?:EnvironmentRpc\.subscribe|orchestration\.subscribe\w*|subscribe\w*)$/)).toHaveCount(0);
});
