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

test("Truncated activity announcements have no space before the ellipsis", WEB, async ({t3, app, browser, screen}) => {
  const readName = "a".repeat(111) + " word";
  const editName = "0123456789".repeat(10) + "01234567 word";
  const project = await t3.project("ws", {[readName]: "old\n", [editName]: "old\n"});
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = {driver: "opencode", enabled: true, config: {binaryPath: "opencode"}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const {cli} = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Reply with just: OK", "--title", "Activity announcement proof", "--provider", "opencode", "--model", "openai/gpt-6-luna", "--wait", "--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open("/settings/chat");
  await screen.getByRole("combobox", "Screen reader announcements").tap();
  await screen.getByRole("option", "Everything", {exact:true}).tap();
  await t3.open({threadId});
  await screen.getByRole("textbox").waitFor();
  await browser.evaluate(() => {
    const records: string[] = [];
    const panel = document.createElement("pre");
    panel.id = "live-region-proof";
    panel.style.cssText = "position:fixed;bottom:12px;left:12px;right:12px;z-index:99999;background:#101827;color:white;padding:16px;border:2px solid #60a5fa;font:16px monospace;white-space:pre-wrap;overflow-wrap:anywhere;pointer-events:none";
    panel.textContent = "Observed screen-reader live-region text (JSON preserves spaces): waiting for activity";
    document.body.append(panel);
    new MutationObserver(() => {
      for (const region of document.querySelectorAll('[aria-live="polite"]')) {
        const text = region.textContent ?? "";
        if (text.endsWith("…") && !records.includes(text)) records.push(text);
      }
      if(records.length && panel.dataset.records !== JSON.stringify(records)) panel.textContent = "Observed screen-reader live-region text (JSON preserves spaces):\n" + records.map(s=>JSON.stringify(s) + "\nSuffix: " + JSON.stringify(s.slice(-8)) + " | space before ellipsis: " + /\s…$/.test(s)).join("\n\n");
      panel.dataset.records = JSON.stringify(records);
    }).observe(document.body, {subtree:true, childList:true, characterData:true});
    return null;
  });
  await screen.getByRole("textbox").fill(`Use the Read tool to read the file named exactly ${readName}. Then use the Write tool to replace the entire file named exactly ${editName} with the exact text "new" followed by a newline. The content is fully specified; perform the write without asking a question. Use these exact names, copying them from this message. After writing, run sleep 20 in a foreground shell tool, then reply DONE. Do not delegate.`);
  await screen.getByRole("textbox").press("Enter");
  await browser.locator('#live-region-proof[data-records*="…"]').waitFor({timeout:180000});
  await screen.getByText("DONE", {exact:true}).waitFor({timeout:180000});
  await app.screenshot("live-region-truncated-activity");
  const records = await browser.evaluate(() => JSON.parse(document.getElementById("live-region-proof")!.dataset.records ?? "[]") as string[]);
  if (!records.length) throw new Error("No truncated activity announcement was observed");
  expect(records.filter(s=> /\s…$/.test(s))).toEqual([]);
});
