import * as NodeHttp from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Single-slash HTTP preview reaches the intended server", WEB, async ({ t3, app, browser, screen }) => {
  const server = NodeHttp.createServer((request, response) => {
    response.writeHead(200, { "content-type": "text/html" });
    response.end(`<!doctype html><title>PROBE OK</title><body style="background:#dcfce7;color:#14532d;font:24px sans-serif;padding:30px"><h1>PROBE OK</h1><p>path=${request.url}</p></body>`);
  });
  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  try {
    const address = server.address();
    if (!address || typeof address === "string") throw new Error("No probe port");
    const url = `http://127.0.0.1:${address.port}/health?probe=1`;
    const project = await t3.project("preview-probe");
    const input = { project, title: "URL preview probe", messages: ["first"] };
    const thread = await t3.thread({ ...input, model: "multi-turn" }).catch((error) => {
      if (!String(error).includes("Advertised models: default")) throw error;
      return t3.thread({ ...input, model: "default" }).catch((nextError) => {
        if (!String(nextError).includes("Model default is not advertised")) throw nextError;
        return t3.thread({ ...input, model: "multi-turn" });
      });
    });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Browser B").tap();
    const addressBar = screen.getByRole("textbox", "Search or enter URL");
    await addressBar.fill(url);
    await browser.keyboard.press("Enter");
    await screen.getByText("PROBE OK", { exact: true }).waitFor();
    await app.screenshot("double-slash-control");
    await addressBar.fill("https:/example.com/path");
    await browser.keyboard.press("Enter");
    await screen.getByRole("button", "Refresh", { exact: true }).waitFor();
    await app.screenshot("single-slash-https");
    const httpsValue = await browser.evaluate(() => (document.querySelector('input[placeholder="Search or enter URL"]') as HTMLInputElement)?.value);
    await addressBar.fill(url.replace("http://", "http:/"));
    await browser.keyboard.press("Enter");
    await screen.getByRole("button", "Refresh", { exact: true }).waitFor();
    try {
      await expect(addressBar).toHaveValue(url);
      await expect(screen.getByText("PROBE OK", { exact: true })).toBeVisible();
      expect(httpsValue).toBe("https://example.com/path");
    } finally {
      await app.screenshot("single-slash-http");
    }
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
});
