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

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

const 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);
const SCREENSHOT_DIR = process.env.MNOTE_PHASE_E_SCREENSHOT_DIR || "/mnt/Data1T/mnote/tmp/wolai-editor-parity/task153-e25-toc-local-smoke";
const TOC_EXTENSION_SOURCE = "/mnt/Data1T/mnote/design/05-editor-mainline/reference-code/leptos-tiptap/tiptap/src/extensions/tiptap_toc_node.ts";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";

function assertTocBridgeSource() {
  const extension = fs.readFileSync(TOC_EXTENSION_SOURCE, "utf8");
  assert(extension.includes('name: "tocNode"'), "E25 必须注册真实 Tiptap tocNode schema");
  assert(extension.includes("Node.create"), "E25 tocNode 必须基于 Tiptap Node.create");
  assert(extension.includes("insertTocNode"), "E25 必须提供 insertTocNode 命令入口");
  assert(extension.includes("editor.state.doc.descendants"), "E25 TOC 列表必须从当前 Tiptap doc headings 派生，不能写死静态列表");
  const spike = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
  assert(spike.includes("editor.insert_toc_node(TiptapTocNodeAttrs"), "E25 /toc 必须通过 leptos-tiptap insert_toc_node bridge");
  assert(!spike.includes('TiptapContent::json(json!({ "type": "tocNode"'), "E25 /toc 不能在 spike 中手写 tocNode JSON 绕过 bridge 命令");
}

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);
  assert(payload?.result, `${label} 缺少 result`);
  return payload.result;
}

async function createTempDocument() {
  const title = `task153-e25-toc-${Date.now().toString(36)}`;
  const result = await postTreeCommand({ action: "create", title }, "创建 E25 临时文档");
  assert(result.documentId, "创建 E25 临时文档缺少 documentId");
  assert(result.workspaceId, "创建 E25 临时文档缺少 workspaceId");
  return { documentId: result.documentId, workspaceId: result.workspaceId, title };
}

async function purgeTempDocument(target) {
  if (!target?.documentId || !target?.workspaceId) return;
  await postTreeCommand({ action: "purge", workspaceId: target.workspaceId, documentId: target.documentId }, "清理 E25 临时文档");
}

async function loadDocumentContent(target, label) {
  const url = `${BASE_URL}/api/documents/content?documentId=${encodeURIComponent(target.documentId)}&workspaceId=${encodeURIComponent(target.workspaceId)}`;
  const response = await fetchWithTimeout(url, { method: "GET" });
  return readJsonResponse(response, label);
}

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

async function screenshot(page, name) {
  fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
  await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
}

function findToc(value) {
  if (!value || typeof value !== "object") return null;
  if (Array.isArray(value)) return value.map(findToc).find(Boolean) || null;
  if (value.type === "tocNode" || value.blockType === "toc" || value.type === "toc") return value;
  return findToc(value.content) || findToc(value.children) || findToc(value.props?.tiptapTocNode) || findToc(value.props?.tiptapToc);
}

function tocShowTitle(value) {
  const toc = findToc(value);
  return toc?.attrs?.showTitle ?? toc?.props?.tiptapTocNode?.attrs?.showTitle ?? null;
}

async function setHeadingFixture(page) {
  await page.evaluate(() => {
    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: 1 }, content: [{ type: 'text', text: 'E25 主标题' }] },
        { type: 'paragraph', content: [{ type: 'text', text: 'E25 正文' }] },
        { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'E25 子标题' }] },
        { type: 'paragraph' },
      ],
    });
    editor.commands.focus('end');
  });
  await page.waitForFunction(() => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    return host?.getAttribute("data-runtime-editor-status") !== "error"
      && document.querySelectorAll('.editor-surface .ProseMirror h1, .editor-surface .ProseMirror h2').length >= 2;
  }, null, { timeout: UI_TIMEOUT_MS });
}

