import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";
const DRIVER = "// Scratch driver for issue #43485. Not committed.\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as NetService from \"@t3tools/shared/Net\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { GlobalFlag } from \"effect/cli\";\nimport { withThreadTools } from \"./src/cli/thread.ts\";\n\nconst [baseDir, action, target] = process.argv.slice(2);\nconst program = withThreadTools(\n  { baseDir: Option.some(baseDir!), json: true, clientLabel: \"proof-43485\" },\n  (tools) => Effect.gen(function* () {\n    const call = (name: string, args: Record<string, unknown>) =>\n      tools.call(name, args, Schema.Unknown) as Effect.Effect<any, any, any>;\n    let threadId = target;\n    if (action === \"launch\") {\n      const listed = yield* call(\"t3_project_list\", {});\n      const project = listed.projects.find((p: any) => p.workspaceRoot === target);\n      const launched = yield* call(\"t3_thread_launch\", {\n        projectId: project.id, title: \"Plan child\", modelSelection: {instanceId: \"devReplay\", model: \"showcase\"},\n        runtimeMode: \"full-access\", interactionMode: \"plan\", message: \"Propose a plan to add a CHANGELOG file.\"\n      });\n      threadId = launched.threadId;\n    } else {\n      yield* call(\"t3_thread_send\", {threadId, message: \"The plan is approved, please implement it.\", mode: \"auto\"});\n    }\n    yield* call(\"t3_thread_wait\", {threadId, timeoutMs: 40000});\n    const read = yield* call(\"t3_thread_read\", {threadId});\n    yield* Effect.sync(() => console.log(JSON.stringify({threadId, interactionMode: read.thread.interactionMode, runtimeMode: read.thread.runtimeMode, status: read.thread.status})));\n  })\n);\n\nprogram.pipe(\n  Effect.tapCause((c) => Effect.sync(() => console.error(\"CAUSE\", JSON.stringify(c, null, 2), String(c)))),\n  Effect.provideService(GlobalFlag.LogLevel, Option.none()),\n  Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)),\n  NodeRuntime.runMain,\n);\n";
test("An MCP approval follow-up moves an idle plan child to build mode", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("plan-follow-up", {"README.md": "Synthetic plan follow-up proof"});
  const script = path.join(APP_DIR, "apps/server/proof-43485.ts");
  await fs.writeFile(script, DRIVER);
  const drive = async (action: string, target: string) => {
    const result = await runPromise(run(process.execPath, [script, T3_HOME, action, target], {cwd: path.join(APP_DIR, "apps/server")}));
    return JSON.parse(result.stdout.trim().split("\n").at(-1)!);
  };
  try {
    const initial = await drive("launch", project);
    await t3.open(initial);
    await screen.getByRole("textbox", "Message Plan child", {exact:true}).waitFor({timeout:60000});
    const after = await drive("send", initial.threadId);
    await t3.open(initial);
    await screen.getByText("The plan is approved, please implement it.", {exact:true}).waitFor({timeout:60000});
    await fs.writeFile(path.join(project, "mcp-readback.json"), JSON.stringify({
      source: "Real MCP t3_thread_read responses", provider: "Replay (dev) / showcase",
      launch: {runtimeMode: "full-access", interactionMode: "plan"},
      afterPlanningTurn: {interactionMode: initial.interactionMode, runtimeMode: initial.runtimeMode, status: initial.status},
      followUp: {tool: "t3_thread_send", mode: "auto", message: "The plan is approved, please implement it."},
      afterFollowUpTurn: {interactionMode: after.interactionMode, runtimeMode: after.runtimeMode, status: after.status}
    }, null, 2));
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("mcp-readback.json");
    await screen.getByRole("option", "mcp-readback.json", {exact:false}).tap();
    await screen.getByText("afterFollowUpTurn", {exact:false}).waitFor({timeout:30000});
    await app.screenshot("after-mcp-approval-follow-up");
    expect(after.interactionMode).toBe("default");
  } finally { await fs.unlink(script); }
});
