import * as fs from "node:fs/promises";
import * as path from "node:path";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { finishImageCompression, holdImageCompression, pasteWideScreenshot } from "./image-compression-hold.ts";
import { test, WEB } from "./t3.ts";

test("Stopping an unanswered question retains its preparing screenshot in the thread draft", WEB, async ({ t3, app, browser, screen }) => {
  await holdImageCompression(browser);
  const project = await t3.project("Screenshot demo");
  // Use the real replay agent with its question recording changed to accept free text.
  const recording = path.join(project, "question.ndjson");
  const fixture = await fs.readFile(path.join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/acp_elicitation/registry_transcript.ndjson"), "utf8");
  await fs.writeFile(recording, fixture.split("\n").filter(Boolean).map((line) => {
    const entry = JSON.parse(line);
    if (entry.frame?.method === "elicitation/create" && entry.frame?.params?.requestedSchema) {
      delete entry.frame.params.requestedSchema.properties.schema_vs_ui_flexibility.enum;
    }
    return JSON.stringify(entry);
  }).join("\n"));
  const agent = path.join(project, "question-replay.ts");
  const replay = await fs.readFile(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  await fs.writeFile(agent, replay.replace('`${FIXTURES}/acp_elicitation/registry_transcript.ndjson`', JSON.stringify(recording)));
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.devReplay.config.commandArgs = [agent];
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const thread = await t3.thread({ project, title: "Unanswered screenshot question", messages: ["Ask me which approach to use."], model: "question" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Use the screenshot to guide the layout.");
  await pasteWideScreenshot(browser);
  await app.screenshot("question-screenshot-preparing");
  await screen.getByRole("button", "Stop generation").tap();
  await screen.getByRole("button", "Fixture", { exact: true }).waitFor({ state: "hidden" });
  await screen.getByRole("button", "Stopping", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("question-closed-still-preparing");
  await finishImageCompression(browser);
  await app.screenshot("draft-after-preparation");
  await expect(composer).toContainText("Use the screenshot to guide the layout.");
  await expect(screen.getByRole("button", "Preview screenshot.png")).toBeVisible();
});
