import { CommandId, ProjectId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A fork of a moved thread accepts a local message", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("demo");
  const source = await t3.thread({ project, title: "Move me", messages: ["first"] });
  const origin = app.baseUrl ?? "";
  const second = startSecondServer(origin);
  try {
    const { host } = await second.ready;
    const forkId = ThreadId.make("thread:moved-local-fork");
    await runPromise(Effect.gen(function* () {
      const a = yield* rpcClient(T3_HOME, origin);
      const b = yield* rpcClient(SECOND_HOME, host);
      const projectId = ProjectId.make("project:destination");
      yield* b["projects.mutate"]({ type: "project.create", commandId: CommandId.make("create-destination"), projectId, title: "demo", workspaceRoot: project });
      for (const client of [a, b]) yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
      yield* a["peerLinks.link"]({ url: host, pairingCode: JSON.parse(pairing.stdout).credential, access: "full-access" });
      const destination = yield* environmentId(host);
      yield* a["threadHandoff.start"]({ threadId: ThreadId.make(source.threadId), environmentId: destination, projectId });
      yield* a["orchestration.dispatchCommand"]({
        type: "thread.fork", commandId: CommandId.make("fork-moved-source"),
        sourceThreadId: ThreadId.make(source.threadId), targetThreadId: forkId,
        sourcePoint: { type: "latest_stable" }, title: "Fork of moved thread",
        createdBy: "agent", creationSource: "mcp",
      });
    }).pipe(Effect.scoped));
    const sent = await runPromise(makeState(T3_HOME).cli(["thread", "send", forkId, "Hello from the CLI", "--wait", "--json"], [0, 1, 2]));
    console.log("Local fork send:", sent);
    await t3.open({ threadId: forkId });
    await screen.getByText("first fixture turn complete", { exact: false }).first().waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "detached" });
    await app.screenshot("fork-after-local-send");
    expect(sent.exitCode, sent.stderr || sent.stdout).toBe(0);
    await expect(screen.getByText("Hello from the CLI", { exact: true })).toBeVisible();
    await expect(screen.getByRole("button", "Thread actions for Fork of moved thread")).toBeVisible();
  } finally {
    await second.stop();
  }
});
