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

test("Generated titles preserve quoted terms and remove a whole-title wrapper", WEB, async ({ t3, app, browser, screen }) => {
  let output = "";
  const requests: string[] = [];
  const stub = NodeHttp.createServer(async (request, response) => {
    let body = "";
    for await (const chunk of request) body += chunk;
    response.setHeader("content-type", "application/json");
    if (request.url?.endsWith("/models")) {
      response.end(JSON.stringify({ object: "list", data: [{ id: "stub-title-model", object: "model", name: "Stub title model" }] }));
      return;
    }
    requests.push(body);
    response.end(JSON.stringify({ id: "stub", object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: output }, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }));
  });
  await new Promise<void>((resolve) => stub.listen(0, "127.0.0.1", resolve));
  const address = stub.address();
  if (!address || typeof address === "string") throw new Error("Stub has no port");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const original = await readFile(settingsPath, "utf8");
  try {
    await writeFile(settingsPath, JSON.stringify({ ...JSON.parse(original), textGenerators: { custom: { kind: "openaiCompatible", baseUrl: `http://127.0.0.1:${address.port}/v1`, label: "Stub titles", apiKey: "", enabled: true } }, textGenerationModelSelection: { instanceId: "custom", model: "stub-title-model" } }));
    await t3.project("demo-project", { "src/foo.ts": "export function foo() { return 1; }\n" });
    await t3.open();
    const cases = [
      { output: JSON.stringify({ title: 'Rename "foo" to "bar"' }), prompt: "Please rename the foo helper to bar everywhere", prefix: "Rename", expected: 'Rename "foo" to "bar"', label: "quoted-terms" },
      { output: JSON.stringify({ title: '"Open in" menu ignores Finder' }), prompt: "Fix the Open in menu ignoring Finder", prefix: "Open in", expected: '"Open in" menu ignores Finder', label: "leading-quoted-term" },
      { output: JSON.stringify({ title: '"Fix login redirect"' }), prompt: "Fix login redirect", prefix: "Fix login redirect", expected: "Fix login redirect", label: "whole-title-wrapper" },
    ];
    const observed = [];
    for (const [index, item] of cases.entries()) {
      if (index > 0) await screen.getByRole("button", "New thread", { exact: true }).tap();
      output = item.output;
      await screen.getByRole("textbox").fill(item.prompt);
      await screen.getByRole("textbox").press("Enter");
      await screen.getByRole("button", index === 1 ? /^Thread actions for "?Open in" menu ignores Finder$/ : new RegExp(`^Thread actions for ${item.prefix}`)).waitFor({ state: "visible", timeout: 60000 });
      await screen.getByText("This turn is a replay.", { exact: false }).waitFor({ state: "visible", timeout: 60000 });
      await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60000 });
      await screen.getByText(/^Working \d/).waitFor({ state: "hidden", timeout: 60000 });
      await app.screenshot(item.label);
      observed.push(await browser.evaluate((prefix) => {
        const action = [...document.querySelectorAll("button[aria-label]")].find((el) => el.getAttribute("aria-label")?.startsWith("Thread actions for ") && el.getAttribute("aria-label")?.includes(prefix));
        return { title: action?.getAttribute("aria-label")?.slice("Thread actions for ".length), documentTitle: document.title };
      }, item.prefix));
    }
    expect(observed.map((item) => item.title)).toEqual(cases.map((item) => item.expected));
    for (const [index, item] of cases.entries()) expect(observed[index]?.documentTitle).toContain(item.expected);
  } finally {
    await writeFile(settingsPath, original);
    await new Promise<void>((resolve) => stub.close(() => resolve()));
  }
});
