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 = [
  ["printf 'foo\\n' | perl -pe 's/foo/bar/'", "bar\n"],
  ["printf 'foo\\n' | perl -nE 'say uc'", "FOO\n"],
  ["printf 'foo\\n' | perl -0777ne 'print length'", "4"],
  ["perl -I lib -M strict -pe 's/foo/bar/' input.txt", "Missing argument to -M.\n"],
  ['perl -e \'print "standalone\\n"\'', "standalone\n"],
  ["perl -I lib -pe 's/foo/bar/' input.txt", "bar\n"],
  ["perl -I lib -Mstrict -nE 'say uc' input.txt", "FOO\n"],
  ["perl -pie 's/foo/bar/' input.txt", ""],
];
function transcript() {
  const rows: unknown[] = [];
  for (const indexes of [[0,1,2,3,4], [5,6,7]]) {
    rows.push({type:"expect_outbound", frame:{kind:"request",method:"session/prompt",params:"<any>"}});
    for (const i of indexes) {
      const [command, output] = commands[i];
      const update = (value: unknown) => rows.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:value}}});
      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:output});
    }
    rows.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Perl command batch complete."}}}}});
    rows.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  }
  return rows.map(row => JSON.stringify(row)).join("\n") + "\n";
}

test("Bundled Perl switches highlight inline scripts and leave value-taking bundles as shell strings", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = path.join(APP_DIR,"apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(fixture,"utf8");
  try {
    await fs.writeFile(fixture,transcript());
    const project = await t3.project("perl-demo", {"input.txt":"foo\n", "lib/.keep":""});
    const thread = await t3.thread({project,title:"Perl inline script highlighting",messages:["Run the first five Perl commands separately.","Run the include-path examples and negative control separately."],model:"command-output"});
    await t3.open(thread);
    await screen.getByRole("button", "Worked for", {exact:false}).first().tap();
    await screen.getByRole("button", "Worked for", {exact:false}).last().tap();
    await screen.getByRole("button", "Ran 5 commands", {exact:false}).tap();
    await screen.getByRole("button", "Ran 3 commands", {exact:false}).tap();
    await app.screenshot("perl-command-rows");
    const highlighted: boolean[] = [];
    for (let i=0;i<commands.length;i++) {
      const row = screen.getByRole("button",commands[i][0],{exact:false}).first();
      await row.tap();
      await browser.locator('[class="text-foreground/85"] span[style]').first().waitFor();
      await app.screenshot(`command-${i+1}`);
      const plainWord = commands[i][0].includes("s/foo/bar/") ? "'s/foo/bar/'" : commands[i][0].includes("say uc") ? "'say" : "'print";
      highlighted.push(await browser.evaluate((word) => !Array.from(document.querySelectorAll("span[style]")).some(span => span.textContent === word), plainWord));
      await row.tap();
    }
    await expect(highlighted).toEqual([true,true,true,false,true,true,true,false]);

  } finally {
    await fs.writeFile(fixture,original);
  }
});
