/// <reference lib="dom" />
import { readFileSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const decodePairing = Schema.decodeEffect(Schema.fromJsonString(Schema.Struct({ credential: Schema.String })));

test("Copied tables keep linked thread names and Markdown links", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("primary");
  const local = await t3.thread({ project, title: "Status table", messages: ["first"] });
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = readFileSync(fixture, "utf8");
  try {
    const { host } = await server.ready;
    await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, origin);
      const remote = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, remote]) yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      const paired = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
      const { credential } = yield* decodePairing(paired.stdout);
      yield* primary["peerLinks.link"]({ url: host, pairingCode: credential, access: "approval-required" });
    }).pipe(Effect.scoped));
    const remote = makeState(SECOND_HOME).state;
    const remoteProject = await remote.project("linked");
    const remoteThread = await remote.thread({ project: remoteProject, title: "Remote build fix", messages: ["first"] });
    const remoteEnv = await runPromise(environmentId(host));
    const localEnv = await runPromise(environmentId(origin));
    const markdown = `| Thread | Status |\n| --- | --- |\n| [Remote build fix](t3-thread://v2/${remoteEnv}/${remoteThread.threadId}) | ready |\n| [Status table](t3-thread://v2/${localEnv}/${local.threadId}) | done |`;
    // Supply deterministic assistant text through the real replay agent and ACP adapter.
    writeFileSync(fixture, [
      { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
      { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: markdown } } } } },
      { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
    ].map(row => JSON.stringify(row)).join("\n"));
    const table = await t3.thread({ project, title: "Table copy proof", messages: ["Show the thread status table"], model: "command-output" });
    await t3.open(table);
    await screen.getByRole("button", "Thread, Remote build fix", { exact: true }).waitFor();
    const results: Record<string, string> = {};
    // Capture the browser's real clipboard-write payload, while still performing the write.
    await browser.evaluate(() => {
      const originalRichWrite = navigator.clipboard.write.bind(navigator.clipboard);
      navigator.clipboard.write = async (items) => {
        document.body.dataset.copiedTable = await (await items[0].getType("text/plain")).text();
        return originalRichWrite(items);
      };
      const originalWrite = navigator.clipboard.writeText.bind(navigator.clipboard);
      navigator.clipboard.writeText = async (text) => {
        document.body.dataset.copiedTable = text;
        return originalWrite(text);
      };
    });
    for (const format of ["CSV", "Markdown", "HTML"]) {
      await browser.evaluate(() => { delete document.body.dataset.copiedTable; });
      await screen.getByRole("button", /^(Copy table|Copied)$/).tap();
      await screen.getByRole("menuitem", `Copy as ${format}`, { exact: true }).tap();
      await browser.locator("body[data-copied-table]").waitFor();
      results[format] = await browser.evaluate(() => document.body.dataset.copiedTable ?? "");
    }
    // Display the captured clipboard payloads beside the original table for human inspection.
    await browser.evaluate((values) => {
      const panel = document.createElement("section");
      panel.style.cssText = "position:fixed;right:20px;bottom:70px;left:300px;max-height:46vh;overflow:auto;z-index:100;background:#18181b;color:#fafafa;border:1px solid #71717a;padding:16px;font:12px monospace;white-space:pre-wrap";
      panel.textContent = Object.entries(values).map(([format, value]) => `Copied ${format}${format === "HTML" ? " (styles omitted for display)" : ""}:\n${format === "HTML" ? value.replace(/ style="[^"]*"/g, "") : value}`).join("\n\n");
      document.body.append(panel);
    }, results);
    await app.screenshot("table-and-clipboard-results");
    expect(results.CSV).toContain("Remote build fix,ready");
    expect(results.Markdown).toContain(`[Remote build fix](https://app.t3.codes/threads/${encodeURIComponent(remoteEnv)}/${encodeURIComponent(remoteThread.threadId)})`);
    expect(results.HTML).toMatch(/<td[^>]*>Remote build fix<\/td>/);
  } finally {
    writeFileSync(fixture, original);
    await server.stop();
  }
});
