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("Sudo bracket probes keep the useful live command label", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("command-label-demo");
  await t3.thread({ project, title: "Setup", messages: ["Start"] });
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = { driver: "opencode", enabled: true, config: { binaryPath: "opencode" } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(T3_HOME);
  const observed: string[] = [];
  for (const [title, command] of [
    ["Control", "git status && sleep 20"],
    ["Sudo file probe", "sudo [ -f /etc/hosts ] && git status && sleep 20"],
    ["Sudo directory probe", "sudo -n [ -d /opt ] && pytest; sleep 20"],
  ]) {
    let threadId: string | undefined;
    for (let attempt = 0; attempt < 8 && !threadId; attempt++) {
      const started = await runPromise(cli(["thread", "start", project,
        `Run exactly this shell command in one tool call, with no modifications or preliminary commands: ${command}. Do not use a timeout shorter than 30 seconds. Then say Done.`,
        "--title", title!, "--provider", "opencode", "--model", "openai/gpt-6-luna", "--json"], [0, 1]));
      if (started.stdout.includes('"threadId"')) threadId = JSON.parse(started.stdout).threadId;
    }
    if (!threadId) throw new Error("OpenCode thread did not start");
    await t3.open({ threadId });
    await screen.getByText(/^Running (git|pytest|command)$/).first().waitFor({ timeout: 90_000 });
    await screen.getByText(/^Working for (?:[89]|1[0-9])s$/).first().waitFor({ timeout: 30_000 });
    observed.push(await browser.evaluate(() => {
      const labels = Array.from(document.querySelectorAll("*"))
        .filter(el => el.children.length === 0 && /^Running (git|pytest|command)$/.test(el.textContent?.trim() ?? ""));
      return labels.map(el => el.textContent?.trim()).join("|");
    }));
    await app.screenshot(title!.toLowerCase().replaceAll(" ", "-"));
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 90_000 });
  }
  expect(observed).toEqual(["Running git", "Running git", "Running pytest"]);
});
