/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Clicking the short suggestion Tab badge inserts the suggested prompt", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("suggestion-demo");
  const thread = await t3.thread({project, title: "Short prompt suggestion", messages: ["Create add.py with a function add(a, b)."]});
  const shown = JSON.parse((await runPromise(makeState(T3_HOME).cli(["thread", "show", thread.threadId, "--json"]))).stdout);
  const runId = shown.messages.at(-1).runId;
  // Replay ACP has no provider suggestion event. Supply only that ephemeral RPC value;
  // the real completed run, settings, composer, layout and pointer handling stay in the app.
  await browser.addInitScript((runId) => {
    const requests = new WeakMap<WebSocket, Set<string>>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const r of [JSON.parse(data)].flat()) {
        if (r._tag === "Request" && r.tag === "orchestration.subscribePromptSuggestion") {
          const ids = requests.get(this) ?? new Set<string>(); ids.add(String(r.id)); requests.set(this, ids);
        }
      }
      return send.call(this, data);
    };
    const add = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(this: WebSocket, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) {
      if (type !== "message" || typeof listener !== "function") return add.call(this, type, listener, options);
      return add.call(this, type, (event: Event) => {
        const raw = (event as MessageEvent).data;
        if (typeof raw !== "string") return listener.call(this, event);
        const parsed = JSON.parse(raw);
        for (const m of [parsed].flat()) if (m._tag === "Chunk" && requests.get(this)?.has(String(m.requestId))) m.values = m.values.map(() => ({runId, text: "Thanks!"}));
        return listener.call(this, new MessageEvent("message", {data: JSON.stringify(parsed)}));
      }, options);
    } as typeof WebSocket.prototype.addEventListener;
  }, runId);
  await t3.open("/settings/labs");
  await screen.getByLabel("Suggest next prompt", {exact: true}).tap();
  await t3.open(thread);
  await screen.getByRole("button", "Use suggested prompt").waitFor();
  await app.screenshot("before-click");
  const point = await browser.evaluate(() => {
    const box = document.querySelector('[aria-label="Use suggested prompt"]')!.getBoundingClientRect();
    return {x: box.x + box.width / 2, y: box.y + box.height / 2};
  });
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await app.screenshot("after-click");
  await expect(screen.getByRole("textbox")).toHaveText("Thanks!");
});
