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

test("Successful true guards do not identify skipped Git commands", WEB, async ({t3, app, screen, browser}) => {
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.pi = {driver: "pi", enabled: true, config: {binaryPath: "/usr/local/bin/pi"}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const project = await t3.project("command-label-proof");
  const {cli} = makeState(T3_HOME);
  let started = "";
  await expect.poll(async () => {
    const result = await runPromise(cli(["thread", "start", project, "Reply only READY. Do not call any tools.", "--title", "True guard command labels", "--provider", "pi", "--model", "openai/gpt-6-luna", "--json"], [0,1])).catch(() => undefined);
    if (result?.stdout.includes("threadId")) started = result.stdout;
    return !!started;
  }, {timeout: 60000}).toBe(true);
  const {threadId} = JSON.parse(started);
  await t3.open({threadId});
  await screen.getByText("READY", {exact: true}).waitFor({timeout: 120000});
  await screen.getByRole("textbox").fill("Run these sequentially, each verbatim as its own separate Bash tool call. Do not combine commands or run them in parallel. Do not add wrappers or extra commands. Commands in order:\ntrue || git --version\nsleep 8\nbuiltin true || git --version\nsleep 8\ntrue && git --version\nsleep 8\nThen reply DONE and say which commands printed output.");
  await screen.getByRole("textbox").press("Enter");
  const labels: string[] = [];
  for (const label of ["true-or", "builtin-true-or", "true-and"]) {
    const activity = screen.getByText(/^(Running|Ran) (git|command)$/).first();
    await activity.waitFor({timeout: 120000});
    labels.push((await activity.textContent()) ?? "");
    await app.screenshot(label);
    await screen.getByText(/^(Running|Ran) sleep$/).first().waitFor({timeout: 60000});
    await screen.getByText(/^(Running|Ran) sleep$/).first().waitFor({state: "hidden", timeout: 60000});
  }
  await screen.getByRole("button", "Stop generation").waitFor({state: "hidden", timeout: 120000});
  await app.screenshot("finished");
  expect(labels.map(text => text.replace(/^Running |^Ran /, ""))).toEqual(["command", "command", "git"]);
});
