import { readFileSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Bundled sudo user options preserve Python and SQL highlighting", WEB, async ({ t3, app, screen, browser }) => {
  const commands = ["sudo -Eu bob python3 -c 'print(1)'", "sudo -nHu postgres psql -c 'select 1'", "sudo -u bob python3 -c 'print(1)'"];
  // Replay supplies the three execute cards; command execution is irrelevant to syntax rendering.
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = readFileSync(fixture, "utf8");
  const frames: unknown[] = [{ type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } }];
  const update = (value: unknown) => frames.push({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
  commands.forEach((command, i) => {
    update({ sessionUpdate: "tool_call", toolCallId: `sudo-${i}`, kind: "execute", title: command, status: "in_progress", rawInput: { command } });
    update({ sessionUpdate: "tool_call_update", toolCallId: `sudo-${i}`, status: "completed", rawOutput: `sudo: unknown user ${i === 1 ? "postgres" : "bob"}\n` });
  });
  update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "All three commands finished with unknown-user errors." } });
  frames.push({ type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } });
  writeFileSync(fixture, frames.map(x => JSON.stringify(x)).join("\n") + "\n");
  try {
    const project = await t3.project("sudo-highlighting");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* client.subscribeServerConfig({}).pipe(
        Stream.filter(event => {
          const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
          return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "command-output"));
        }), Stream.runHead);
    }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
    const thread = await t3.thread({ project, title: "Sudo inline scripts", messages: ["Run these three commands separately:\n" + commands.join("\n")], model: "command-output" });
    await t3.open(thread);
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Ran 3 commands").tap();
    for (const command of commands) await screen.getByRole("button", command, { exact: false }).first().tap();
    await screen.getByText("sudo: unknown user postgres", { exact: false }).waitFor();
    await app.screenshot("sudo-inline-highlighting");
    const highlighted = await browser.evaluate(() => Array.from(document.querySelectorAll("div")).filter(d => d.children.length === 1 && d.firstElementChild?.tagName === "SPAN" && d.textContent?.startsWith("sudo -")).map(pre => ({ text: pre.textContent, tokens: Array.from(pre.querySelectorAll("span")).map(s => ({ text: s.textContent, color: getComputedStyle(s).color })) })));
    const python = highlighted.filter(p => p.text?.includes("sudo -Eu"));
    const sql = highlighted.filter(p => p.text?.includes("sudo -nHu"));
    expect(python.some(p => p.tokens.some(t => t.text === "print"))).toBe(true);
    expect(sql.some(p => p.tokens.some(t => t.text?.toLowerCase() === "select"))).toBe(true);
  } finally { writeFileSync(fixture, original); }
});
