#!/usr/bin/env node
"use strict";

const assert = require("node:assert");
const { chromium } = require("playwright");
const {
  BASE_URL,
  UI_TIMEOUT_MS,
  cleanupDocuments,
  createTempDocument,
  ensureAuthenticated,
  renameDocument,
} = require("./tree-shell-smoke-helpers");

async function main() {
  const suffix = Date.now().toString(36);
  const title = `TEST-HERMES-AI-queue-${suffix}`;
  const sessionId = `mnote_queue_${suffix}`;
  const runId = `run_queue_${suffix}`;
  const queueId = `queue_${suffix}`;
  const createdIds = [];
  const runBodies = [];
  const cancelBodies = [];
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();

  try {
    await page.route("**/api/ai-agent/run", async (route) => {
      throw new Error(`页面 AI 不应请求旧 /api/ai-agent/run: ${route.request().url()}`);
    });
    await page.route("**/api/hermes/client/profiles", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, profiles: [{ name: "default", active: true, model: "gpt-5" }] }),
      });
    });
    await page.route("**/api/hermes/client/profile-memory**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, memory: "", user: "", soul: "" }),
      });
    });
    await page.route("**/api/hermes/client/skills**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, categories: [], archived: [] }),
      });
    });
    await page.route("**/api/hermes/client/tools**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, tools: [] }),
      });
    });
    await page.route("**/api/hermes/client/sessions", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, sessionId, title: "队列测试", profile: "default" }),
      });
    });
    await page.route(`**/api/hermes/client/sessions/${sessionId}/resume`, async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId,
          session: { sessionId, profile: "default", messages: [] },
          runtime: { sessionId, runId, status: "running", queueLength: 0 },
        }),
      });
    });
    await page.route("**/api/hermes/client/runs", async (route) => {
      runBodies.push(JSON.parse(route.request().postData() || "{}"));
      if (runBodies.length === 1) {
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ ok: true, runId, sessionId, traceId: `trace_run_${suffix}` }),
        });
        return;
      }
      await route.fulfill({
        status: 202,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          queued: true,
          queueId,
          sessionId,
          status: "queued",
          queueLength: 1,
          traceId: `trace_queue_${suffix}`,
        }),
      });
    });
    await page.route(`**/api/hermes/client/sessions/${sessionId}/queue/${queueId}`, async (route) => {
      cancelBodies.push({ method: route.request().method(), url: route.request().url() });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, sessionId, queueId, cancelled: true, queueLength: 0 }),
      });
    });
    await page.route(`**/api/hermes/client/events/${runId}`, async () => {
      // 保持第一个 run 处于 active 状态，让第二条输入进入队列。
    });

    await ensureAuthenticated(page, context.request);
    const target = await createTempDocument(context.request);
    createdIds.push(target.documentId);
    await renameDocument(context.request, target.workspaceId, target.documentId, title);
    await page.goto(
      `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`,
      { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS },
    );

    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-input]").fill(`第一条 ${title}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await waitForCondition(() => runBodies.length === 1, UI_TIMEOUT_MS, "未捕获第一条 run 请求");

    await page.locator("[data-page-ai-input]").fill(`第二条 ${title}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });

    await page.waitForFunction(
      () => (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("已加入 Hermes 队列"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.waitForFunction(
      () => (document.querySelector("[data-page-ai-run-status]")?.textContent || "").includes("队列 1"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.locator('.wolai-page-ai-icon[data-page-ai-tab="agent"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-page-ai-panel-section:not([hidden]) [data-page-ai-tab="runtime"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator(`[data-page-ai-queue-item="${queueId}"] [data-page-ai-action="cancel-queued-run"]`).click({
      timeout: UI_TIMEOUT_MS,
    });
    await page.waitForFunction(
      () => (document.querySelector("[data-page-ai-run-status]")?.textContent || "").includes("队列 1") === false,
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await waitForCondition(() => cancelBodies.length === 1, UI_TIMEOUT_MS, "未捕获取消 queued item 请求");

    assert.equal(runBodies.length, 2, "第二条输入必须到达 mnote-web BFF");
    assert.equal(cancelBodies.length, 1, "取消 queued item 必须调用 mnote-web queue cancel API");
    assert.equal(cancelBodies[0].method, "DELETE", "取消 queued item 必须使用 DELETE");
    assert.equal(runBodies[0].sessionId, sessionId, "第一条 run 必须携带 Hermes sessionId");
    assert.equal(runBodies[1].sessionId, sessionId, "第二条 queued run 必须携带同一个 sessionId");

    console.log(
      JSON.stringify(
        {
          ok: true,
          baseUrl: BASE_URL,
          documentId: target.documentId,
          workspaceId: target.workspaceId,
          sessionId,
          runId,
          queueId,
          runRequests: runBodies.length,
          cancelRequests: cancelBodies.length,
        },
        null,
        2,
      ),
    );
  } finally {
    await cleanupDocuments(context.request, createdIds).catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

async function waitForCondition(predicate, timeoutMs, message) {
  const started = Date.now();
  while (Date.now() - started < timeoutMs) {
    if (predicate()) return;
    await new Promise((resolve) => setTimeout(resolve, 50));
  }
  throw new Error(message);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error));
  process.exit(1);
});
