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 { test, WEB } from "./t3.ts";

test("A guarded cd keeps the following command's program in the work log", WEB, async ({ t3, app, screen, browser }) => {
  const settings = JSON.parse(await fs.readFile(path.join(T3_HOME, "userdata/settings.json"), "utf8"));
  const fixture = path.join(path.dirname(settings.providerInstances.devReplay.config.commandArgs[0]), "dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const records = original.trim().split("\n").map((line) => JSON.parse(line));
  for (const record of records) {
    const update = record.frame?.params?.update;
    if (update?.toolCallId === "showcase-test" && update.sessionUpdate === "tool_call") {
      update.title = "cd /tmp || exit 1; vp test run";
      update.rawInput.command = update.title;
    }
    if (update?.toolCallId === "showcase-test" && update.status === "completed") record.afterMs = 8000;
  }
  await fs.writeFile(fixture, records.map((record) => JSON.stringify(record)).join("\n") + "\n");
  try {
    const project = await t3.project("command-label-demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
    const thread = await t3.thread({ project, title: "Guarded cd command", messages: ["Give me a short tour"], model: "multi-turn" });
    await t3.open(thread);
    await screen.getByRole("textbox").waitFor();
    await browser.evaluate(() => window.t3dev.replay("showcase"));
    await screen.getByRole("button", "Approve", { exact: true }).tap();
    await screen.getByText(/^Running (command|vp)$/, { exact: true }).waitFor();
    await app.screenshot("guarded-cd-running");
    await expect(screen.getByText("Running vp", { exact: true })).toBeVisible();
  } finally {
    await fs.writeFile(fixture, original);
  }
});
