import { setTimeout as delay } from "node:timers/promises";
import { readFile, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Imported title preserves Unicode at the length boundary", WEB, async ({ t3, app, screen, browser }) => {
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.codex.enabled = true;
  await writeFile(settingsPath, JSON.stringify(settings));
  await browser.setViewport({ width: 1920, height: 1080 });
  await t3.open("/welcome");
  await screen.getByRole("button", /^Review all/).tap();
  await screen.getByRole("checkbox", /^demo-project/).tap();
  await screen.getByRole("button", "Import 1 project and start").tap();
  await screen.getByRole("button", "Settled", { exact: false }).tap();
  await t3.open({ threadId: "import:codex:93ff74ea-1e71-4e87-b61d-447c51a9d811" });
  await screen.getByRole("combobox", "Branch: master").waitFor({ timeout: 60000 });
  await screen.getByRole("button", "Dismiss Codex provider error").tap();
  await browser.evaluate(() => {
    (document.activeElement as HTMLElement)?.blur();
    const region = document.querySelector('[aria-label="Conversation"]');
    if (region) for (const node of [region, ...region.querySelectorAll("*")]) {
      if (node instanceof HTMLElement && node.scrollHeight > node.clientHeight) node.scrollTop = 0;
    }
  });
  let previous = await app.screenshot("settling");
  let stable = false;
  for (let i = 0; i < 12; i++) {
    await delay(500);
    const current = await app.screenshot("settling");
    if ((await readFile(previous)).equals(await readFile(current))) {
      stable = true;
      break;
    }
    previous = current;
  }
  if (!stable) throw new Error("Capture is not stable");
  await app.screenshot("imported-title");
  const title = await browser.evaluate(() => document.title);
  expect(title.split(" - ")[0].split(" / ").at(-1)).toBe("a".repeat(99));
});
