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 cases = [
  ["area", "The area is 3 * 4 * 5 cubic units.", "The area is 3 * 4 * 5 cubic units."],
  ["glob", "Matching glob * and the * literal.", "Matching glob * and the * literal."],
  ["under", "*em* and _a b_ leave _ these _ alone.", "em and a b leave _ these _ alone."],
];
const thought = (text: string, afterMs = 0) => ({type: "emit_inbound", afterMs, frame: {kind: "notification", method: "session/update", params: {sessionId: "<session-id>", update: {sessionUpdate: "agent_thought_chunk", content: {type: "text", text}}}}});

test("Collapsed live thoughts keep spaced literal markers and strip real emphasis", WEB, async ({t3, app, screen, browser}) => {
  const replay = await fs.readFile(new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url), "utf8");
  const files: Record<string,string> = {};
  for (const [name, input] of cases) {
    files[`${name}/dev-replay-agent.ts`] = replay;
    files[`${name}/dev-replay/showcase_transcript.ndjson`] = [
      {type: "expect_outbound", frame: {kind: "request", method: "session/prompt"}},
      thought(input),
      ...Array.from({length: 120}, () => thought("", 2000)),
      {type: "emit_inbound", frame: {kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}},
    ].map(x => JSON.stringify(x)).join("\n");
  }
  const project = await t3.project("Literal markers", files);
  const observed: string[] = [];
  for (const [name, , expected] of cases) {
    const instanceId = ProviderInstanceId.make(`literal-${name}`);
    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: "Replay literal markers", enabled: true, config: {source: "local", commandPath: process.execPath, commandArgs: [path.join(project, name, "dev-replay-agent.ts")]}}}});
    }).pipe(Effect.scoped));
    const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Check literal markers", "--title", `Live ${name}`, "--provider", instanceId, "--model", "default", "--json"]));
    const {threadId} = JSON.parse(started.stdout);
    await t3.open({threadId});
    await screen.getByRole("button", "Stop generation").waitFor();
    const row = browser.locator('[data-testid="work-group-toggle"]');
    const live = screen.getByText(name === "area" ? /^The area is/ : name === "glob" ? /^Matching glob/ : /^em and a b leave/);
    await live.waitFor();
    await app.screenshot(`live-${name}`);
    observed.push(await live.textContent() ?? "");
  }
  expect(observed).toEqual(cases.map(x => x[2]));
});
