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

if (process.env.MNOTE_ALLOW_RETIRED_AI_AGENT_RUN_SMOKE !== "1") {
  console.log(JSON.stringify({
    ok: true,
    retired: true,
    script: "task178-page-ai-local-subtree-context-smoke.js",
    reason: "旧 /api/ai-agent/run 页面 AI context smoke 已退役；当前请运行 scripts/task-hermes-page-ai-retirement-guard.js 验证 legacy guard。",
  }, null, 2));
  process.exit(0);
}

const assert = require("node:assert");
const { chromium } = require("playwright");
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");

const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);

async function readJsonResponse(response, label) {
  const text = await response.text();
  let payload = null;
  try {
    payload = text ? JSON.parse(text) : null;
  } catch {
    throw new Error(`${label} 返回了非 JSON 内容: ${text.slice(0, 1200)}`);
  }
  assert(response.ok, `${label} 请求失败: ${response.status}; body: ${text.slice(0, 1200)}`);
  return payload;
}

async function postTreeCommand(body, label) {
  const response = await fetchWithTimeout(`${BASE_URL}/api/tree/commands`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  const payload = await readJsonResponse(response, label);
  const result = payload && typeof payload.result === "object" ? payload.result : null;
  assert(result, `${label} 缺少 result`);
  return result;
}

async function createTempPage(title) {
  const result = await postTreeCommand({ action: "create", title }, `创建临时页面 ${title}`);
  assert(result.documentId, `创建临时页面 ${title} 缺少 documentId`);
  assert(result.workspaceId, `创建临时页面 ${title} 缺少 workspaceId`);
  return { documentId: result.documentId, workspaceId: result.workspaceId, title };
}

async function purgeTempPage(target) {
  if (!target?.documentId || !target?.workspaceId) return;
  await postTreeCommand(
    { action: "purge", workspaceId: target.workspaceId, documentId: target.documentId },
    `清理临时页面 ${target.documentId}`,
  );
}

async function waitForRuntimeIsland(page) {
  await page.waitForFunction(
    () => {
      const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const editor = host?.querySelector(".editor-surface .ProseMirror[contenteditable='true']");
      return (
        host?.getAttribute("data-editor-host-kind") === "leptos_tiptap_island" &&
        host?.getAttribute("data-runtime-editor-status") !== "error" &&
        editor instanceof HTMLElement &&
        editor.isContentEditable
      );
    },
    null,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function setLocalHeadingFixture(page, headingText) {
  await page.evaluate((text) => {
    const editor = document.querySelector(".editor-surface .ProseMirror")?.editor;
    if (!editor) throw new Error("找不到 Tiptap editor");
    editor.commands.setContent({
      type: "doc",
      content: [
        { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text }] },
        { type: "paragraph", content: [{ type: "text", text: "本地正文尚未等待服务端 pageSubtree 刷新。" }] },
      ],
    });
  }, headingText);
  await page.waitForFunction(
    (text) => Array.from(document.querySelectorAll(".editor-surface .ProseMirror h2")).some((node) => (node.textContent || "").includes(text)),
    headingText,
    { timeout: UI_TIMEOUT_MS },
  );
}

function stringify(value) {
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
}

async function main() {
  const suffix = Date.now().toString(36);
  const pageTitle = `task178-page-ai-${suffix}`;
  const localHeading = `TASK178 本地 Heading ${suffix}`;
  let target = null;
  let capturedBody = null;
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();

  try {
    target = await createTempPage(pageTitle);
    await page.route("**/api/ai-agent/run", async (route) => {
      const postData = route.request().postData() || "{}";
      capturedBody = JSON.parse(postData);
      await route.fulfill({
        status: 200,
        headers: { "content-type": "text/event-stream; charset=utf-8" },
        body: 'event: assistant_message\ndata: {"text":"ok"}\n\n',
      });
    });

    const url = `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`;
    const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    assert(response, "文档页没有返回响应");
    assert.equal(response.status(), 200, `文档页状态码异常: ${response.status()}`);
    assert.equal(response.headers()["x-mnote-web-owner"], "mnote-web", "文档页必须由 mnote-web 拥有");

    await waitForRuntimeIsland(page);
    await setLocalHeadingFixture(page, localHeading);

    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-input]").fill(`请基于当前本地结构回答：${localHeading}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => Boolean(window.__task178Noop) || true, null, { timeout: 10 });
    await page.waitForFunction(
      () => document.querySelector('[data-testid="wolai-page-ai-drawer"] .wolai-page-ai-message--assistant'),
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    assert(capturedBody, "未捕获 /api/ai-agent/run 请求");
    const contextPayload = capturedBody.context || {};
    const rawContext = stringify(contextPayload);
    assert.equal(contextPayload.pageSubtreeSource, "local", `AI context 应标记本地 pageSubtree，实际: ${rawContext}`);
    assert(rawContext.includes(localHeading), `AI context 应包含本地 heading: ${rawContext.slice(0, 1600)}`);
    assert(Array.isArray(contextPayload.documentBlocks), `AI context 应包含本地 documentBlocks: ${rawContext.slice(0, 1600)}`);
    assert(contextPayload.outline?.some((item) => stringify(item).includes(localHeading)), `AI context outline 应包含本地 heading: ${rawContext.slice(0, 1600)}`);
    assert(contextPayload.subtree?.stats?.headingCount >= 1, `AI context subtree stats 应包含 headingCount: ${rawContext.slice(0, 1600)}`);

    console.log(
      JSON.stringify(
        {
          ok: true,
          baseUrl: BASE_URL,
          documentId: target.documentId,
          workspaceId: target.workspaceId,
          localHeading,
          pageSubtreeSource: contextPayload.pageSubtreeSource,
          headingCount: contextPayload.subtree?.stats?.headingCount ?? null,
        },
        null,
        2,
      ),
    );
  } finally {
    if (target) await purgeTempPage(target).catch(() => undefined);
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

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