import { expect } from "e2e";
import { readFileSync, writeFileSync, chmodSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("env wrappers retain git in live command labels", WEB, async ({t3, app, screen}) => {
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent = {driver:"claudeAgent",enabled:true,config:{}};
  settings.defaultRuntimeMode = "full-access";
  writeFileSync(settingsPath, JSON.stringify(settings));
  const project = await t3.project("command-label-demo");
  const hook = `${project}/.git/slow-fsmonitor`;
  writeFileSync(hook, "#!/bin/sh\nsleep 12\nprintf 'token\\0'\n");
  chmodSync(hook, 0o755);
  execFileSync("git", ["config", "core.fsmonitor", hook], {cwd:project});
  const cli = makeState(T3_HOME).cli;
  const started = JSON.parse((await runPromise(cli(["thread","start",project,
    "Reply READY only. Do not use tools.","--provider","claudeAgent","--model","claude-haiku-5-5",
    "--title","Git command labels","--wait","--json"]))).stdout);
  const thread = {threadId:started.threadId};
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor({timeout:120000});
  const commands = ["git status", 'env -S"FOO=1 git status"', 'env -vS "FOO=1 git status"', "env - git status", "git status"];
  const labels: string[] = [];
  for (const [i, command] of commands.entries()) {
    await screen.getByRole("textbox").fill(`Run exactly this as one shell tool call, with no description or descriptive title: ${command} . Do not change the command or run other tools. Then reply DONE.`);
    await screen.getByRole("textbox").press("Enter");
    const live = screen.getByText(/^Running (git|command)$/).last();
    await live.waitFor({timeout:120000});
    labels.push(await live.textContent() ?? "");
    await app.screenshot(`${i+1}-${["control","attached-S","bundled-vS","lone-dash","followup-control"][i]}`);
    await screen.getByRole("button", "Stop generation").waitFor({state:"hidden",timeout:120000});
  }
  expect(labels).toEqual(commands.map(() => "Running git"));
});
