/// <reference lib="dom" />
import { CommandId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Retrying a failed Settled page reveals only the requested 35 rows", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Retry demo");
  const current = { threadId: "scenario:current" };
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const { projects } = yield* client["orchestration.getArchivedShellSnapshot"]({});
    const projectId = projects.find(p => p.workspaceRoot === project)!.id;
    yield* client["orchestration.dispatchCommand"]({ type: "thread.create", commandId: CommandId.make("create:current"), threadId: ThreadId.make(current.threadId), projectId, title: "Current work", createdBy: "user", creationSource: "web", modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null });
    for (let i = 69; i >= 0; i--) {
      const threadId = ThreadId.make(`scenario:settled:${i}`);
      yield* client["orchestration.dispatchCommand"]({ type: "thread.create", commandId: CommandId.make(`create:${i}`), threadId, projectId,
        title: `Settled thread ${String(i).padStart(2, "0")}`, createdBy: "user", creationSource: "web",
        modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null });
      yield* client["orchestration.dispatchCommand"]({ type: "thread.settle", commandId: CommandId.make(`settle:${i}`), threadId });
    }
  }).pipe(Effect.scoped));
  await browser.addInitScript(() => {
    (window as any).failOlderPage = false;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data !== "string") return send.call(this, data);
      const frame = JSON.parse(data);
      if (frame.tag === "orchestration.getOlderSettledThreads" && (window as any).failOlderPage) {
        queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify({ _tag: "Exit", requestId: frame.id, exit: { _tag: "Failure", cause: [{ _tag: "Die", defect: "Deliberate older-page request failure" }] } }) })));
        return;
      }
      return send.call(this, data);
    };
  });
  await t3.open(current);
  await screen.getByRole("button", /^Settled/).tap();
  const more = browser.locator('[data-sidebar-row="settled:more"]');
  await screen.getByRole("button", "Show 25 more", { exact: true }).waitFor();
  await browser.evaluate(() => { (window as any).failOlderPage = true; });
  await more.tap();
  await screen.getByRole("button", "Could not load older threads. Retry", { exact: true }).waitFor();
  await browser.evaluate(() => document.querySelector('[data-sidebar-row="settled:more"]')?.scrollIntoView({ block: "end" }));
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); });
  await browser.evaluate(async () => {
    await new Promise(resolve => setTimeout(resolve, 1500));
    document.querySelector('[data-sidebar-row="settled:more"]')?.scrollIntoView({ block: "end", behavior: "instant" });
    await new Promise(resolve => setTimeout(resolve, 500));
  });
  await app.screenshot("failed-page-before-retry");
  await browser.evaluate(() => { (window as any).failOlderPage = false; });
  await more.tap();
  await screen.getByRole("button", /^Show \d+ more$/).waitFor();
  await browser.evaluate(() => {
    const rows = [...document.querySelectorAll('[data-sidebar-row]')].filter(e => e.textContent?.includes("Settled thread"));
    (window as any).retryRows = rows.length;
    const last = rows.at(-1);
    last?.scrollIntoView({ block: "center" });
  });
  await browser.evaluate(() => document.querySelector('[data-sidebar-row="settled:more"]')?.scrollIntoView({ block: "end" }));
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); });
  // Allow the shelf's row-position transition to finish before framing the evidence.
  await browser.evaluate(async () => {
    await new Promise(resolve => setTimeout(resolve, 1500));
    document.querySelector('[data-sidebar-row="settled:more"]')?.scrollIntoView({ block: "end", behavior: "instant" });
    await new Promise(resolve => setTimeout(resolve, 500));
  });
  await app.screenshot("recovered-retry");
  expect(await browser.evaluate(() => (window as any).retryRows)).toBe(35);
});
