/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";

import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
const decodeSettings = Schema.decodeEffect(SettingsJson);
const encodeSettings = Schema.encodeEffect(SettingsJson);

const threadRuntimeSettings = Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json");
  const original = yield* fs.readFileString(settingsPath);
  const settings = yield* decodeSettings(original);
  return {
    supervise: fs.writeFileString(
      settingsPath,
      yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }),
    ),
    restore: fs.writeFileString(settingsPath, original),
  };
});

test("Queued scheduled work can be snoozed", WEB, async ({ t3, app, browser, screen }) => {
  const settings = await runPromise(threadRuntimeSettings);
  try {
    await runPromise(settings.supervise);
    await browser.setViewport({ width: 1440, height: 1000 });
    await browser.addInitScript(() => {
      const requests = new Set<string>();
      const watched = new WeakSet<WebSocket>();
      const send = WebSocket.prototype.send;
      WebSocket.prototype.send = function (data) {
        if (typeof data === "string") {
          for (const request of [JSON.parse(data)].flat()) {
            if (request?.tag === "orchestration.dispatchCommand" && request.payload?.type === "thread.snooze") requests.add(String(request.id));
          }
        }
        if (!watched.has(this)) {
          watched.add(this);
          this.addEventListener("message", (event) => {
            if (typeof event.data !== "string") return;
            for (const response of [JSON.parse(event.data)].flat()) {
              if (response?._tag === "Exit" && requests.has(String(response.requestId))) document.documentElement.dataset.snoozeResult = response.exit._tag;
            }
          });
        }
        return send.call(this, data);
      };
    });
    const project = await t3.project("demo-project");
    const thread = await t3.thread({ project, title: "Approval held", messages: ["go"], model: "approval" });
    await t3.open(thread);
    await screen.getByRole("button", "Approve", { exact: true }).waitFor();
    await t3.open("/settings/scheduled-tasks");
    await screen.getByRole("button", "New task").tap();
    await screen.getByRole("textbox", "Name").fill("Queued check");
    await screen.getByRole("combobox", "Destination").tap();
    await screen.getByRole("option", "One thread, continuing the conversation").tap();
    await screen.getByRole("combobox", "Destination thread").tap();
    await screen.getByRole("option", "Approval held").tap();
    await screen.getByRole("textbox", "Prompt").fill("Check the queue");
    await screen.getByRole("button", "Create task").tap();
    await screen.getByRole("button", "Actions for Queued check").tap();
    await screen.getByRole("menuitem", "Run now").tap();
    await screen.getByText("Succeeded", { exact: true }).waitFor();
    await t3.open(thread);
    await screen.getByRole("button", "Automation Queued check").waitFor();
    await screen.getByRole("button", "Stop generation").tap();
    await screen.getByRole("button", "Resume thread").waitFor();
    await screen.getByRole("button", "Edit queued message").waitFor();
    await app.screenshot("queued-after-stop");
    await browser.evaluate((id) => {
      const row = document.querySelector(`[data-thread-item$="${id}"] [data-sidebar-row]`);
      if (!row) throw new Error("Thread sidebar row not found");
      row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2 }));
    }, thread.threadId);
    await screen.getByRole("menuitem", "Snooze", { exact: true }).tap();
    await screen.getByRole("menuitem", /^In 3 hours/).tap();
    await browser.locator("html[data-snooze-result]").waitFor({ state: "attached" });
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => undefined)));
    });
    await app.screenshot("snooze-result");
    await t3.open(thread);
    await expect(screen.getByText("Snoozed", { exact: true })).toBeVisible();
    await expect(screen.getByRole("button", "Automation Queued check")).toBeVisible();
    await expect(screen.getByRole("button", "Edit queued message")).toBeVisible();
    await app.screenshot("queued-run-preserved");
  } finally {
    await runPromise(settings.restore);
  }
});
