import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const commands = [
  "node --title 'build job' -e 'console.log(42)'",
  "node --inspect-port 9234 -e 'console.log(42)'",
  "node --title='build job' -e 'console.log(42)'",
  "node --inspect-port=9234 -e 'console.log(42)'",
];
test("Node eval is JavaScript after separate title and inspector port values", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await fs.readFile(fixture, "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: `node-${i}`, kind: "execute", title: command, status: "in_progress", rawInput: { command } }),
      update({ sessionUpdate: "tool_call_update", toolCallId: `node-${i}`, status: "completed", rawOutput: "42\n" }),
    ]),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "All four commands printed 42." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  await fs.writeFile(fixture, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
  const project = await t3.project("node-options");
  let thread;
  try {
    thread = await t3.thread({ project, title: "Node eval highlighting", messages: ["Run the four Node eval commands"], model: "default" });
  } finally {
    await fs.writeFile(fixture, original);
  }
  await t3.open(thread);
  await screen.getByText("All four commands printed 42.").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 }).tap();
  await browser.locator('span[style]:text-is("log")').first().waitFor();
  await app.screenshot("node-eval-options");
  const tokens = await browser.evaluate(() => Array.from(document.querySelectorAll('span[style]')).filter(el => el.textContent === "log").map(el => ({text: el.textContent, color: getComputedStyle(el).color})));
  expect(tokens.length).toBe(4);
});
