import { CommandId, MessageId, ThreadId, ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FS from "node:fs";
import * as Path from "node:path";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const withClient = <A>(origin: string, f: (client: any) => Effect.Effect<A, any, any>) =>
  runPromise(Effect.scoped(Effect.gen(function* () { return yield* f(yield* rpcClient(T3_HOME, origin)); })) as any);

test("An auto message from agent C steers past agent A's queued message", WEB, async ({t3, app, screen}) => {
  const wrapper = `import {writeFileSync} from "node:fs";
import {spawn} from "node:child_process";
writeFileSync(".scenario-mcp-" + process.env.T3CODE_THREAD_ID + ".json", JSON.stringify({endpoint:process.env.T3_ACP_MCP_ENDPOINT,authorization:process.env.T3_ACP_MCP_AUTHORIZATION}));
const child=spawn(process.execPath,[process.argv[2]],{stdio:"inherit",env:process.env});
process.on("SIGTERM",()=>child.kill("SIGTERM"));
child.on("exit",code=>process.exit(code??0));`;
  const project = await t3.project("dispatch-demo", {"replay-wrapper.mjs": wrapper});
  const origin = app.baseUrl ?? "";
  await withClient(origin, (client) => client["server.updateSettings"]({patch: {}, providerInstanceMutation: {
    operation:"upsert", instanceId:ProviderInstanceId.make("devReplay"), instance:{driver:ProviderDriverKind.make("acpRegistry"),displayName:"Replay (dev)",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[Path.join(project,"replay-wrapper.mjs"),Path.join(APP_DIR,"apps/server/scripts/dev-replay-agent.ts")]}}
  }}));
  const a = await t3.thread({project, title: "Agent A", messages: ["Ready"], model:"question"});
  const c = await t3.thread({project, title: "Agent C", messages: ["Ready"], model:"question"});
  const b = await t3.thread({project, title: "Busy destination", messages: ["Ready"]});
  await withClient(origin, (client) => client["server.updateSettings"]({patch: {}, providerInstanceMutation: {
    operation: "upsert", instanceId: ProviderInstanceId.make("pi"), instance: {driver: ProviderDriverKind.make("pi"), enabled: true, config: {enabled: true, launchArgs: "--approve"}}
  }}));
  await t3.open(b);
  const dispatch = (text: string, senderThreadId: string | undefined, dispatchMode: unknown, auto = false, start = false) =>
    withClient(origin, (client) => client["orchestration.dispatchCommand"]({
      type: "message.dispatch", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(b.threadId),
      messageId: MessageId.make(crypto.randomUUID()), text, attachments: [],
      createdBy: senderThreadId ? "agent" : "user", creationSource: senderThreadId ? "mcp" : "web",
      ...(senderThreadId ? {senderThreadId: ThreadId.make(senderThreadId)} : {}),
      ...(auto ? {deliveryIntent: "auto"} : {}),
      ...(start ? {modelSelection: {instanceId: ProviderInstanceId.make("pi"), model: "anthropic/claude-haiku-4-5-20251001"}} : {}), dispatchMode
    }));
  await dispatch("Use bash to run exactly: sleep 180. Do not do anything else until it finishes. This deliberately holds the turn open for a message delivery demonstration.", undefined, {type:"start_immediately"}, false, true);
  await screen.getByText("Running sleep", {exact:true}).waitFor({timeout: 60_000});
  await screen.getByRole("button", "Stop generation").waitFor();
  // The running tool keeps the same turn active while both messages arrive.
  const projection: any = await withClient(origin, (client) => client["orchestration.getThreadProjection"]({threadId: ThreadId.make(b.threadId)}));
  const active = projection.runs.find((r: any) => r.status === "running");
  if (!active) throw new Error("No running turn");
  const sendAsAgent = (sender: string, message: string, mode: string) => runPromise(Effect.scoped(Effect.gen(function* () {
    const options = JSON.parse(FS.readFileSync(Path.join(project, ".scenario-mcp-" + sender + ".json"), "utf8"));
    const session = yield* mcpToolSession({...options, clientName:"scenario-replay-agent"});
    yield* session.call("tool_search", {query:"t3_thread_send"});
    const result: any = yield* session.call("t3_thread_send", {threadId:b.threadId, message, mode});
    if (result.isError) throw new Error(JSON.stringify(result));
    return result;
  })));
  await sendAsAgent(a.threadId, "queued first", "queue");
  await screen.getByRole("button", "Edit queued message").waitFor();
  await sendAsAgent(c.threadId, "urgent", "auto");
  await screen.getByText("urgent", {exact:true}).last().waitFor();
  const after: any = await withClient(origin, (client) => client["orchestration.getThreadProjection"]({threadId: ThreadId.make(b.threadId)}));
  const urgent = after.messages.find((m: any) => m.text === "urgent");
  await app.screenshot("cross-sender-auto-delivery");
  expect(urgent.runId).toBe(active.id);
});
