import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
import { CommandId, MessageId, ProviderInstanceId, ProviderDriverKind, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

// Keep the replayed parent running until Stop on both commits. The child uses real
// Claude because the generic ACP replay adapter cannot natively resume a turn.
const frame = (text: string, afterMs = 0) => ({ type: "emit_inbound", afterMs, frame: {
  kind: "notification", method: "session/update", params: { sessionId: "recorded", update: {
    sessionUpdate: "agent_message_chunk", content: { type: "text", text },
  } },
} });
const prompt = { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } };
const end = { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } };

test("A delegated child resumed after Stop wakes its parent", WEB, async ({ t3, app, screen, browser }) => {
  const recording = join(APP_DIR, "apps/server/scripts/dev-replay/bench_stream_transcript.ndjson");
  const original = await readFile(recording, "utf8");
  const entries = [prompt, frame("Working on the delegated task.\n\n"),
    ...Array.from({ length: 60 }, () => frame("Still working. ", 2000)), end,
    prompt, frame("CHILD_DONE — resumed work completed.\n"), end];
  await writeFile(recording, entries.map((entry) => JSON.stringify(entry)).join("\n"));
  const origin = app.baseUrl ?? "";
  const read = (threadId: string) => runPromise(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, origin);
    return yield* rpc["orchestration.getThreadProjection"]({ threadId: ThreadId.make(threadId) });
  }).pipe(Effect.scoped));
  const dispatch = (command: import("@t3tools/contracts").OrchestrationV2Command) => runPromise(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, origin);
    yield* rpc["orchestration.dispatchCommand"](command);
  }).pipe(Effect.scoped));
  const waitForChild = (threadId: string, milestone: "command" | "completed") => runPromise(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, origin);
    const isRun = (run: { ordinal: number; status: string }) => run.ordinal > 1 && run.status === "completed";
    const isCommand = (item: { type: string; status: string }) => item.type === "command_execution" && item.status === "running";
    yield* rpc["orchestration.subscribeThread"]({ threadId: ThreadId.make(threadId) }).pipe(
      Stream.filter((item) => item.kind === "snapshot"
        ? milestone === "completed" ? item.projection.runs.some(isRun) : item.projection.turnItems.some(isCommand)
        : item.kind === "event" && (milestone === "completed"
          ? item.event.type === "run.updated" && isRun(item.event.payload)
          : item.event.type === "turn-item.updated" && isCommand(item.event.payload))),
      Stream.runHead,
      Effect.timeout("180 seconds"),
    );
  }).pipe(Effect.scoped));
  try {
    await runPromise(Effect.gen(function* () {
      const rpc = yield* rpcClient(T3_HOME, origin);
      yield* rpc["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
        operation: "upsert", instanceId: ProviderInstanceId.make("claudeAgent"),
        instance: { driver: ProviderDriverKind.make("claudeAgent"), enabled: true },
      } });
    }).pipe(Effect.scoped));
    const project = await t3.project("delegate-resume-proof");
    const parent = await t3.thread({ project, title: "Parent — stop and resume proof", messages: ["Prepare to delegate"] });
    const modelSelection = { instanceId: ProviderInstanceId.make("devReplay"), model: "bench-stream" };
    await dispatch({ type: "message.dispatch", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(parent.threadId), messageId: MessageId.make(randomUUID()), text: "Delegate one child. Stop both, then resume only the child.", attachments: [], modelSelection, dispatchMode: { type: "start_immediately" }, createdBy: "user", creationSource: "web" });
    await t3.open(parent);
    await screen.getByText("Working on the delegated task.", { exact: false }).waitFor();
    const parentProjection = await read(parent.threadId);
    const parentRun = parentProjection.runs.at(-1)!;
    await dispatch({ type: "delegated_task.request", commandId: CommandId.make(randomUUID()), parentThreadId: ThreadId.make(parent.threadId), parentRunId: parentRun.id, parentNodeId: parentRun.rootNodeId, task: 'Run exactly python3 -c "import time; time.sleep(150)" in the foreground with Bash timeout 200000 and run_in_background false. Do not delegate. If this turn is interrupted, when resumed do not rerun the command: reply CHILD_DONE only. Otherwise reply CHILD_DONE after the command finishes.', title: "Resumable child", modelSelection: { instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-haiku-5-5" }, runtimeMode: "full-access", interactionMode: "default", completionWake: "always", createdBy: "agent", creationSource: "mcp" });
    const delegated = (await read(parent.threadId)).subagents.at(-1)!;
    const child = { threadId: delegated.childThreadId! };
    // Wait for the child to actually enter its running provider turn before Stop.
    await t3.open(child);
    await waitForChild(child.threadId, "command");
    await screen.getByRole("button", "Stop generation", { exact: true }).waitFor();
    await t3.open(parent);
    await screen.getByRole("button", "Stop generation", { exact: true }).waitFor();
    await app.screenshot("parent-and-child-running");
    await screen.getByRole("button", "Stop generation", { exact: true }).tap();
    await screen.getByText("Run interrupted", { exact: true }).waitFor();
    await t3.open(child);
    await screen.getByRole("button", "Resume thread", { exact: true }).waitFor();
    await app.screenshot("child-stopped");
    await screen.getByRole("button", "Resume thread", { exact: true }).tap();
    await waitForChild(child.threadId, "completed");
    await screen.getByRole("button", "Stop generation", { exact: true }).waitFor({ state: "hidden" });
    await screen.getByText("Resumed thread", { exact: true }).waitFor();
    await app.screenshot("resumed-child-completed");
    await t3.open(parent);
    await screen.getByRole("heading", "Parent — stop and resume proof", { exact: true }).waitFor();
    try {
      // Only a new assistant turn on the parent can contain the second replayed response.
      await expect.poll(async () => (await read(parent.threadId)).runs.some((run) => run.id !== parentRun.id && run.ordinal > parentRun.ordinal && run.status === "completed"), { timeout: 30000 }).toBe(true);
    } finally {
      await app.screenshot("parent-after-child-completion");
      const output = process.env.T3_PROOF_FACTS_DIR;
      if (output) {
        const finishedParent = await read(parent.threadId);
        const finishedChild = await read(child.threadId);
        await writeFile(join(output, `runtime-${Date.now()}.json`), JSON.stringify({
          parentRuns: finishedParent.runs.map((run) => ({ ordinal: run.ordinal, status: run.status, cohort: run.delegatedCompletion })),
          childRuns: finishedChild.runs.map((run) => ({ ordinal: run.ordinal, status: run.status })),
          tasks: finishedParent.subagents.map((task) => ({ title: task.title, status: task.status, completionDelivery: task.completionDelivery })),
        }, null, 2));
      }
    }
  } finally {
    await writeFile(recording, original);
  }
});
