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

const cases = [
  { label: "input-type-inline", command: `node --input-type module -e "import fs from 'node:fs'; console.log(typeof fs.readFile)"` },
  { label: "env-if-exists-inline", command: `node --env-file-if-exists .env.local -e 'console.log(1)'` },
  { label: "env-file-inline", command: `node --env-file .env.local -e 'console.log(process.env.FOO)'` },
  { label: "conditions-control", command: `node -C development -e 'console.log(1)'` },
  { label: "loader-inline", command: `node --experimental-loader ./loader.mjs -e 'console.log(1)'` },
  ...["--input-type module", "--env-file .env.local", "--env-file-if-exists .env.local", "--experimental-loader ./loader.mjs"].map((option, i) => ({label: `stdin-${i+1}`, command: `node ${option} <<'JS'\nconsole.log(1)\nJS` })),
];

test("Node option values preserve JavaScript highlighting in command previews", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("node-preview", {".env.local": "FOO=bar\n", "loader.mjs": "export {};\n"});
  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: unknown[] = [{type:"transcript_start",provider:"acpRegistry",protocol:"acp.ndjson-jsonrpc",version:"1",scenario:"node-options"}, {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  for (const [i, item] of cases.entries()) {
    const output = execFileSync("bash", ["-c", item.command], {cwd:project, encoding:"utf8"});
    frames.push(update({sessionUpdate:"tool_call",toolCallId:`node-${i}`,kind:"execute",title:item.command,status:"in_progress",rawInput:{command:item.command}}), update({sessionUpdate:"tool_call_update",toolCallId:`node-${i}`,status:"completed",rawOutput:output}));
  }
  frames.push(update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Node command previews ready."}}), {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  try {
    await fs.writeFile(recording, frames.map(frame => JSON.stringify(frame)).join("\n")+"\n");
    const thread = await t3.thread({project,title:"Node script highlighting",messages:["Run Node inline and stdin scripts with separate option values"],model:"command-output"});
    await t3.open(thread);
    await screen.getByText("Node command previews ready.", {exact:true}).waitFor();
    await screen.getByRole("button", "Worked for", {exact:false}).tap();
    await screen.getByRole("button", "Ran 9 commands", {exact:true}).tap();
    const highlighted: boolean[] = [];
    for (const item of cases) {
      const row = screen.getByRole("button", item.command, {exact:false}).first();
      await row.tap();
      await browser.locator('div[class="text-foreground/85"] span[style*="color"]').first().waitFor();
      await app.screenshot(item.label);
      highlighted.push(await browser.evaluate(() => Array.from(document.querySelectorAll('span[style]')).some(span => span.textContent === 'console' && (span as HTMLElement).style.color !== '')));
      await row.tap();
    }
    expect(highlighted, "Every Node script has separate JavaScript console tokens").toEqual(cases.map(() => true));
  } finally {
    await fs.writeFile(recording, original);
  }
});
