#!/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/task154-e26-anchor-local-smoke";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";
const CONVERTER_SOURCE = "/mnt/Data1T/mnote/wolai-frontend/src/lib/documents/tiptap-content-converter.ts";
const TARGET_BLOCK_ID = "e26-anchor-target";
const SECOND_BLOCK_ID = "e26-anchor-second";

function assertAnchorSourceBoundary() {
  const spike = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
  assert(!spike.includes('Some(format!("top-level-{index}"))'), "E26 不能继续把 top-level 序号当块锚点 id");
  assert(spike.includes("data-block-id"), "E26 runtime DOM 必须暴露 data-block-id");
  assert(spike.includes("navigator.clipboard.writeText"), "E26 复制链接必须真实写入剪贴板");
  assert(spike.includes("scroll_mnote_block_anchor_from_hash"), "E26 必须处理 reload/hash 定位");
  const converter = fs.readFileSync(CONVERTER_SOURCE, "utf8");
  assert(converter.includes('const BLOCK_ID_ATTR = "blockId"'), "TS 转换层必须继续以 Rust blockId 作为 Tiptap attrs 真源");
  assert(converter.includes("editorBlockDocumentFromTiptapDoc"), "保存链必须继续回到 EditorBlockDocument");
}

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 = `task154-e26-anchor-${Date.now().toString(36)}`;
  const result = await postTreeCommand({ action: "create", title }, "创建 E26 临时文档");
  assert(result.documentId, "创建 E26 临时文档缺少 documentId");
  assert(result.workspaceId, "创建 E26 临时文档缺少 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 }, "清理 E26 临时文档");
}

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 collectBlockIds(value, ids = []) {
  if (!value || typeof value !== "object") return ids;
  if (Array.isArray(value)) {
    for (const item of value) collectBlockIds(item, ids);
    return ids;
  }
  if (typeof value.blockId === "string") ids.push(value.blockId);
  if (typeof value.id === "string") ids.push(value.id);
  if (value.attrs && typeof value.attrs.blockId === "string") ids.push(value.attrs.blockId);
  collectBlockIds(value.content, ids);
  collectBlockIds(value.children, ids);
  collectBlockIds(value.blocks, ids);
  collectBlockIds(value.editorDocument, ids);
  return ids;
}

async function setAnchorFixture(page) {
  await page.evaluate(({ targetBlockId, secondBlockId }) => {
    const editor = document.querySelector('.editor-surface .ProseMirror')?.editor;
    if (!editor) throw new Error('找不到 Tiptap editor');
    editor.commands.setContent({
      type: 'doc',
      content: [
        {
          type: 'paragraph',
          attrs: { blockId: targetBlockId },
          content: [{ type: 'text', text: 'E26 anchor target paragraph' }],
        },
        {
          type: 'heading',
          attrs: { blockId: secondBlockId, level: 2 },
          content: [{ type: 'text', text: 'E26 second heading' }],
        },
      ],
    }, true);
    editor.commands.focus('start');
  }, { targetBlockId: TARGET_BLOCK_ID, secondBlockId: SECOND_BLOCK_ID });
  try {
    await page.waitForFunction(({ targetBlockId, secondBlockId }) => {
      return document.querySelector(`[data-block-id="${targetBlockId}"]`) instanceof HTMLElement
        && document.querySelector(`[data-block-id="${secondBlockId}"]`) instanceof HTMLElement;
    }, { targetBlockId: TARGET_BLOCK_ID, secondBlockId: SECOND_BLOCK_ID }, { timeout: UI_TIMEOUT_MS });
  } catch (error) {
    const diagnostics = await page.evaluate(() => {
      const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const editor = document.querySelector('.editor-surface .ProseMirror');
      return {
        status: host?.getAttribute('data-runtime-editor-status') || null,
        html: editor?.innerHTML || null,
        json: editor?.editor?.getJSON?.() || null,
      };
    }).catch((evalError) => ({ evalError: String(evalError) }));
    throw new Error(`E26 fixture 未渲染 data-block-id: ${JSON.stringify(diagnostics).slice(0, 2400)}; cause=${error.message}`);
  }
}

