import * as fs from "node:fs/promises";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
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("env argv0 commands name git in the live work log", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("env-argv0-demo", {
    "bin/env": await fs.readFile(process.env.ENV97_BINARY!),
  });
  await fs.chmod(`${project}/bin/env`, 0o755);
  const instanceId = ProviderInstanceId.make("opencode");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { defaultRuntimeMode: "full-access" }, providerInstanceMutation: {
      operation: "upsert", instanceId, instance: {
        driver: ProviderDriverKind.make("opencode"), displayName: "OpenCode", enabled: true,
        config: { binaryPath: process.env.OPENCODE_BINARY! },
      },
    }});
  }).pipe(Effect.scoped));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project,
    "Reply only READY. Do not run tools.", "--title", "GNU env argv0 labels", "--provider", instanceId,
    "--model", "anthropic/claude-haiku-5-5", "--wait", "--json"]));
  const { threadId } = JSON.parse(started.stdout);
  await t3.open({ threadId });
  let failure: unknown;
  for (const [option, label] of [["--argv0=app", "long-option"], ["-a app", "short-option"]]) {
    await screen.getByRole("textbox").fill(`Run exactly one Bash command: ./bin/env ${option} git status . Then immediately write a 2000 word essay about version control, using no further tools. The bundled bin/env is genuine GNU coreutils 9.7, built for this test.`);
    await screen.getByRole("textbox").press("Enter");
    const row = screen.getByRole("button", /^(Running|Ran) (git|command)$/);
    await row.waitFor({ timeout: 120000 });
    await app.screenshot(`env-argv0-${label}-live-label`);
    try {
      await expect(screen.getByRole("button", /^(Running|Ran) git$/)).toBeVisible();
      await app.screenshot(`env-argv0-${label}-named-label`);
    } catch (error) {
      failure ??= error;
    }
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 120000 });
  }
  if (failure !== undefined) throw failure;
});
