import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("POSIX lone dash stops option parsing in command labels", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("shell-labels");
  const cli = makeState(T3_HOME, { CURSOR_API_KEY: process.env.CURSOR_API_KEY }).cli;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {
      providerInstances: { cursor: { driver: "cursor", enabled: true } },
    } });
  }).pipe(Effect.scoped));
  const commands = ["bash - -c 'git status'", "bash -c - '-e'"];
  const threads = [];
  for (const [index, command] of commands.entries()) {
    const result = await runPromise(cli([
      "thread", "start", project,
      `Run exactly this command as one shell tool call: ${command}\nDo not change or wrap it. Do not run any other tools or retry. Then reply only: Done.`,
      "--title", index === 0 ? "Lone dash before command mode" : "Lone dash after command mode",
      "--provider", "cursor", "--model", "composer-2.5", "--wait", "--json",
    ], [0, 1, 2]));
    if (!result.stdout.trim()) throw new Error(`Thread launch failed: ${result.stderr}`);
    threads.push(JSON.parse(result.stdout));
  }
  const labels: string[] = [];
  for (const [index, thread] of threads.entries()) {
    await t3.open(thread);
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Ran 1 command", { exact: false }).tap();
    const row = screen.getByRole("button", index === 0 ? /^(git status|bash - -c 'git status')(, tool call failed)?$/ : /^(bash -c - '-e'|-e)(, tool call failed)?$/).first();
    labels.push((await row.getAttribute("aria-label"))?.replace(/, tool call failed$/, "") ?? "");
    await row.tap();
    await screen.getByText(index === 0 ? "bash: -c: No such file or directory" : "bash: line 1: -e: command not found", { exact: false }).waitFor();
    await screen.getByText("Syncing messages", { exact: false }).waitFor({ state: "hidden" });
    await app.screenshot(index === 0 ? "dash-before-command-mode-expanded" : "dash-after-command-mode-expanded");
  }
  expect(labels[0]).toContain("bash - -c 'git status'");
  expect(labels[1]?.trim()).toBe("-e");
});
