import * as fs from "node:fs/promises";
import * as path from "node:path";
import * as Effect from "effect/Effect";
import { ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("A running ACP session without steering offers Queue", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Queue capability demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  const binary = path.join(T3_HOME, "bin", "copilot");
  await fs.symlink(process.execPath, binary);
  const transcript = path.join(T3_HOME, "running.ndjson");
  const frame = (update: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update } } });
  await fs.writeFile(transcript, [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    frame({ sessionUpdate: "tool_call", toolCallId: "sleep", kind: "execute", title: "sleep 150 && echo done", status: "in_progress", rawInput: { command: "sleep 150 && echo done" } }),
    ...Array.from({ length: 100 }, () => ({ ...frame({ sessionUpdate: "tool_call_update", toolCallId: "sleep", status: "in_progress" }), afterMs: 2000 })),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } }
  ].map(x => JSON.stringify(x)).join("\n"));
  const agent = path.join(T3_HOME, "agent.ts");
  await fs.writeFile(agent, (await fs.readFile(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8")).replace('"./dev-replay/showcase_transcript.ndjson"', JSON.stringify(transcript)));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("devReplay"),
      instance: { driver: ProviderDriverKind.make("acpRegistry"), displayName: "Copilot capability replay",
        config: { source: "local", commandPath: binary, commandArgs: [agent] } }
    } });
  }).pipe(Effect.scoped));
  await t3.open();
  const composer = screen.getByRole("textbox");
  await composer.fill("Run sleep 150 && echo done and wait for it to finish");
  await composer.press("Enter");
  await screen.getByText("Running sleep", { exact: false }).first().waitFor({ state: "visible" });
  await composer.fill("Also print the date");
  const action = screen.getByRole("button", /^(Steer|Queue) message$/);
  await action.hover();
  await screen.getByText(/^(Click to steer,.*|Queue message)$/).waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    const popup = document.querySelector('[data-slot="tooltip-popup"]');
    await Promise.all(popup?.getAnimations({ subtree: true }).map(animation => animation.finished) ?? []);
    return null;
  });
  await app.screenshot("running-follow-up");
  const primaryLabel = await action.getAttribute("aria-label");
  await action.tap();
  await screen.getByText("1 queued", { exact: false }).first().waitFor({ state: "visible" });
  await composer.fill("Then print the time");
  await composer.press("Control+Enter");
  await screen.getByText("2 queued", { exact: false }).first().waitFor({ state: "visible" });
  await composer.fill("Next follow-up");
  await action.hover();
  await screen.getByText(/^(Click to steer,.*|Queue message)$/).waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    const popup = document.querySelector('[data-slot="tooltip-popup"]');
    await Promise.all(popup?.getAnimations({ subtree: true }).map(animation => animation.finished) ?? []);
    return null;
  });
  await app.screenshot("queued-shortcut");
  const threadUrl = await browser.url();
  await app.open("/settings/chat");
  await screen.getByRole("combobox", "Follow-up behavior").tap();
  await screen.getByRole("option", "Queue", { exact: true }).tap();
  await browser.goto(threadUrl);
  await composer.fill("Queue preference keyboard follow-up");
  await composer.press("Control+Enter");
  await screen.getByText("3 queued", { exact: false }).first().waitFor({ state: "visible" });
  await composer.fill("Another follow-up");
  await action.hover();
  await screen.getByText(/^(Click to queue,.*|Queue message)$/).waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    const popup = document.querySelector('[data-slot="tooltip-popup"]');
    await Promise.all(popup?.getAnimations({ subtree: true }).map(animation => animation.finished) ?? []);
    return null;
  });
  await app.screenshot("queue-preference-shortcut");
  await expect(primaryLabel).toBe("Queue message");
  await expect(screen.getByText("Also print the date", { exact: true }).first()).toBeVisible();
});
