import { readFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Run now keeps a paused one-time task and its scheduled time", WEB, async ({ t3, app, screen }) => {
  await t3.project("scheduled-demo");
  const state = makeState(T3_HOME);
  const issued = await runPromise(state.cli(["auth", "session", "issue", "--token-only", "--subject", "mcp-client", "--label", "proof"]));
  const { origin } = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const call = (name: string, args: Record<string, unknown>) => Effect.runPromise(Effect.scoped(Effect.gen(function* () {
    const session = yield* mcpToolSession({ endpoint: `${origin}/mcp`, authorization: `Bearer ${issued.stdout.trim()}`, clientName: "scenario-proof" });
    const result: any = yield* session.call(name, args);
    if (result.isError) throw new Error(JSON.stringify(result));
    return result.structuredContent ?? JSON.parse(result.content.find((c: any) => c.type === "text").text);
  })));
  const { projects } = await call("t3_project_list", {});
  const projectId = projects[0].id;
  const runAt = new Date(Date.now() + 3600000).toISOString();
  const task = await call("schedule_task", { projectId, title: "Paused one-time reminder", prompt: "Give me a short tour", schedule: { type: "once", runAt }, bindToCurrentThread: false });
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("switch", "Enable Paused one-time reminder").tap();
  await app.screenshot("paused-before-run");
  await screen.getByRole("button", "Actions for Paused one-time reminder").tap();
  await screen.getByRole("menuitem", "Run now").tap();
  for (let n = 0; n < 300; n++) {
    const pending = await call("list_scheduled_tasks", { projectId });
    const status = pending.tasks[0]?.lastRunStatus;
    if (status === "succeeded") break;
    if (status === "failed") throw new Error(`Dispatch failed: ${JSON.stringify(pending)}`);
    if (n === 299) throw new Error("Dispatch did not finish");
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  let threads: any[] = [];
  for (let n = 0; n < 100; n++) {
    ({ threads } = await call("t3_thread_list", { projectId }));
    if (threads.length) break;
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  if (!threads.length) throw new Error("No scheduled run thread appeared");
  await t3.open({ threadId: threads[0].threadId });
  await screen.getByRole("button", "Approve", { exact: true }).tap();
  for (let n = 0; n < 10; n++) {
    const done = await call("t3_thread_wait", { threadId: threads[0].threadId, timeoutMs: 30000, untilDelegatedWorkSettled: true });
    if (done.status === "completed" || done.thread?.status === "completed") break;
    if (n === 9) throw new Error(`Run did not finish: ${JSON.stringify(done)}`);
  }
  await app.open("/settings/scheduled-tasks");
  await screen.getByRole("heading", "Scheduled tasks", { exact: true }).textContent();
  // Read the server after completion before taking the visible result.
  const listed = await call("list_scheduled_tasks", { projectId });
  await app.screenshot("after-manual-run-completes");
  await expect(screen.getByRole("switch", "Enable Paused one-time reminder")).toBeVisible();
  expect(listed.tasks[0]?.enabled).toBe(false);
  expect(listed.tasks[0]?.schedule.runAt).toBe(runAt);
  await screen.getByRole("switch", "Enable Paused one-time reminder").tap();
  await app.screenshot("resumed-with-original-time");
  const resumed = await call("list_scheduled_tasks", { projectId });
  expect(resumed.tasks[0].nextRunAt).toBe(runAt);
});