async function main() {
  assertTocBridgeSource();

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  const saveRequests = [];
  page.on("request", (request) => {
    if (!request.url().includes("/api/documents/save")) return;
    const body = request.postData();
    if (!body) return;
    try {
      saveRequests.push(JSON.parse(body));
    } catch {
      saveRequests.push({ raw: body });
    }
  });

  let target = null;
  try {
    target = await createTempDocument();
    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()}`);

    const editor = await waitForRuntimeIsland(page);
    await setHeadingFixture(page);
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("/");
    const slash = page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first();
    await slash.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const slashText = await slash.innerText();
    assert(slashText.includes("页面目录"), `slash 菜单缺少页面目录: ${slashText}`);
    assert(slashText.includes("/toc"), `slash 菜单缺少页面目录快捷码 /toc: ${slashText}`);

    const tocItem = page.locator('[data-testid="slash-item-toc"]').first();
    await tocItem.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
    await screenshot(page, "01-slash-toc-entry");
    await tocItem.click({ timeout: UI_TIMEOUT_MS });

    await page.waitForFunction(() => {
      const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const toc = document.querySelector('.editor-surface .ProseMirror [data-type="toc-node"]');
      const items = Array.from(document.querySelectorAll('.tiptap-table-of-contents-item')).map((item) => item.textContent || '');
      return host?.getAttribute("data-runtime-editor-status") === "saved"
        && toc instanceof HTMLElement
        && toc.getAttribute("data-show-title") === "true"
        && items.includes("E25 主标题")
        && items.includes("E25 子标题");
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "02-after-toc-insert");

    await page.evaluate(() => {
      const editor = document.querySelector('.editor-surface .ProseMirror')?.editor;
      if (!editor) throw new Error('找不到 Tiptap editor');
      const doc = editor.getJSON();
      const content = Array.isArray(doc.content) ? [...doc.content] : [];
      content.push({ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'E25 动态标题' }] });
      editor.commands.setContent({ ...doc, content });
    });
    await page.waitForFunction(() => Array.from(document.querySelectorAll('.tiptap-table-of-contents-item')).some((item) => (item.textContent || '').includes('E25 动态标题')), null, { timeout: UI_TIMEOUT_MS });

    const firstTocItem = page.locator('.tiptap-table-of-contents-item', { hasText: 'E25 主标题' }).first();
    await firstTocItem.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => window.location.hash.startsWith('#heading-'), null, { timeout: UI_TIMEOUT_MS });

    await page.locator('[data-testid="toc-show-title-toggle"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const toc = document.querySelector('.editor-surface .ProseMirror [data-type="toc-node"]');
      return host?.getAttribute("data-runtime-editor-status") === "saved"
        && toc instanceof HTMLElement
        && toc.getAttribute("data-show-title") === "false"
        && !document.querySelector('.tiptap-table-of-contents-title');
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03-toc-title-hidden");

    const lastSave = [...saveRequests].reverse().find((request) => findToc(request.tiptapDocument));
    assert(lastSave?.tiptapDocument, `TOC 插入后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
    assert.equal(findToc(lastSave.tiptapDocument)?.type, "tocNode", `保存请求必须包含 tocNode: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);

    const contentAfterToc = await loadDocumentContent(target, "读取 TOC 保存后的正文");
    const savedContent = contentAfterToc?.result?.content;
    assert(findToc(savedContent), `/api/documents/content 必须保留 tocNode 真源: ${JSON.stringify(savedContent).slice(0, 1600)}`);
    assert.equal(tocShowTitle(savedContent), false, `/api/documents/content 必须保留 showTitle=false: ${JSON.stringify(savedContent).slice(0, 1600)}`);

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction(() => {
      const toc = document.querySelector('.editor-surface .ProseMirror [data-type="toc-node"]');
      const items = Array.from(document.querySelectorAll('.tiptap-table-of-contents-item')).map((item) => item.textContent || '');
      return toc instanceof HTMLElement
        && toc.getAttribute("data-show-title") === "false"
        && items.includes("E25 主标题")
        && items.includes("E25 动态标题");
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "04-after-reload-toc");

    console.log(JSON.stringify({ ok: true, baseUrl: BASE_URL, documentId: target.documentId, screenshotDir: SCREENSHOT_DIR }, null, 2));
  } finally {
    if (target) await purgeTempDocument(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);
  });
}
