import { readFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A stopped scheduled turn records failure and its interruption reason", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    let previous = await readFile(await app.screenshot(`${label}-stability-0`));
    for (let i = 1; i <= 10; i++) {
      await delay(500);
      const current = await readFile(await app.screenshot(`${label}-stability-${i}`));
      if (previous.equals(current)) return;
      previous = current;
    }
    throw new Error(`Capture did not stabilize: ${label}`);
  };
  await t3.project("scheduled-demo");
  await t3.open();
  await screen.getByText("scheduled-demo", { exact: true }).first().waitFor();
  await app.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "New task").tap();
  await screen.getByRole("textbox", "Name", { exact: true }).fill("Scheduled interruption proof");
  await screen.getByRole("combobox", "Project", { exact: true }).tap();
  await screen.getByRole("option", "scheduled-demo", { exact: true }).tap();
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByRole("option", "Use the project checkout", { exact: true }).tap();
  await screen.getByRole("textbox", "Prompt", { exact: true }).fill("Give me a short tour");
  await screen.getByRole("button", "Create task", { exact: true }).tap();
  await screen.getByRole("button", "Actions for Scheduled interruption proof").tap();
  await screen.getByRole("menuitem", "Run now", { exact: true }).tap();
  await app.screenshot("scheduled-run-launched");
  await browser.keyboard.press("Escape");
  await screen.getByRole("button", /Scheduled interruption proof,/).tap();
  await screen.getByRole("button", "Stop generation", { exact: true }).waitFor();
  await screen.getByRole("button", "Stop generation", { exact: true }).tap();
  await screen.getByRole("button", "Stop generation", { exact: true }).waitFor({ state: "hidden" });
  await app.open("/settings/scheduled-tasks");
  await screen.getByText("Scheduled interruption proof", { exact: true }).first().waitFor();
  await capture("scheduled-run-outcome");
  await expect(screen.getByText("failed", { exact: true })).toBeVisible();
  await expect(screen.getByText("The run was interrupted.", { exact: true })).toBeVisible();
});