async function waitForSavedDocument(page, expectedBlockIds) {
  await page.waitForFunction(({ expectedBlockIds }) => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    if (host?.getAttribute('data-runtime-editor-status') !== 'saved') return false;
    const editor = host?.querySelector('.editor-surface .ProseMirror');
    if (!(editor instanceof HTMLElement)) return false;
    return expectedBlockIds.every((blockId) => editor.querySelector(`[data-block-id="${blockId}"]`) instanceof HTMLElement);
  }, { expectedBlockIds }, { timeout: UI_TIMEOUT_MS });
}

async function openBlockMenuForTarget(page) {
  const target = page.locator(`[data-block-id="${TARGET_BLOCK_ID}"]`).first();
  await target.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
  await target.hover({ timeout: UI_TIMEOUT_MS });
  const handle = page.locator('[data-testid="block-drag-handle-trigger"]').first();
  await handle.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await handle.click({ timeout: UI_TIMEOUT_MS });
  const menu = page.locator('[data-testid="block-drag-menu"]').first();
  await menu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return menu;
}

async function main() {
  assertAnchorSourceBoundary();

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, permissions: ["clipboard-read", "clipboard-write"] });
  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()}`);

    await waitForRuntimeIsland(page);
    await setAnchorFixture(page);
    await waitForSavedDocument(page, [TARGET_BLOCK_ID, SECOND_BLOCK_ID]);
    await screenshot(page, "01-anchor-blocks-with-data-block-id");

    const persistedByRequest = [...saveRequests].reverse().find((request) => collectBlockIds(request).includes(TARGET_BLOCK_ID));
    assert(persistedByRequest, `保存请求必须包含 Rust blockId 派生的 EditorBlockDocument/TiptapDocument: ${JSON.stringify(saveRequests.slice(-3)).slice(0, 2000)}`);

    const contentAfterSave = await loadDocumentContent(target, "读取 E26 保存后的正文");
    assert(collectBlockIds(contentAfterSave?.result ?? contentAfterSave).includes(TARGET_BLOCK_ID), `/api/documents/content 必须保留目标 blockId: ${JSON.stringify(contentAfterSave).slice(0, 1600)}`);

    const menu = await openBlockMenuForTarget(page);
    await screenshot(page, "02-block-menu-copy-link-entry");
    await menu.locator('[data-testid="block-drag-menu-item-copy-link"]').first().click({ timeout: UI_TIMEOUT_MS });
    const clipboardText = await page.evaluate(() => navigator.clipboard.readText());
    assert(clipboardText.includes(`/documents/${target.documentId}`), `复制链接必须指向当前页面: ${clipboardText}`);
    assert(clipboardText.endsWith(`#${TARGET_BLOCK_ID}`), `复制链接必须使用 Rust blockId 作为 hash: ${clipboardText}`);
    assert(!clipboardText.includes("top-level-"), `复制链接不能使用前端序号 id: ${clipboardText}`);

    const hashUrl = new URL(clipboardText);
    assert.equal(hashUrl.hash, `#${TARGET_BLOCK_ID}`, `复制链接 hash 异常: ${clipboardText}`);
    await page.goto(hashUrl.href, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction((targetBlockId) => {
      const block = document.querySelector(`[data-block-id="${targetBlockId}"]`);
      if (!(block instanceof HTMLElement)) return false;
      const rect = block.getBoundingClientRect();
      const anchorMatched = block.id === targetBlockId && block.matches(":target");
      const highlighted = anchorMatched
        || block.getAttribute("data-anchor-highlight") === "true"
        || block.classList.contains("mnote-block-anchor-highlight");
      return rect.top >= 0 && rect.top < window.innerHeight * 0.75 && highlighted;
    }, TARGET_BLOCK_ID, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03-after-hash-reload-anchor-highlight");

    console.log(JSON.stringify({ ok: true, baseUrl: BASE_URL, documentId: target.documentId, blockId: TARGET_BLOCK_ID, clipboardText, 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);
  });
}
