/// <reference lib="dom" />
import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("HTML render issue links open beside the thread", WEB, async ({ t3, app, browser, screen }) => {
  const agentPath = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
  const original = await readFile(agentPath, "utf8");
  const injected = original.replace('const turns = loadTurns(session.model);', `
        const { mcpToolSession } = await import("../src/mcp/AcpMcpStdioBridge.ts");
        const Effect = await import("effect/Effect");
        const result = await Effect.runPromise(mcpToolSession({endpoint: process.env.T3_ACP_MCP_ENDPOINT!, authorization: process.env.T3_ACP_MCP_AUTHORIZATION!, clientName: "html-proof-replay"}).pipe(Effect.flatMap(client => client.call("html_render", { title: "GitHub links", height: 200, html: '<h2>GitHub links</h2><p><a href="https://github.com/pingdotgg/t3code/pull/41809">Pull request 41809</a></p><p><a href="https://github.com/pingdotgg/t3code/issues/41939">Issue 41939</a></p><p><a href="https://example.com">External website</a></p>' })), Effect.scoped));
        send({ method: "session/update", params: { sessionId, update: { sessionUpdate: "tool_call", toolCallId: "html-proof", kind: "other", title: "html_render", status: "completed", rawInput: {}, rawOutput: result, _meta: { mcpToolName: "html_render", mcpServerName: "t3-code" } } } });
        const turns = loadTurns(session.model);`);
  await writeFile(agentPath, injected);
  try {
    const project = await t3.project("t3code");
    execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], {cwd: project});
    const thread = await t3.thread({project, title: "HTML issue link proof", messages: ["Render GitHub issue and pull request links"]});
    await t3.open(thread);
    await browser.evaluate(() => { window.open = ((url: string) => { Object.assign(window, {lastExternalUrl: url}); return null; }) as typeof window.open; });
    const frame = browser.frameLocator('iframe[title="GitHub links"]');
    await frame.getByRole("link", "Issue 41939").tap();
    try {
      await expect(screen.getByRole("button", "Refresh issue")).toBeVisible();
    } finally {
      await app.screenshot("issue-link-clicked");
    }
  } finally { await writeFile(agentPath, original); }
});
