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

test("Late workspace skill descriptions stay dismissed outside the composer", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("demo", {
    ".claude/skills/deploy-preview/SKILL.md": "---\nname: deploy-preview\ndescription: Builds the current branch, uploads it to a disposable preview environment, waits for the deployment to become healthy, and returns a shareable preview URL for review. Use when a preview deployment is requested.\n---\nBuild a preview.\n",
  });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.refreshProviders"]({instanceId: "devReplay" as any, cwd: project, fresh: true});
  }).pipe(Effect.scoped));
  let thread;
  try {
    thread = await t3.thread({project, title: "Late skill results", messages: ["Hello"], model: "multi-turn"});
  } catch (error) {
    if (!String(error).includes("Advertised models: default")) throw error;
    try {
      thread = await t3.thread({project, title: "Late skill results", messages: ["Hello"], model: "default"});
    } catch (error) {
      if (!String(error).includes("Model default is not advertised")) throw error;
      thread = await t3.thread({project, title: "Late skill results", messages: ["Hello"], model: "multi-turn"});
    }
  }
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent = {driver: "claudeAgent", enabled: true};
  await writeFile(settingsPath, JSON.stringify(settings));
  await browser.addInitScript(() => {
    const held: Array<() => void> = [];
    let holding = true;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (holding && typeof data === "string") {
        const parsed = JSON.parse(data);
        if ([parsed].flat().some(m => m?._tag === "Request" && m.tag === "server.refreshProviders" && m.payload?.cwd)) {
          held.push(() => send.call(this, data)); return;
        }
      }
      return send.call(this, data);
    };
    (window as any).releaseScan = () => { holding = false; held.splice(0).forEach(release => release()); };
  });
  await t3.open(thread);
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await browser.keyboard.type("Haiku");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  const composer = screen.getByRole("textbox");
  await composer.pressSequentially("/deploy");
  await screen.getByText("Searching workspace skills...", {exact: true}).first().waitFor();
  await composer.press("Tab");
  await app.screenshot("searching-after-tab");
  await browser.evaluate(() => { (window as any).releaseScan(); });
  await screen.getByRole("option").first().waitFor();
  // Allow the real tooltip's opening delay to elapse before sampling its state.
  await new Promise(resolve => setTimeout(resolve, 2000));
  await app.screenshot("late-result-outside-focus");
  expect(await browser.evaluate(() => [...document.querySelectorAll('[data-slot="tooltip-popup"]')].some(el => el.textContent?.includes("Builds the current branch")))).toBe(false);
  await composer.tap();
  await browser.locator('[data-slot="tooltip-popup"]').filter({hasText: "Builds the current branch"}).waitFor();
  await app.screenshot("description-after-refocus");
});
