import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test(
  "Browser preview connects to a host without media ticket routes",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const hostHome = process.env.PROOF_HOST_HOME!;
    const hostCli = process.env.PROOF_HOST_CLI!;
    const pairing = JSON.parse(
      execFileSync(
        hostCli,
        [
          "auth",
          "pairing",
          "create",
          "--base-dir",
          hostHome,
          "--base-url",
          "http://127.0.0.1:3774",
          "--json",
        ],
        { encoding: "utf8" },
      ),
    );
    await browser.addInitScript(() => {
      const originalFetch = window.fetch.bind(window);
      (window as any).__ticketTrace = [];
      window.fetch = async (...args) => {
        const response = await originalFetch(...args);
        const path = new URL(response.url).pathname;
        if (path.startsWith("/api/auth/websocket-ticket")) {
          (window as any).__ticketTrace.push({ path, status: response.status });
        }
        return response;
      };
      const observer = new MutationObserver(() => {
        if (document.getElementById("evidence-privacy")) return;
        const style = document.createElement("style");
        style.id = "evidence-privacy";
        style.textContent =
          "[data-chat-composer-overlay], [data-chat-composer-stack] { visibility: hidden !important; }";
        document.documentElement.append(style);
      });
      observer.observe(document, { childList: true, subtree: true });
    });
    await t3.project("Local fixture");
    await t3.open();
    await screen.getByRole("button", "Settings", { exact: true }).tap();
    await screen.getByRole("treeitem", "Environments", { exact: true }).tap();
    await screen.getByRole("button", "Add environment").tap();
    await screen.getByText("Remote link", { exact: true }).tap();
    await screen.getByRole("textbox", "Host").fill(pairing.pairUrl);
    await screen.getByRole("button", "Add environment").last().tap();
    await screen.getByRole("textbox", "Host").waitFor({ state: "hidden" });
    await screen.getByRole("button", "Close", { exact: true }).tap();
    await screen
      .getByTestId("sidebar-row-card")
      .filter({ hasText: "Preview ticket compatibility" })
      .tap();
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    try {
      await expect(screen.getByRole("button", "Release control", { exact: true })).toBeVisible({
        timeout: 20000,
      });
    } finally {
      await app.screenshot("older-host-preview");
      console.log(
        "TICKET_TRACE",
        JSON.stringify(await browser.evaluate(() => (window as any).__ticketTrace)),
      );
    }
  },
);
