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

test("sudo preserve-env keeps the live program label", WEB, async ({ t3, app, screen }) => {
  const transcript = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(transcript, "utf8");
  await fs.writeFile(transcript, original.split("\n").map(line => {
    if (!line) return line;
    const entry = JSON.parse(line);
    const update = entry.frame?.params?.update;
    if (update?.toolCallId === "showcase-test" && update.sessionUpdate === "tool_call") {
      update.title = "sudo --preserve-env=PATH vp test run";
      update.rawInput.command = update.title;
    }
    if (update?.toolCallId === "showcase-test" && update.status === "completed") entry.afterMs = 20000;
    return JSON.stringify(entry);
  }).join("\n"));
  try {
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: { defaultRuntimeMode: "approval-required" } });
    }).pipe(Effect.scoped));
    const project = await t3.project("demo", { "src/math.ts": "export function sum(a: number, b: number) {\n  return a + b;\n}\n" });
    const thread = await t3.thread({ project, title: "Sudo command label", messages: ["Give me a short tour"], model: "showcase" });
    await t3.open(thread);
    await screen.getByRole("button", "Approve", { exact: true }).tap();
    await screen.getByText(/^Running (command|vp)$/).waitFor();
    await app.screenshot("live-sudo-command-label");
    await expect(screen.getByText("Running vp", { exact: true })).toBeVisible();
  } finally {
    await fs.writeFile(transcript, original);
  }
});
