import * as fs from "node:fs/promises";
import * as path from "node:path";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const commands = ["env -a custom python3 -c 'print(42)'", "env --argv0 custom node -e 'console.log(42)'", "env -ia custom python3 -c 'print(42)'", "python3 -c 'print(42)'", "node -e 'console.log(42)'"];
const update = (value: object) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
test("env argv0 options preserve inline script highlighting", WEB, async ({ t3, app, screen, browser }) => {
  const transcript = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    ...commands.flatMap((command, i) => [update({ sessionUpdate: "tool_call", toolCallId: `cmd-${i}`, kind: "execute", title: command, status: "in_progress", rawInput: { command } }), update({ sessionUpdate: "tool_call_update", toolCallId: `cmd-${i}`, status: "completed" })]),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Five command strings ready for highlighting inspection." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(x => JSON.stringify(x)).join("\n");
  const agent = await fs.readFile(new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url), "utf8");
  const project = await t3.project("inline-scripts", { "replay/dev-replay-agent.ts": agent, "replay/dev-replay/showcase_transcript.ndjson": transcript });
  const instanceId = ProviderInstanceId.make("scenario-script-replay");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: { operation: "upsert", instanceId, instance: { driver: ProviderDriverKind.make("acpRegistry"), displayName: "Script replay", enabled: true, config: { source: "local", commandPath: process.execPath, commandArgs: [path.join(project, "replay/dev-replay-agent.ts")] } } } });
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Show the five inline script commands", "--title", "Inline script highlighting", "--provider", instanceId, "--model", "default", "--wait", "--json"]));
  await t3.open(JSON.parse(started.stdout));
  await screen.getByText("Five command strings ready for highlighting inspection.", { exact: true }).waitFor();
  await screen.getByRole("button", /^Worked/).tap();
  const group = screen.getByRole("button", /Ran 5 commands/);
  await group.tap();
  for (const command of commands) await screen.getByRole("button", command, { exact: true }).first().tap();
  await app.screenshot("expanded-inline-scripts");
  const tokens = await browser.evaluate(() => [...document.querySelectorAll('div[class="text-foreground/85"]')].map(pre => ({ text: pre.textContent, tokens: [...pre.querySelectorAll("span")].map(span => ({ text: span.textContent, color: getComputedStyle(span).color })) })));
  console.log(JSON.stringify(tokens));
  for (const command of commands.slice(0, 3)) {
    const rendered = tokens.find(row => row.text?.includes(command));
    expect(rendered?.tokens.some(token => (token.text === "print" || token.text === "log") && token.color !== "rgb(16, 106, 43)")).toBe(true);
  }
});
