/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const commands = [
  "sudo -S python3 -c 'print(1)'",
  "sudo -S -p '' python3 -c 'print(1)'",
  "sudo -Sp '' python3 -c 'print(1)'",
  "sudo -h localhost python3 -c 'print(1)'",
];
test("Sudo prompt and host values preserve embedded Python highlighting", WEB, async ({ t3, app, screen, browser }) => {
  const recording = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(recording, "utf8");
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    ...commands.flatMap((command, i) => [
      update({ sessionUpdate: "tool_call", toolCallId: `command-${i}`, kind: "execute", title: command, status: "in_progress", rawInput: { command } }),
      update({ sessionUpdate: "tool_call_update", toolCallId: `command-${i}`, status: "completed", rawOutput: "1\n" }),
    ]),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Four sudo command forms completed." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  const project = await t3.project("sudo-highlighting");
  let thread;
  try {
    await fs.writeFile(recording, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
    for (let attempt = 0; attempt < 8; attempt++) {
      try {
        thread = await t3.thread({ project, title: "Sudo inline Python", messages: ["Show the four sudo command forms"], model: "command-output" });
        break;
      } catch (error) {
        if (!String(error).includes("not advertised") || attempt === 7) throw error;
      }
    }
    if (!thread) throw new Error("Replay model never became available");
  } finally { await fs.writeFile(recording, original); }
  await browser.emulateMedia({ colorScheme: "light" });
  await t3.open(thread);
  await screen.getByText("Four sudo command forms completed.", { exact: true }).waitFor();
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  await screen.getByRole("button", "Ran 4 commands", { exact: false }).tap();
  for (const command of commands) await screen.getByRole("button", command, { exact: false }).first().tap();
  await app.screenshot("four-sudo-python-commands");
  await expect.poll(() => browser.evaluate(() => {
    return Array.from(document.querySelectorAll("div.text-foreground\\/85")).filter(code => code.textContent?.includes("sudo ")).map(code => ({
      command: code.textContent,
      python: Array.from(code.querySelectorAll("span")).some(span => span.textContent === "print" && getComputedStyle(span).color !== "rgb(16, 106, 43)"),
    }));
  })).toEqual(commands.map(command => ({ command, python: true })));
});
