/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Terminal excerpt numbers the rows retained after trimming blank lines", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("terminal-demo");
  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 thread = await t3.thread({ project, title: "Terminal excerpts", messages: ["hello"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const readReady = () => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return yield* fs.readFileString(`${project}/ready`);
  }).pipe(Effect.orElseSucceed(() => "")));
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("echo ready > ready\n");
    return readReady();
  }, { timeout: 30000 }).toBe("ready\n");
  await terminal.focus();
  await browser.keyboard.type("printf '\\033[2J\\033[H\\n\\nalpha\\nbravo\\n\\n\\n'; sleep 600\n");
  await expect.poll(() => browser.evaluate(() => {
    const input = document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement;
    return parseFloat(input.style.top) === 4 + 6 * parseFloat(input.style.height);
  })).toBe(true);
  const grid = await browser.evaluate(() => {
    const input = document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement;
    const canvas = input.parentElement!.querySelector("canvas")!;
    const bounds = canvas.getBoundingClientRect();
    const height = parseFloat(input.style.height);
    const context = canvas.getContext("2d")!;
    return { x: bounds.left + 4, y: bounds.top + 4, height, width: context.measureText("M").width };
  });
  const drag = async (first: number, last: number, endCol: number, label: string) => {
    await browser.mouse.move(grid.x + 1, grid.y + (first + .5) * grid.height);
    await browser.mouse.down();
    for (let step = 1; step <= 10; step++) {
      await browser.mouse.move(grid.x + 1 + (endCol * grid.width - 1) * step / 10, grid.y + (first + .5 + (last - first) * step / 10) * grid.height);
    }
    await browser.mouse.up();
    await app.screenshot(`selected-${label}`);
    await browser.locator("canvas.cursor-text").secondaryTap();
    await screen.getByText("Add to chat", { exact: true }).tap();
  };
  const observed: string[] = [];
  const editor = browser.locator('[data-testid="composer-editor"]');
  for (const [first, last, endCol, label] of [
    [0, 3, 5, "leading-blank-rows"],
    [2, 5, 1, "trailing-blank-rows"],
    [2, 3, 5, "text-only-control"],
  ] as const) {
    await drag(first, last, endCol, label);
    await editor.getByText(/lines \d+-\d+/).waitFor();
    await app.screenshot(`excerpt-${label}`);
    observed.push((await editor.textContent())!.match(/lines \d+-\d+/)![0]);
    await editor.tap();
    await browser.keyboard.press("Control+a");
    await browser.keyboard.press("Backspace");
  }
  expect(observed).toEqual([
    "lines 3-4",
    "lines 3-4",
    "lines 3-4",
  ]);
});
