// Run with PROMPT_COMMAND="PS1='proof> '" T3_SCENARIO_INHERIT_ENV=PROMPT_COMMAND to keep public recordings free of local paths.
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Explicit attach stopOnSettle stops the already running terminal", WEB, async ({ t3, app, screen }) => {
  const cwd = await t3.project("terminal-proof");
  const thread = await t3.thread({ project: cwd, title: "Attach then settle", messages: ["hello"] });
  const threadId = ThreadId.make(thread.threadId);
  const rpc = <A>(fn: (client: Effect.Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A, unknown, never>) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* fn(client);
  }).pipe(Effect.scoped));
  const snapshot = (terminalId: string) => rpc(client => client["terminal.observe"]({threadId, terminalId}).pipe(Stream.runHead));
  await rpc(client => Effect.gen(function* () {
    yield* client["terminal.open"]({threadId, terminalId: "default", cwd});
    yield* client["terminal.open"]({threadId, terminalId: "term-2", cwd, stopOnSettle: true});
    yield* client["terminal.write"]({threadId, terminalId: "default", data: "export PS1='proof> '; clear; echo 'Existing terminal: sleep 4711'; sleep 4711\r"});
    yield* client["terminal.write"]({threadId, terminalId: "term-2", data: "export PS1='proof> '; clear; echo 'Control terminal: sleep 4712'; sleep 4712\r"});
  }));
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  // Wait for both real shells to execute the submitted commands, before attaching.
  for (const id of ["default", "term-2"]) {
    await rpc(client => client["terminal.observe"]({threadId, terminalId:id}).pipe(
      Stream.filter(event => "snapshot" in event ? event.snapshot.history.includes(id === "default" ? "Existing terminal: sleep 4711\r\n" : "Control terminal: sleep 4712\r\n") : event.type === "output" && event.data.includes(id === "default" ? "Existing terminal: sleep 4711\r\n" : "Control terminal: sleep 4712\r\n")), Stream.runHead));
  }
  const before = await snapshot("default");
  const control = await snapshot("term-2");
  const controlPid = control.value.snapshot.pid;
  const attached = await rpc(client => client["terminal.attach"]({threadId, terminalId:"default", cwd, worktreePath:null, cols:100, rows:30, stopOnSettle:true, restartIfNotRunning:true}).pipe(Stream.runHead));
  if (!("snapshot" in before.value) || !("snapshot" in attached.value) || before.value.snapshot.pid !== attached.value.snapshot.pid || attached.value.snapshot.status !== "running") throw new Error("Attach did not preserve the live terminal PID");
  console.log("Attach preserved running PID", attached.value.snapshot.pid);
  await app.screenshot("running-before-settlement");
  await rpc(client => client["orchestration.dispatchCommand"]({type:"thread.settle", threadId, commandId:CommandId.make(crypto.randomUUID())}));
  // The web drawer may automatically reopen an idle shell with the same terminal ID.
  // Wait for the original control PID to disappear, not for that ID to stay absent.
  await rpc(client => client["subscribeTerminalMetadata"]({}).pipe(Stream.filter(event => event.type === "remove" ? event.threadId === threadId && event.terminalId === "term-2" : event.type === "snapshot" ? !event.terminals.some(t => t.pid === controlPid) : event.terminal.terminalId === "term-2" && event.terminal.pid !== controlPid), Stream.runHead));
  const result = await rpc(client => client["subscribeTerminalMetadata"]({}).pipe(Stream.runHead));
  // Keep the replacement shell's prompt free of local paths in public captures.
  if (result.value.type === "snapshot") {
    for (const t of result.value.terminals) {
      if (t.threadId === threadId && t.terminalId === "term-2" && t.pid !== controlPid && t.status === "running") {
        await rpc(client => client["terminal.write"]({threadId, terminalId:"term-2", data:"export PS1='proof> '; clear\r"}));
        await rpc(client => client["terminal.observe"]({threadId, terminalId:"term-2"}).pipe(Stream.filter(e => "snapshot" in e ? e.snapshot.history.endsWith("proof> ") : e.type === "output" && e.data.includes("proof> ")), Stream.runHead));
      }
    }
  }
  const stillRunning = result.value.type === "snapshot" && result.value.terminals.some(t => t.threadId === threadId && t.terminalId === "default" && t.status === "running");
  console.log("After settlement: control closed; attached terminal still running:", stillRunning);
  await app.screenshot("attached-terminal-after-settlement");
  await expect(stillRunning).toBe(false);
});
