/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Feedback keeps the pending reply", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("feedback-demo");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.codex = { driver: "codex", enabled: true, config: { binaryPath: "/usr/local/bin/codex" } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Reply with exactly: Ready for feedback.", "--title", "Feedback pending reply", "--provider", "codex", "--model", "gpt-6-luna", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  if (thread.status !== "completed") throw new Error(`Codex did not complete: ${started.stdout}`);
  await t3.open({threadId: thread.threadId});
  await screen.getByRole("button", "Reply to this response").first().tap();
  const composer = screen.getByRole("textbox");
  await composer.tap();
  await composer.pressSequentially("/feedback testing");
  await app.screenshot("feedback-before-send");
  await composer.press("Enter");
  await screen.getByText(/(?:Could not send feedback|Feedback sent) to OpenAI/).first().waitFor({timeout: 60_000});
  await app.screenshot("feedback-after-send");
  const idleReplyKept = await browser.evaluate(() => !!document.querySelector('[aria-label="Cancel reply"]'));
  const idleText = await browser.evaluate(() => document.querySelector('[data-testid="composer-editor"]')?.textContent);
  await runPromise(cli(["thread", "send", thread.threadId, "Run the shell command sleep 60 and then say Done. Do not finish before the command returns."]));
  await screen.getByRole("button", "Stop generation").waitFor({timeout: 60_000});
  await screen.getByRole("button", "Reply to this response").first().tap();
  await composer.tap();
  await composer.pressSequentially("/feedback running testing");
  const send = screen.getByRole("button", /^(Submit message|Steer message)$/);
  const runningLabel = await send.getAttribute("aria-label");
  await send.hover();
  await screen.getByText(/^(Click to steer,|Submit message$)/).waitFor();
  await browser.evaluate(async () => {
    await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    const popup = document.querySelector('[data-slot="tooltip-popup"]');
    await Promise.all((popup?.getAnimations({subtree: true}) ?? []).map(animation => animation.finished));
    return null;
  });
  await app.screenshot("running-feedback-button");
  await composer.press("Enter");
  await screen.getByText("Feedback sent to OpenAI.", {exact: true}).nth(1).waitFor({timeout: 60_000});
  await app.screenshot("running-feedback-after-send");
  const runningReplyKept = await browser.evaluate(() => !!document.querySelector('[aria-label="Cancel reply"]'));
  const runningText = await browser.evaluate(() => document.querySelector('[data-testid="composer-editor"]')?.textContent);
  await screen.getByRole("button", "Stop generation").tap();
  expect({idleReplyKept, idleText, runningLabel, runningReplyKept, runningText}).toEqual({idleReplyKept: true, idleText: "", runningLabel: "Submit message", runningReplyKept: true, runningText: ""});
});
