/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Every osascript -e script has embedded language colors", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const commands = ["osascript -e 'set x to 1' -e 'return x + 1'", "osascript -l JavaScript -e 'const x = 1' -e 'x + 1'"];
  const frames: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  commands.forEach((command, i) => {
    frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"tool_call",toolCallId:`osascript-${i}`,kind:"execute",title:command,status:"in_progress",rawInput:{command}}}}});
    frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"tool_call_update",toolCallId:`osascript-${i}`,status:"completed",rawOutput:"2\n"}}}});
  });
  frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Both osascript commands finished."}}}}});
  frames.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  const project = await t3.project("demo");
  const settings = JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8"));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{}, providerInstanceMutation:{operation:"upsert",instanceId:"devReplay",instance:{...settings.providerInstances.devReplay,config:{...settings.providerInstances.devReplay.config,customModels:["command-output"]}}}});
    yield* client["server.refreshProviders"]({instanceId: "devReplay", cwd: project, fresh: true, refreshModels: true});
  }).pipe(Effect.scoped));
  let thread;
  try {
    await writeFile(fixture, frames.map(frame => JSON.stringify(frame)).join("\n"));
    thread = await t3.thread({project,title:"AppleScript and JavaScript",messages:["Run the two osascript commands."],model:"command-output"});
  } finally { await writeFile(fixture, original); }
  await t3.open(thread);
  await screen.getByText("Both osascript commands finished.").waitFor();
  await screen.getByRole("button", "Worked for", {exact:false}).tap();
  const group = screen.getByRole("button", "Ran 2 commands", {exact:false});
  await group.tap();
  await screen.getByRole("button", "osascript -e", {exact:false}).first().tap();
  await screen.getByRole("button", "osascript -l JavaScript", {exact:false}).first().tap();
  await browser.evaluate(async () => {
    document.body.dispatchEvent(new MouseEvent("mousemove", {clientX: 1100, clientY: 700, bubbles: true}));
    await Promise.all(document.getAnimations().filter(a => a.playState !== "finished" && a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
    await new Promise(resolve => setTimeout(resolve, 1000));
    return null;
  });
  await app.screenshot("osascript-embedded-scripts");
  const colors = await browser.evaluate(() => Array.from(document.querySelectorAll("div")).filter(pre => pre.textContent?.startsWith("osascript") && !pre.querySelector("div") && pre.querySelector("span[style]")).map(pre => Array.from(pre.querySelectorAll("span")).filter(span => span.children.length === 0).map(span => ({text:span.textContent,color:getComputedStyle(span).color}))));
  console.log(JSON.stringify(colors));
  expect(colors[0]?.some(token => token.text?.includes("return") && token.color !== "rgb(16, 106, 43)")).toBe(true);
  expect(colors[1]?.filter(token => token.text?.includes("1") && token.color !== "rgb(16, 106, 43)").length).toBe(2);
});
