import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A self-settle expires after the agent reads a steered message", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Button design");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.defaultRuntimeMode = "full-access";
  settings.providerInstances.claudeAgent = {
    driver: "claudeAgent", enabled: true,
    config: { binaryPath: "/usr/local/bin/claude" },
    environment: ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "NODE_EXTRA_CA_CERTS"].flatMap(name =>
      process.env[name] ? [{ name, value: process.env[name], sensitive: true }] : []),
  };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(T3_HOME);
  let threadId: string | undefined;
  const prompt = 'Call the t3_thread_organize MCP tool with {"action":"settle"} on this thread now. After it returns, say exactly "Self-settle requested. Waiting for a steered message." Then run `python3 -c "import time; time.sleep(90)"` in the shell in the foreground (one command, wait for it). After that, answer any new message I sent by asking me one question, and do not settle again.';
  for (let attempt = 0; attempt < 8 && !threadId; attempt++) {
    const started = await runPromise(cli(["thread", "start", project, prompt, "--title", "Button colour question", "--provider", "claudeAgent", "--model", "claude-haiku-5-5", "--json"], [0, 1]));
    if (started.stdout.includes('"threadId"')) threadId = JSON.parse(started.stdout).threadId;
  }
  if (!threadId) throw new Error("Claude thread did not start");
  await t3.open({ threadId });
  await screen.getByText("Self-settle requested. Waiting for a steered message.", { exact: false }).last().waitFor({ timeout: 120_000 });
  await screen.getByRole("button", "Stop generation").waitFor();
  await screen.getByText("Running python3", { exact: true }).waitFor({ timeout: 60_000 });
  await app.screenshot("self-settle-requested");
  const composer = screen.getByRole("textbox");
  await composer.fill("Which colour should the button be?");
  await screen.getByRole("button", "Steer message", { exact: true }).tap();
  await app.screenshot("message-steered");
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 180_000 });
  // Capture the completed turn before asserting, on both sides.
  await app.screenshot("question-after-steer");
  await expect(screen.getByRole("button", "Un-settle", { exact: true })).toBeHidden();
});
