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 { APP_DIR, 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);
  const marker = (yield* Path.Path).join(T3_HOME, "fail-replay");
  const wrapper = (yield* Path.Path).join(T3_HOME, "replay-failure.mjs");
  yield* fs.writeFileString(marker, "ready");
  yield* fs.writeFileString(wrapper, `
import { spawn } from "node:child_process";
import { watch } from "node:fs";
import { createInterface } from "node:readline";
const child = spawn(process.execPath, [process.argv[2]], { stdio: ["pipe", "pipe", "inherit"] });
let pending;
const suppressed = new Set();
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
createInterface({ input: process.stdin }).on("line", (line) => {
  const message = JSON.parse(line);
  if (message.method === "session/prompt") pending = { id: message.id, sessionId: message.params.sessionId };
  child.stdin.write(line + "\\n");
});
createInterface({ input: child.stdout }).on("line", (line) => {
  const message = JSON.parse(line);
  if (suppressed.delete(message.id)) return;
  if (pending?.id === message.id) pending = undefined;
  process.stdout.write(line + "\\n");
});
const watcher = watch(process.argv[3], () => {
  if (!pending) return;
  const failed = pending;
  pending = undefined;
  suppressed.add(failed.id);
  send({ jsonrpc: "2.0", id: failed.id, error: { code: -32603, message: "Replay provider failed after the scheduled occurrence queued." } });
  child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: failed.sessionId } }) + "\\n");
});
process.stdin.on("end", () => child.stdin.end());
child.on("exit", (code) => { watcher.close(); process.exit(code ?? 0); });
`);
  const instances = settings.providerInstances as Record<string, { config: Record<string, unknown> }>;
  const replay = instances.devReplay!;
  return {
    fail: fs.writeFileString(marker, "fail"),
    supervise: fs.writeFileString(
      settingsPath,
      yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required",
        providerInstances: { ...instances, devReplay: { ...replay, config: { ...replay.config,
          commandPath: process.execPath,
          commandArgs: [wrapper, (yield* Path.Path).join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), marker],
        } } },
      }),
    ),
    restore: fs.writeFileString(settingsPath, original),
  };
});

test(
  "A recurring task reports when its queued occurrence is held",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const settings = await runPromise(threadRuntimeSettings);
    try {
      // Supervised mode makes the approval recording wait for an answer, which holds its turn open.
      await runPromise(settings.supervise);
      const project = await t3.project("scheduled-hold");
      await t3.thread({ project, title: "Earlier work", messages: ["Start"] });
      const thread = await t3.thread({
        project,
        title: "Waiting scheduled thread",
        messages: ["Ask a question"],
        model: "approval",
      });

      await t3.open("/settings/scheduled-tasks");
      await screen.getByRole("button", "New task").tap();
      await screen.getByRole("textbox", "Name").fill("Held recurring task");
      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", "Waiting scheduled thread").tap();
      await screen.getByRole("textbox", "Prompt").fill("Scheduled check prompt");
      await screen.getByRole("button", "Every interval").tap();
      await screen.getByRole("spinbutton", "Run every").fill("1");
      await screen.getByRole("button", "Create task").tap();

      await t3.open(thread);
      await screen.getByRole("button", "Approve", { exact: true }).waitFor();
      await screen
        .getByRole("button", "Automation Held recurring task")
        .waitFor({ timeout: 100_000 });
      // The replay agent returns a provider error through the real ACP adapter.
      await runPromise(settings.fail);
      await screen.getByText("Replay provider failed after the scheduled occurrence queued.", { exact: false }).first().waitFor();
      await screen.getByRole("button", "Resume thread").waitFor();
      await screen.getByRole("button", "Edit queued message").waitFor();

      await app.screenshot("001-held-thread-queue");
      await app.open("/settings/scheduled-tasks");
      // Cross a full recurring interval on both sides before reading the warning.
      await new Promise((resolve) => setTimeout(resolve, 70_000));
      await app.screenshot("002-blocked-recurring-tick");
      const reportedHeld = await browser.evaluate(() => document.body.innerText.includes(
        "A previous occurrence is held in the thread queue. Resume or remove it to run this task again.",
      ));

      await t3.open(thread);
      await screen.getByRole("button", "Remove queued message").tap();
      await screen.getByRole("button", "Edit queued message").waitFor({ state: "hidden" });
      await app.screenshot("003-held-occurrence-removed");
      await app.open("/settings/scheduled-tasks");
      await new Promise((resolve) => setTimeout(resolve, 70_000));
      await app.screenshot("004-next-interval-after-removal");
      const stillReportedHeld = await browser.evaluate(() => document.body.innerText.includes(
        "A previous occurrence is held in the thread queue. Resume or remove it to run this task again.",
      ));
      await expect(reportedHeld).toBe(true);
      await expect(stillReportedHeld).toBe(false);
    } finally {
      await runPromise(settings.restore);
    }
  },
);
