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";

test("Node scripts after separate option values have JavaScript tokens", WEB, async ({ t3, app, screen, browser }) => {
  const command = "node --dns-result-order ipv4first -e 'console.log(1)'\nnode --v8-pool-size 2 -p '1+1'\nnode --icu-data-dir /tmp -e 'console.log(1)'\nnode --title job -e 'console.log(1)'";
  const recording = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const entries = (await fs.readFile(recording, "utf8")).trim().split("\n").map(line => JSON.parse(line));
  for (const entry of entries) {
    const update = entry.frame?.params?.update;
    if (update?.sessionUpdate === "tool_call") {
      update.title = command;
      update.rawInput = { command };
    }
  }
  await fs.writeFile(recording, entries.map(entry => JSON.stringify(entry)).join("\n"));
  const project = await t3.project("node-highlighting");
  const thread = await t3.thread({ project, title: "Node inline script highlighting", model: "command-output", messages: ["Show the Node commands."] });
  await t3.open(thread);
  await screen.getByRole("button", /^Worked/).tap();
  await screen.getByRole("button", /node --dns-result-order/).tap();
  const tokens = () => browser.evaluate(() => Array.from(document.querySelectorAll("span[style]"), el => el.textContent));
  await expect.poll(async () => (await tokens()).includes("console"), { timeout: 30000 }).toBe(true);
  await app.screenshot("expanded-node-commands");
  expect((await tokens()).filter(text => text === "console").length).toBe(3);
  expect((await tokens()).includes("+")).toBe(true);
});
