import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Ten successful zsh worktree setups leave no idle setup terminals", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("setup-demo");
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const config = yield* client["server.getConfig"]({});
    const replay = config.settings.providerInstances.devReplay!;
    yield* client["server.updateSettings"]({ patch: { providerInstances: { devReplay: { ...replay, enabled: true, config: { ...(replay.config as Record<string, unknown>), customModels: ["multi-turn"] } } } } });
    yield* client["server.refreshProviders"]({ instanceId: "devReplay", cwd: project, fresh: true, refreshModels: true });
    yield* client["server.updateSettings"]({ patch: { defaultProjectScripts: [{ id: "setup", name: "Setup", command: "echo setup-finished", icon: "play", runOnWorktreeCreate: true }] } });
  })));
  const anchor = await t3.thread({ project, title: "Setup demonstration", messages: ["hello"], model: "multi-turn" });
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open(anchor);
  const remaining: Array<{ threadId: string; terminalId: string }> = [];
  for (let index = 1; index <= 10; index++) {
    const started = await runPromise(run(process.execPath, ["apps/server/src/bin.ts", "thread", "start", project, "hello", "--title", `Worktree setup ${index}`, "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json", "--base-dir", T3_HOME], { cwd: APP_DIR, env: { PATH: process.env.PATH, HOME: process.env.HOME } }));
    const thread = JSON.parse(started.stdout) as { threadId: string };
    await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").waitFor({ timeout: 60_000 });
    const terminals = await runPromise(Effect.scoped(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const snapshot = yield* client.subscribeTerminalMetadata({}).pipe(Stream.runHead);
      return Option.isSome(snapshot) && snapshot.value.type === "snapshot" ? snapshot.value.terminals.filter(t => t.threadId === thread.threadId && t.status === "running") : [];
    })));
    remaining.push(...terminals.map(t => ({ threadId: t.threadId, terminalId: t.terminalId })));
    if (terminals.length > 0) {
      await screen.getByRole("button", "Toggle terminal drawer").tap();
      await screen.getByLabel("Terminal input").waitFor();
    }
    await app.screenshot(`worktree-${String(index).padStart(2, "0")}-after-setup`);
  }
  expect(remaining).toHaveLength(0);
});
