import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { writeFileSync, openSync, writeSync, closeSync } from "node:fs";
import { CommandId, ThreadId, MessageId, type OrchestrationV2Command } from "@t3tools/contracts";
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("Latest stable fork and merge back include turn two after cancelling a queued follow-up", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("checkpoint-demo");
  const parent = await t3.thread({project, title: "Parent", messages: ["Turn one: establish the baseline"]});
  await t3.open(parent);
  await screen.getByRole("textbox").last().waitFor();
  const outcomes = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const projection = (id: string) => client["orchestration.getThreadProjection"]({threadId: ThreadId.make(id)});
    const dispatch = (command: OrchestrationV2Command) => client["orchestration.dispatchCommand"](command);
    const cmd = () => CommandId.make(randomUUID());
    const wait = <A,>(read: () => Effect.Effect<A, unknown>, predicate: (value: A) => boolean) => Effect.gen(function* () {
      for (;;) { const value = yield* read(); if (predicate(value)) return value; yield* Effect.sleep("5 millis"); }
    }).pipe(Effect.timeout("60 seconds"));
    const settled = (id: string) => wait(() => projection(id), p => p.runs.some(r => r.checkpointId !== null));
    yield* settled(parent.threadId);
    const forkId = ThreadId.make(randomUUID());
    const exercise = (source: string, target: string, type: "thread.fork" | "thread.merge_back", title?: string) => Effect.gen(function* () {
      const before = yield* projection(source);
      const ordinal = Math.max(0, ...before.runs.map(r => r.ordinal)) + 1;
      const workspace = before.thread.worktreePath ?? project;
      yield* dispatch({type: "message.dispatch", commandId: cmd(), threadId: ThreadId.make(source), messageId: MessageId.make(randomUUID()), text: "Turn two: include latest-change.txt in the latest stable point", attachments: [], createdBy: "user", creationSource: "web", dispatchMode: {type: "start_immediately"}});
      writeFileSync(`${workspace}/latest-change.txt`, `${type}: latest work\n`);
      const fd = openSync(`${workspace}/capture-load.bin`, "w");
      const chunk = Buffer.alloc(1024 * 1024);
      for (let i = 0; i < 600; i++) writeSync(fd, chunk);
      closeSync(fd);
      const pending = yield* wait(() => projection(source), p => p.runs.some(r => r.ordinal === ordinal && r.status === "completed"));
      const latest = pending.runs.find(r => r.ordinal === ordinal)!;
      if (latest.checkpointId !== null) throw new Error("Missed pending checkpoint window");
      yield* dispatch({type: "message.dispatch", commandId: cmd(), threadId: ThreadId.make(source), messageId: MessageId.make(randomUUID()), text: "Cancel this queued follow-up", attachments: [], createdBy: "user", creationSource: "web", dispatchMode: {type: "queue_after_active"}});
      const queued = (yield* projection(source)).runs.find(r => r.ordinal === ordinal + 1)!;
      if (queued.status !== "queued") throw new Error("Follow-up started before cancellation");
      yield* dispatch({type: "queued-run.cancel", commandId: cmd(), threadId: ThreadId.make(source), runId: queued.id});
      const atRequest = yield* projection(source);
      if (atRequest.runs.find(r => r.id === latest.id)!.checkpointId !== null) throw new Error("Checkpoint finished before the latest stable request");
      const start = performance.now();
      yield* dispatch({type, commandId: cmd(), sourceThreadId: ThreadId.make(source), targetThreadId: ThreadId.make(target), sourcePoint: {type: "latest_stable"}, createdBy: "user", creationSource: "web", ...(title ? {title} : {})});
      const durationMs = Math.round(performance.now() - start);
      const destination = yield* projection(target);
      const transfer = destination.contextTransfers.findLast(t => t.sourceThreadId === source);
      const finished = yield* wait(() => projection(source), p => p.runs.find(r => r.id === latest.id)?.checkpointId !== null);
      return {operation: type, latestCompletedRunOrdinal: ordinal, selectedRunOrdinal: finished.runs.find(r => r.id === transfer?.sourcePoint.runId)?.ordinal, pendingAtRequest: latest.checkpointId === null, cancelledBeforeStart: queued.startedAt === null, durationMs, expectedRun: latest.id, expectedCheckpoint: finished.runs.find(r => r.id === latest.id)!.checkpointId, selected: transfer?.sourcePoint};
    });
    const fork = yield* exercise(parent.threadId, forkId, "thread.fork", "Fork from latest stable");
    yield* Effect.promise(async () => {
      await t3.open({threadId: forkId});
      await screen.getByRole("textbox").last().waitFor();
      await screen.getByText("Forked from conversation", {exact: true}).waitFor();
      await screen.getByText("Syncing messages...", {exact: true}).waitFor({state: "hidden"});
      await app.screenshot("fork-latest-stable-after-cancel");
    });
    yield* dispatch({type: "message.dispatch", commandId: cmd(), threadId: forkId, messageId: MessageId.make(randomUUID()), text: "Fork turn one: establish the merge baseline", attachments: [], createdBy: "user", creationSource: "web", dispatchMode: {type: "start_immediately"}});
    yield* settled(forkId);
    const merge = yield* exercise(forkId, parent.threadId, "thread.merge_back");
    return {fork, merge, forkId};
  }).pipe(Effect.scoped));
  await t3.open(parent);
  await screen.getByRole("textbox").last().waitFor();
  await screen.getByText("Turn two: include latest-change.txt in the latest stable point", {exact: true}).last().waitFor();
  await screen.getByText("Syncing messages...", {exact: true}).waitFor({state: "hidden"});
  await app.screenshot("merge-back-latest-stable-after-cancel");
  const sha = execFileSync("git", ["rev-parse", "HEAD"], {cwd: APP_DIR, encoding: "utf8"}).trim();
  writeFileSync(new URL(`../.e2e/runtime-${sha}.json`, import.meta.url), JSON.stringify({sha, ...outcomes}, null, 2));
  console.log(JSON.stringify(outcomes));
  expect([outcomes.fork, outcomes.merge].map(result => ({run: result.selected?.runId, checkpoint: result.selected?.checkpointId}))).toEqual([outcomes.fork, outcomes.merge].map(result => ({run: result.expectedRun, checkpoint: result.expectedCheckpoint})));
});
