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

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

const TASK = "task504-page-ai-history-agent-filter-smoke";
const OUTPUT_DIR = path.join(process.cwd(), "tmp", TASK);
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}

function documentUrl(root, relativePath) {
  const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", fileUrl(root));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

function writeWorkspaceManifest(root, ownerId, workspaceId) {
  fs.mkdirSync(path.join(root, ".mnote"), { recursive: true });
  fs.writeFileSync(
    path.join(root, ".mnote", "workspace.json"),
    `${JSON.stringify({
      workspaceId,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "ai_sessions", "markdown_edit"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function saveScreenshot(page, name) {
  const target = path.join(OUTPUT_DIR, `${name}.png`);
  await page.screenshot({ path: target, fullPage: false });
  return target;
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const suffix = Date.now().toString(36);
  const actorId = "mnote-e2e";
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task504-history-"));
  const rootUri = fileUrl(root);
  const workspaceId = `local-ws:${actorId}:task504`;
  const relativePath = "HistoryAgentFilter.md";
  const documentId = localMdDocumentId(relativePath);
  const longGeminiMessage = [
    "Gemini 历史预览应只显示摘要，不应把 ChatOnly 的完整长消息塞进历史列表。",
    "这段内容用于模拟网页问答返回的完整长回复，历史列表应保留可扫描性。",
    "FULL_TAIL_SHOULD_NOT_RENDER",
  ].join("");
  const sessions = [
    {
      sessionId: `mnote_task504_gemini_${suffix}`,
      runId: `run_task504_gemini_${suffix}`,
      title: "Gemini 问答",
      profile: "shared_gemini_chat",
      acpRuntime: "hermes",
      status: "completed",
      payload: {
        agentId: "chat_only",
        profileId: "shared_gemini_chat",
        profile: "shared_gemini_chat",
        acpRuntime: "hermes",
        message: longGeminiMessage,
      },
      createdAt: "2026-05-30T08:00:00Z",
      updatedAt: "2026-05-30T08:02:00Z",
      persistence: "sqlite_acp_runtime_store",
    },
    {
      sessionId: `mnote_task504_doubao_${suffix}`,
      runId: `run_task504_doubao_${suffix}`,
      title: "豆包问答",
      profile: "shared_doubao_chat",
      acpRuntime: "hermes",
      status: "completed",
      payload: {
        agentId: "chat_only",
        profileId: "shared_doubao_chat",
        profile: "shared_doubao_chat",
        acpRuntime: "hermes",
        message: "豆包短回复",
      },
      createdAt: "2026-05-30T08:01:00Z",
      updatedAt: "2026-05-30T08:01:30Z",
      persistence: "sqlite_acp_runtime_store",
    },
    {
      sessionId: `mnote_task504_stale_chatonly_${suffix}`,
      runId: `run_task504_stale_chatonly_${suffix}`,
      title: "旧 ChatOnly profile",
      profile: "myHermes",
      acpRuntime: "hermes",
      status: "completed",
      payload: {
        agentId: "chat_only",
        profileId: "myHermes",
        profile: "myHermes",
        acpRuntime: "hermes",
        message: "旧数据里误写成 Hermes profile 的 ChatOnly 会话",
      },
      createdAt: "2026-05-30T08:00:50Z",
      updatedAt: "2026-05-30T08:01:00Z",
      persistence: "sqlite_acp_runtime_store",
    },
    {
      sessionId: `mnote_task504_hermes_${suffix}`,
      runId: `run_task504_hermes_${suffix}`,
      title: "Hermes 问答",
      profile: "shared_lite",
      acpRuntime: "hermes",
      status: "completed",
      payload: {
        agentId: "hermes",
        profileId: "shared_lite",
        profile: "shared_lite",
        acpRuntime: "hermes",
        message: "Hermes 回复",
      },
      createdAt: "2026-05-30T08:00:30Z",
      updatedAt: "2026-05-30T08:00:45Z",
      persistence: "sqlite_acp_runtime_store",
    },
  ];
  const capturedRuns = [];
  const capturedSessionCreates = [];
  const splitDeltaDetailText = "历史回答不应按 delta 拆成多个气泡。";
  let caughtError = null;
  const screenshots = {};

  writeWorkspaceManifest(root, actorId, workspaceId);
  fs.writeFileSync(path.join(root, relativePath), ["# History Agent Filter", "", suffix, ""].join("\n"), "utf8");

  const browser = await chromium.launch({
    headless: true,
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 960 },
    locale: "zh-CN",
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();

  try {
    await page.route("**/api/user/access-policy**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          controlPlane: "sqlite",
          grants: [{
            id: `grant_task504_${suffix}`,
            userId: actorId,
            workspaceId,
            rootUri,
            rootPath: root,
            permission: "write",
            recursive: true,
            capabilities: ["ai", "markdown_edit"],
            source: "user",
            status: "active",
          }],
        }),
      });
    });
    await page.route("**/api/ui/preferences**", async (route) => {
      if (route.request().method() === "GET") {
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ok: true,
            owner: "mnote-web",
            result: {
              aiPreferences: {
                "ai.common.default_agent_id": "chat_only",
                "ai.agent.hermes.profile_id": "shared_deepseek_chat",
                "ai.common.context_refs.default_selected": {
                  current_page: true,
                  selection: false,
                  active_editor: false,
                  file: false,
                  folder: false,
                  changed_files: false,
                },
              },
            },
          }),
        });
        return;
      }
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, owner: "mnote-web", result: {} }),
      });
    });
    await page.route("**/api/documents/buffer-state**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          result: { dirtyState: "", fileVersion: `task504-${suffix}` },
        }),
      });
    });
    await page.route("**/api/hermes/client/gateway/health**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          gateway: { ok: true, status: "mocked" },
          profile: { name: "reasonix", modelConfigured: true, apiKeyConfigured: true },
          suggestions: [],
        }),
      });
    });
    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/profiles**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          active: "mnoteai",
          profiles: [{ name: "mnoteai", label: "MNote AI", modelConfigured: true, apiKeyConfigured: true }],
        }),
      });
    });
    await page.route("**/api/ai/agent-profiles**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          agentId: "hermes",
          profiles: [
            { profileId: "shared_deepseek_chat", kind: "shared", displayName: "DeepSeek Chat", baseProfile: "deepseek-chat", isolatedProfile: "openclaw-deepseek-chat", readonly: true },
            { profileId: "shared_doubao_chat", kind: "shared", displayName: "豆包 Chat", baseProfile: "doubao-chat", isolatedProfile: "openclaw-doubao-chat", readonly: true },
            { profileId: "shared_gemini_chat", kind: "shared", displayName: "Gemini Chat", baseProfile: "gemini-chat", isolatedProfile: "openclaw-gemini-chat", readonly: true },
            { profileId: "shared_lite", kind: "shared", displayName: "Lite", baseProfile: "lite", isolatedProfile: "lite", readonly: true },
          ],
        }),
      });
    });
    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/capabilities**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, runtime: "mnote", categories: [], archived: [] }),
      });
    });
    await page.route("**/api/hermes/client/sessions**", async (route) => {
      const requestUrl = new URL(route.request().url());
      const detailMatch = requestUrl.pathname.match(/\/api\/hermes\/client\/sessions\/([^/]+)(?:\/resume)?$/);
      if (route.request().method() === "GET") {
        if (detailMatch) {
          const sessionId = decodeURIComponent(detailMatch[1]);
          await route.fulfill({
            status: 200,
            headers: { "content-type": "application/json" },
            body: JSON.stringify({
              ok: true,
              persistence: "sqlite_acp_runtime_store",
              sessionStorage: "sqlite_control_plane",
              sessionId,
              session: {
                sessionId,
                messages: [],
                runs: [{
                  sessionId,
                  runId: `run_task504_detail_${suffix}`,
                  title: "Gemini 问答",
                  profile: "shared_gemini_chat",
                  acpRuntime: "hermes",
                  status: "completed",
                  payload: {
                    agentId: "chat_only",
                    profileId: "shared_gemini_chat",
                    profile: "shared_gemini_chat",
                    acpRuntime: "hermes",
                    message: "历史详情测试",
                  },
                  createdAt: "2026-05-30T08:00:00Z",
                  updatedAt: "2026-05-30T08:02:00Z",
                  persistence: "sqlite_acp_runtime_store",
                }],
              },
              events: Array.from(splitDeltaDetailText).map((delta, index) => ({
                eventId: `evt_task504_detail_${index}`,
                sessionId,
                runId: `run_task504_detail_${suffix}`,
                eventType: "message.delta",
                payload: { delta },
                createdAt: `2026-05-30T08:01:${String(index).padStart(2, "0")}Z`,
                persistence: "sqlite_acp_runtime_store",
              })),
            }),
          });
          return;
        }
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ok: true,
            persistence: "sqlite_acp_runtime_store",
            sessions,
          }),
        });
        return;
      }
      if (route.request().method() === "POST" && detailMatch && requestUrl.pathname.endsWith("/resume")) {
        const sessionId = decodeURIComponent(detailMatch[1]);
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ok: true,
            persistence: "sqlite_acp_runtime_store",
            sessionStorage: "sqlite_control_plane",
            sessionId,
            session: {
              sessionId,
              messages: [{ role: "assistant", content: splitDeltaDetailText }],
              runs: [],
            },
            events: [],
          }),
        });
        return;
      }
      capturedSessionCreates.push(JSON.parse(route.request().postData() || "{}"));
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId: `mnote_task504_new_${suffix}`,
          title: "当前页问答",
          persistence: "sqlite_acp_runtime_store",
        }),
      });
    });
    await page.route("**/api/hermes/client/runs", async (route) => {
      const body = JSON.parse(route.request().postData() || "{}");
      capturedRuns.push(body);
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          upstream: {
            runId: `run_task504_current_page_${suffix}`,
            traceId: `trace_task504_current_page_${suffix}`,
          },
        }),
      });
    });
    await page.route("**/api/hermes/client/events/run_task504_current_page_*", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "text/event-stream; charset=utf-8" },
        body: [
          "event: message.delta",
          "data: {\"text\":\"### TASK504_CURRENT_PAGE_OK\\n- **Markdown 渲染**\"}",
          "",
          "event: run.completed",
          "data: {\"output\":\"### TASK504_CURRENT_PAGE_OK\\n- **Markdown 渲染**\"}",
          "",
        ].join("\n"),
      });
    });

    await ensureAuthenticated(page, context.request);
    const response = await page.goto(documentUrl(root, relativePath), {
      waitUntil: "domcontentloaded",
      timeout: UI_TIMEOUT_MS,
    });
    assert(response && response.status() === 200, `文档页状态码异常: ${response && response.status()}`);
    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="wolai-page-ai-drawer"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="history"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="history"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator(`[data-page-ai-session-row="mnote_task504_gemini_${suffix}"]`).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    const historyPanel = page.locator('[data-page-ai-panel="history"]');
    const historyText = await historyPanel.innerText({ timeout: UI_TIMEOUT_MS });
    assert(historyText.includes("ChatOnly / Gemini"), "历史会话应显示 Gemini 所属 agent");
    assert(historyText.includes("ChatOnly / 豆包"), "历史会话应显示豆包所属 agent");
    assert(historyText.includes("Hermes / Lite"), "历史会话应显示 Hermes profile");
    assert(!historyText.includes("ChatOnly / myHermes"), "ChatOnly 历史不应显示 Hermes profile 标签");
    assert(!historyText.includes("FULL_TAIL_SHOULD_NOT_RENDER"), "历史预览不应显示 ChatOnly 完整长消息尾部");
    assert.strictEqual(capturedSessionCreates.length, 0, "打开 Page AI 和历史列表不应创建空白后端会话");

    const filter = page.locator('[data-page-ai-session-agent-filter]');
    await filter.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await filter.selectOption("chat_only:shared_gemini_chat", { timeout: UI_TIMEOUT_MS });
    await page.locator(`[data-page-ai-session-row="mnote_task504_gemini_${suffix}"]`).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator(`[data-page-ai-session-row="mnote_task504_doubao_${suffix}"]`).count(),
      0,
      "筛选 Gemini 后不应显示豆包会话",
    );
    await filter.selectOption("chat_only:shared_doubao_chat", { timeout: UI_TIMEOUT_MS });
    await page.locator(`[data-page-ai-session-row="mnote_task504_doubao_${suffix}"]`).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator(`[data-page-ai-session-row="mnote_task504_gemini_${suffix}"]`).count(),
      0,
      "筛选豆包后不应显示 Gemini 会话",
    );
    screenshots.history = await saveScreenshot(page, "history-filter");

    await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="history"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="chat"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="new-session"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.querySelector('[data-page-ai-agent-chip]')?.textContent?.includes("DeepSeek"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.evaluate(({ staleWorkspaceId, documentId, rootUri: currentRootUri }) => {
      const staleSnapshot = {
        schema: "mnote.open_editors_snapshot.v1",
        generatedAt: Date.now(),
        activeObjectIdentity: "page:primary",
        activeEditor: {
          objectIdentity: "page:primary",
          workspacePath: {
            schema: "mnote.workspace_path.v1",
            workspaceId: staleWorkspaceId,
            sourceKind: "local_folder",
            rootUri: currentRootUri,
            relativePath: "HistoryAgentFilter.md",
            documentId,
            objectIdentity: "page:primary",
            assetId: "",
            resourceKind: "page",
          },
          paneRole: "primary",
          documentId,
          workspaceId: staleWorkspaceId,
          title: "Stale page target",
          kind: "page",
          editorKind: "page",
          active: true,
          dirtyState: "",
          preview: false,
          pinned: true,
          lastActiveAt: Date.now(),
          assetId: "",
          path: "HistoryAgentFilter.md",
        },
        editors: [],
        resourceEditors: [],
        groups: { primary: { paneRole: "primary", activeObjectIdentity: "page:primary", editors: [], resourceEditors: [] }, secondary: { paneRole: "secondary", activeObjectIdentity: "", editors: [], resourceEditors: [] } },
      };
      staleSnapshot.editors = [staleSnapshot.activeEditor];
      staleSnapshot.groups.primary.editors = [staleSnapshot.activeEditor];
      window.__mnoteOpenEditorsSnapshot = staleSnapshot;
      const previous = window.__mnoteDocumentPaneRuntime || {};
      window.__mnoteDocumentPaneRuntime = {
        ...previous,
        getOpenEditorsSnapshot: () => staleSnapshot,
      };
    }, {
      staleWorkspaceId: `${workspaceId}:stale`,
      documentId,
      rootUri,
    });
    await page.locator("[data-page-ai-input]").fill(`task504 current page target ${suffix}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="chat"] [data-page-ai-conversation]').getByText("TASK504_CURRENT_PAGE_OK").waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const markdownState = await page.locator('[data-page-ai-panel="chat"] [data-page-ai-conversation]').evaluate((root) => ({
      heading: Boolean(root.querySelector(".wolai-page-ai-message--assistant .wolai-page-ai-message-text h3")),
      strong: Boolean(root.querySelector(".wolai-page-ai-message--assistant .wolai-page-ai-message-text strong")),
      rawHeadingMarkers: root.textContent?.includes("### TASK504_CURRENT_PAGE_OK") || false,
      rawStrongMarkers: root.textContent?.includes("**Markdown 渲染**") || false,
    }));
    assert.deepStrictEqual(markdownState, {
      heading: true,
      strong: true,
      rawHeadingMarkers: false,
      rawStrongMarkers: false,
    }, `AI 面板应渲染 Markdown，而不是显示原始标记: ${JSON.stringify(markdownState)}`);
    assert.strictEqual(capturedRuns.length, 1, "当前页 ChatOnly 请求应通过前置 target 校验并到达 runs API");
    assert.strictEqual(capturedSessionCreates.length, 1, "只有真实发送消息时才应创建后端会话");
    assert.strictEqual(capturedRuns[0].agentId, "chat_only", "应使用 ChatOnly agent");
    assert.strictEqual(capturedRuns[0].profile, "shared_deepseek_chat", "应使用 DeepSeek ChatOnly profile");
    assert.strictEqual(
      capturedRuns[0].runTargetSnapshot?.editorTarget?.workspaceId,
      workspaceId,
      "只选择当前页时 runTargetSnapshot 应使用当前 workspaceId，而不是 stale active editor workspaceId",
    );
    assert(
      capturedRuns[0].contextRefs.some((item) => item.kind === "current_page" && item.workspaceId === workspaceId),
      "当前页 contextRef 应保留当前 workspaceId",
    );
    assert(
      !capturedRuns[0].contextRefs.some((item) => item.kind === "active_editor"),
      "取消打开资源后不应发送 active_editor contextRef",
    );
    screenshots.currentPageTarget = await saveScreenshot(page, "current-page-target");

    await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="history"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="history"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-session-agent-filter]').selectOption("all", { timeout: UI_TIMEOUT_MS });
    await page.locator(`[data-page-ai-session-resume="mnote_task504_gemini_${suffix}"]`).click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="chat"] [data-page-ai-conversation]').getByText(splitDeltaDetailText).waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const restoredAssistantMessages = await page.locator(".wolai-page-ai-message--assistant").evaluateAll((nodes) => (
      nodes.map((node) => node.textContent || "").filter((text) => text.includes("历史回答") || text.includes("不应按"))
    ));
    assert.deepStrictEqual(
      restoredAssistantMessages,
      [`AI${splitDeltaDetailText}`],
      "恢复历史详情时 message.delta 必须合并为一条 assistant 消息，不能按字拆气泡",
    );
    screenshots.historyRestore = await saveScreenshot(page, "history-restore");
  } catch (error) {
    caughtError = error;
    try {
      screenshots.failure = await saveScreenshot(page, "failure");
    } catch (_) {}
  } finally {
    await browser.close();
    const result = {
      ok: !caughtError,
      error: caughtError ? String(caughtError && caughtError.stack || caughtError) : null,
      screenshots,
      root,
      capturedRuns,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    if (caughtError) {
      console.error(JSON.stringify(result, null, 2));
      process.exit(1);
    }
    console.log(JSON.stringify(result, null, 2));
  }
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
