import { randomUUID } from "node:crypto";
import { existsSync, writeFileSync } from "node:fs";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as DateTime from "effect/DateTime";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

// Uses real delegation, projections, Git, cleanup and Maintenance UI. No database edits.
test(
  "Delete merged worktrees removes a finished isolated subagent without its own PR",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("merged-subagent", { "tracked.txt": "initial\n" });
    const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
    const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
    const remote = `${T3_HOME}/origin.git`;
    await git(project, "init", "--bare", "--initial-branch=main", remote);
    await git(project, "remote", "add", "origin", remote);
    await git(project, "push", "origin", "main");
    await git(project, "remote", "set-head", "origin", "main");
    await git(project, "checkout", "-b", "parent-branch");
    const parent = await t3.thread({
      project,
      title: "Parent work",
      messages: ["Plan the work"],
      model: "question",
    });
    const parentId = ThreadId.make(parent.threadId);
    const rpc = <A>(
      f: (client: Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A, unknown, never>,
    ) =>
      runPromise(
        Effect.gen(function* () {
          return yield* f(yield* rpcClient(T3_HOME, app.baseUrl ?? ""));
        }).pipe(Effect.scoped),
      );
    const commandId = () => CommandId.make(randomUUID());
    await rpc((client) =>
      client["server.updateSettings"]({
        patch: {
          storageCleanup: {
            worktreeOnMerge: true,
            worktreeOnDelete: true,
            worktreeAfterDays: 30,
            worktreeSettledAfterDays: null,
            worktreeUnchanged: false,
          },
        },
      }),
    );
    const parentProjection = await rpc((client) =>
      client["orchestration.getThreadProjection"]({ threadId: parentId }),
    );
    const parentRun = parentProjection.runs.at(-1)!;
    await rpc((client) =>
      client["orchestration.dispatchCommand"]({
        type: "delegated_task.request",
        commandId: commandId(),
        createdBy: "user",
        creationSource: "web",
        parentThreadId: parentId,
        parentRunId: parentRun.id,
        parentNodeId: parentRun.rootNodeId!,
        title: "Isolated subagent work",
        task: "Complete the isolated work",
        modelSelection: {
          instanceId: parentProjection.thread.modelSelection.instanceId,
          model: "multi-turn",
        },
        runtimeMode: "full-access",
        interactionMode: "default",
        workspaceStrategy: {
          type: "worktree",
          baseRef: "main",
          branch: "feature",
          startFromOrigin: false,
        },
      }),
    );
    const family = await rpc((client) =>
      client["orchestration.getThreadFamily"]({ threadId: parentId }),
    );
    const childId = family.threads.find(
      (thread) => thread.lineage.relationshipToParent === "subagent",
    )!.id;
    // Public dispatch creates a preparing child; provision its Git workspace and release it
    // through the same commands used by launch preparation.
    const isolatedPath = `${T3_HOME}/worktrees/feature`;
    await git(project, "worktree", "add", "-b", "feature", isolatedPath, "main");
    await rpc((client) =>
      client["orchestration.dispatchCommand"]({
        type: "thread.metadata.update",
        commandId: commandId(),
        threadId: childId,
        branch: "feature",
        worktreePath: isolatedPath,
      }),
    );
    const preparing = await rpc((client) =>
      client["orchestration.getThreadProjection"]({ threadId: childId }),
    );
    await rpc((client) =>
      client["orchestration.dispatchCommand"]({
        type: "prepared-run.release",
        commandId: commandId(),
        threadId: childId,
        runId: preparing.runs.at(-1)!.id,
      }),
    );
    await t3.open({ threadId: childId });
    await screen
      .getByText("first fixture turn complete", { exact: false })
      .waitFor({ timeout: 120_000 });
    const child = await rpc((client) =>
      client["orchestration.getThreadProjection"]({ threadId: childId! }),
    );
    const worktree = child.thread.worktreePath!;
    writeFileSync(`${worktree}/tracked.txt`, "subagent work\n");
    await git(worktree, ...author, "commit", "-am", "subagent work");
    await git(project, ...author, "merge", "--no-ff", "-m", "merge subagent", "feature");
    await git(project, "checkout", "main");
    await git(project, ...author, "merge", "--no-ff", "-m", "merge parent work", "parent-branch");
    await git(project, "push", "origin", "main");
    await git(worktree, "merge-base", "--is-ancestor", "HEAD", "origin/main");
    for (const session of child.providerSessions.filter(
      (session) => session.status !== "stopped",
    )) {
      await rpc((client) =>
        client["orchestration.dispatchCommand"]({
          type: "provider-session.detach",
          commandId: commandId(),
          threadId: childId!,
          providerSessionId: session.id,
          reason: "Finished isolated work",
        }),
      );
    }
    const question = parentProjection.runtimeRequests.find(
      (request) => request.status === "pending",
    )!;
    await rpc((client) =>
      client["orchestration.dispatchCommand"]({
        type: "runtime-request.respond",
        commandId: commandId(),
        threadId: parentId,
        requestId: question.id,
        answers: { schema_vs_ui_flexibility: "Strict schemas (Recommended)" },
      }),
    );
    await t3.open(parent);
    await screen
      .getByText("plan questions fixture complete", { exact: false })
      .waitFor({ timeout: 60_000 });
    await rpc((client) =>
      client["orchestration.dispatchCommand"]({
        type: "thread.settle",
        commandId: commandId(),
        threadId: parentId,
        settledAt: DateTime.makeUnsafe(Date.now() - 86_400_000),
      }),
    );
    // The real service protects settle scripts for 60 seconds after any thread activity.
    await new Promise((resolve) => setTimeout(resolve, 61_000));
    await t3.open("/settings/maintenance");
    await browser.evaluate(
      `(() => { const style = document.createElement('style'); style.textContent = '#storage-cleanup-last-run code {font-size:0} #storage-cleanup-last-run code::after {content:"[synthetic workspace]";font-size:12px}'; document.head.append(style); return true; })()`,
    );
    await screen.getByRole("button", "Delete now", { exact: true }).tap();
    await screen.getByRole("button", /^Last run/).tap();
    const row = browser
      .locator('#storage-cleanup-last-run [data-slot="settings-row"]')
      .filter({ has: screen.getByText("Isolated subagent work", { exact: true }) });
    await row.scrollIntoView();
    await row.getByText(/Inactive for|Work is on the default branch/).waitFor();
    // Hide synthetic absolute paths in public evidence; all app state and result text stay intact.
    await browser.evaluate(
      `(() => { const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); const nodes = []; while(walk.nextNode()) nodes.push(walk.currentNode); for(const node of nodes) if(node.textContent.includes(${JSON.stringify(T3_HOME)})) node.textContent = node.textContent.replaceAll(${JSON.stringify(T3_HOME)}, '[scenario workspace]'); return true; })()`,
    );
    await browser.evaluate(
      `(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); document.querySelector('#storage-cleanup-last-run [data-slot="settings-row"]')?.scrollIntoView({block:'center',behavior:'instant'}); return true; })()`,
    );
    await app.screenshot("merged-isolated-subagent-cleanup");
    await expect(row).toContainText("Work is on the default branch");
    expect(existsSync(worktree)).toBe(false);
  },
);
