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

const SOURCE = String.raw`Literal \<em>not emphasized\</em> here

Keep \<!-- note -->, \<br/> and \<?pi?> visible

<details><summary>Literal &lt;em&gt;example&lt;/em&gt; &amp; more</summary>

Body
</details>

After the details.

Comparison: b\<c.`;

test("Copied literal HTML survives the pull request editor Preview", WEB, async ({ t3, app, browser, screen }) => {
  // The free replay model supplies synthetic chat text; GitHub and the PR editor are real.
  const fixture = join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const project = await t3.project("Literal HTML");
  execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project });
  const transcript = join(T3_HOME, "literal-transcript.ndjson");
  const agent = join(T3_HOME, "literal-replay.ts");
  const entries = original.trim().split("\n").map(line => JSON.parse(line));
  for (const entry of entries) {
    if (entry.label === "first.assistant") entry.frame.params.update.content.text = SOURCE;
  }
  await writeFile(transcript, entries.map(entry => JSON.stringify(entry)).join("\n") + "\n");
  const replaySource = await readFile(join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  await writeFile(agent, replaySource.replace('NodeFS.readFileSync(new URL(scenario.file, import.meta.url), "utf8")', `NodeFS.readFileSync(${JSON.stringify(transcript)}, "utf8")`));
  const settingsPath = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.devReplay.config.commandArgs = [agent];
  await writeFile(settingsPath, JSON.stringify(settings));
  // Give the settings watcher time to reload the replay executable before starting the turn.
  await new Promise(resolve => setTimeout(resolve, 1500));
  const thread = await t3.thread({ project, title: "Copy literal HTML", model: "default", messages: ["Show literal HTML for a copy and paste check."] });
  const dwell = async () => {
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.playState === "running" && a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
      await new Promise(resolve => setTimeout(resolve, 1500));
      return null;
    });
  };
  const capture = async (label: string) => {
    await dwell();
    let first = await app.screenshot(label + "-stability");
    for (let attempt = 0; attempt < 24; attempt++) {
      await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 500)); return null; });
      const second = await app.screenshot(label);
      if ((await readFile(first)).equals(await readFile(second))) return;
      first = second;
    }
    throw new Error("Unsettled screenshot: " + label);
  };
  await t3.open(thread!);
  await screen.getByText("After the details.", { exact: true }).waitFor();
  await browser.locator(".chat-markdown [data-markdown-details-summary]").tap();
  await capture("01-rendered-chat");
  await browser.evaluate(() => {
    const root = [...document.querySelectorAll(".chat-markdown")].find(e => e.textContent?.includes("After the details."));
    if (!root) throw new Error("Assistant Markdown missing");
    const range = document.createRange(); range.selectNodeContents(root);
    const selection = window.getSelection()!; selection.removeAllRanges(); selection.addRange(range);
    return null;
  });
  await capture("02-selected-chat");
  await browser.keyboard.press("ControlOrMeta+C");
  await dwell();
  const env = await runPromise(environmentId(app.baseUrl!));
  const { makeState } = await import("./t3.ts");
  const token = (await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
  const projects = await fetch(`${app.baseUrl}/api/projects`, { headers: { authorization: `Bearer ${token}` } }).then(r => r.json()) as { projects: {id:string; workspaceRoot:string}[] };
  const id = projects.projects.find(p => p.workspaceRoot === project)!.id;
  const query = new URLSearchParams({ repository: "pingdotgg/t3code", number: "46169", selectedProjectId: id, selectedEnvironmentId: env, selectedHost: "github.com" });
  await t3.open(`/pull-requests?${query}`);
  await screen.getByRole("button", "Edit description", {exact:true}).waitFor({timeout:120000});
  await screen.getByRole("button", "Maximize panel", {exact:true}).tap();
  await screen.getByRole("button", "Edit description", {exact:true}).tap();
  const textarea = screen.getByRole("combobox", "Pull request description", {exact:true});
  await textarea.tap();
  await browser.keyboard.press("ControlOrMeta+A");
  await browser.keyboard.press("ControlOrMeta+V");
  // Blur the textarea so the caret does not invalidate the stability pair.
  await screen.getByRole("button", "Write", {exact:true}).tap();
  await capture("03-pasted-markdown-source");
  await screen.getByRole("button", "Preview", {exact:true}).tap();
  await browser.locator('[aria-label="Markdown editor mode"] [data-pressed]').filter({hasText:"Preview"}).waitFor();
  await browser.locator('[aria-label="Markdown editor mode"]').scrollIntoView();
  await browser.locator('[data-markdown-details-summary]').filter({hasText:"Literal"}).tap();
  await capture("04-pasted-pull-request-preview");
  const visible = await browser.evaluate(() => {
    const modes = document.querySelector('[aria-label="Markdown editor mode"]');
    const editor = modes?.parentElement;
    return { text: editor?.textContent ?? "", emphasis: editor?.querySelectorAll("em").length ?? -1, summary: editor?.querySelector("[data-markdown-details-summary]")?.textContent ?? "" };
  });
  // Cancel before asserting, so the proof never saves or posts to GitHub.
  await screen.getByRole("button", "Cancel", {exact:true}).tap();
  expect(visible.text).toContain("Literal <em>not emphasized</em> here");
  expect(visible.text).toContain("Keep <!-- note -->, <br/> and <?pi?> visible");
  expect(visible.summary).toBe("Literal <em>example</em> & more");
  expect(visible.emphasis).toBe(0);
});
