import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("An explicitly named empty thread keeps its name after its first prompt", WEB, async ({t3, app, screen}) => {
  await t3.project("Release demo");
  const named = await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const snapshot = yield* Effect.promise(async () => (await fetch(`${app.baseUrl}/api/projects`, {headers:{authorization:`Bearer ${issued.stdout.trim()}`}})).json());
    const mcpIssued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only", "--subject", "mcp-client"]);
    const client = yield* mcpToolSession({endpoint:`${app.baseUrl}/mcp`, authorization:`Bearer ${mcpIssued.stdout.trim()}`, clientName:"scenario"});
    const threads: Array<{threadId:string}> = [];
    for (const title of ["Release thread 2", "Release notes", "Release planning"]) {
      const result = yield* client.call("t3_thread_launch", {
        projectId:snapshot.projects[0].id, title,
        modelSelection:{instanceId:"devReplay", model:"showcase"}
      });
      const response = result as {structuredContent?: {threadId:string}; content:Array<{text:string}>};
      threads.push(response.structuredContent ?? JSON.parse(response.content[0]!.text));
    }
    return threads;
  }).pipe(Effect.scoped));
  const send = async (text: string, approval = true) => {
    await screen.getByRole("textbox").fill(text);
    await screen.getByRole("textbox").press("Enter");
    if (text !== "/compact" && approval) await screen.getByRole("button", "Approve", {exact:true}).tap();
  };
  await t3.open(named[0]!);
  await screen.getByRole("textbox").waitFor({state:"visible"});
  await screen.getByText("Syncing messages...", {exact:false}).waitFor({state:"hidden"});
  await app.screenshot("named-empty");
  const keptNames: boolean[] = [];
  await send("work on this");
  await screen.getByText("This turn is a replay.", {exact:false}).waitFor({state:"visible"});
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await app.screenshot("placeholder-shaped-name-after-prompt");
  keptNames.push(await screen.getByRole("heading", "Release thread 2").isVisible());
  await t3.open(named[1]!);
  await send("/compact");
  await screen.getByText("Cannot compact an empty thread", {exact:false}).waitFor({state:"visible"});
  await send("draft the changelog for the next release");
  await screen.getByText("This turn is a replay.", {exact:false}).waitFor({state:"visible"});
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await app.screenshot("chosen-name-after-compact-and-prompt");
  keptNames.push(await screen.getByRole("heading", "Release notes").isVisible());
  await t3.open(named[2]!);
  await send("work on this");
  await screen.getByText("This turn is a replay.", {exact:false}).waitFor({state:"visible"});
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await app.screenshot("ordinary-name-control");
  keptNames.push(await screen.getByRole("heading", "Release planning").isVisible());
  await screen.getByRole("button", "New thread", {exact:true}).tap();
  await send("/compact");
  await screen.getByText("Cannot compact an empty thread", {exact:false}).waitFor({state:"visible"});
  await send("fix the flaky login test", false);
  await screen.getByText("This turn is a replay.", {exact:false}).waitFor({state:"visible"});
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await app.screenshot("draft-compact-gets-prompt-title-control");
  keptNames.push(await screen.getByRole("heading", "fix the flaky login test").isVisible());
  await expect(keptNames).toEqual([true, true, true, true]);
});
