import { appendFileSync } from "node:fs";
import { CommandId, ThreadId, NodeId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Deleting a parent deletes its subagent thread", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("cascade-demo");
  await t3.thread({ project, title: "Observer", messages: ["first"] });
  const parent = await t3.thread({ project, title: "Parent investigation", messages: ["Wait for approval while a child investigates"], model: "question" });
  const origin = app.baseUrl ?? "";
  const child = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    const projection = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(parent.threadId) });
    const run = projection.runs.at(-1)!;
    yield* client["orchestration.dispatchCommand"]({
      type: "delegated_task.request", commandId: CommandId.make("scenario-child-request"),
      createdBy: "agent", creationSource: "mcp", parentThreadId: ThreadId.make(parent.threadId),
      parentRunId: run.id, parentNodeId: NodeId.make(run.rootNodeId!),
      task: "Investigate the child and wait for approval", title: "Child investigation",
      modelSelection: projection.thread.modelSelection, runtimeMode: "approval-required", interactionMode: "default",
    });
    const updated = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(parent.threadId) });
    return { threadId: updated.subagents[0]!.childThreadId! };
  }).pipe(Effect.scoped));
  await t3.open(parent);
  await screen.getByRole("button", "Open Child investigation").waitFor();
  await app.screenshot("before-parent-delete");
  await screen.getByRole("button", "Thread actions for Parent investigation").tap();
  await screen.getByRole("menuitem", "Delete", { exact: true }).tap();
  await screen.getByRole("button", "Confirm", { exact: true }).tap();
  const deleted = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    const projection = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(child.threadId) });
    const family = yield* client["orchestration.getThreadFamily"]({ threadId: ThreadId.make(parent.threadId) });
    return { ...projection, liveChildPresent: family.threads.some(thread => thread.id === child.threadId) };
  }).pipe(Effect.scoped));
  await t3.open(child);
  if (deleted.thread.deletedAt === null) {
    await screen.getByRole("button", "Thread actions for Child investigation").waitFor();
    await screen.getByRole("button", "Fixture", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  } else {
    await screen.getByRole("heading", "New thread", { exact: true }).waitFor();
  }
  if (process.env.T3_PROOF_DATA) appendFileSync(process.env.T3_PROOF_DATA, JSON.stringify({ deletedAt: deleted.thread.deletedAt, runs: deleted.runs.map(run => ({id: run.id, status: run.status})), liveChildPresent: deleted.liveChildPresent }) + "\n");
  await app.screenshot("child-after-parent-delete");
  expect(deleted.thread.deletedAt).not.toBeNull();
  expect(deleted.liveChildPresent).toBe(false);
  expect(deleted.runs.every(run => run.status === "cancelled")).toBe(true);
});
