#!/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/task144-e19-indent-local-smoke";

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

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 waitForSavedText(page, text) {
  await page.waitForFunction((expected) => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const editor = host?.querySelector('.editor-surface .ProseMirror');
    return host?.getAttribute("data-runtime-editor-status") === "saved" && (editor?.textContent || "").includes(expected);
  }, text, { timeout: UI_TIMEOUT_MS });
}

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

function collectTypes(value, out = []) {
  if (Array.isArray(value)) {
    value.forEach((item) => collectTypes(item, out));
    return out;
  }
  if (!value || typeof value !== "object") return out;
  if (typeof value.type === "string") out.push(value.type);
  collectTypes(value.content, out);
  return out;
}

function hasNestedBulletList(value) {
  if (!value || typeof value !== "object") return false;
  if (Array.isArray(value)) return value.some(hasNestedBulletList);
  if (value.type === "listItem" && Array.isArray(value.content)) {
    return value.content.some((item) => item?.type === "bulletList" || item?.type === "orderedList" || item?.type === "taskList");
  }
  if ((value.type === "bullet_list_item" || value.type === "numbered_list_item" || value.type === "todo") && Array.isArray(value.children)) {
    return value.children.length > 0;
  }
  return hasNestedBulletList(value.content);
}

async function main() {
  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 editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("/");
    const slashBullet = page.locator('[data-testid="slash-item-bullet"]').first();
    await slashBullet.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await slashBullet.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("E19 parent");
    await page.keyboard.press("Enter");
    await page.keyboard.type("E19 child");
    await waitForSavedText(page, "E19 child");
    await screenshot(page, "01-before-indent");

    await page.keyboard.press("Tab");
    await page.waitForFunction(() => !!document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedText(page, "E19 child");
    await screenshot(page, "02-after-tab-indent");

    const lastSave = saveRequests.at(-1);
    assert(lastSave?.tiptapDocument, `Tab 缩进后必须走 /api/documents/save 并提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
    assert(hasNestedBulletList(lastSave.tiptapDocument), `保存请求里的 Tiptap JSON 必须包含真实嵌套列表结构: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
    assert(collectTypes(lastSave.tiptapDocument).filter((type) => type === "bulletList").length >= 2, "保存请求应包含父/子两层 bulletList");

    await page.keyboard.press("Shift+Tab");
    await page.waitForFunction(() => !document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedText(page, "E19 child");
    await screenshot(page, "03-after-shift-tab-outdent");

    await page.keyboard.press("Tab");
    await page.waitForFunction(() => !!document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedText(page, "E19 child");
    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction(() => !!document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "04-after-reload-nested-list");

    const contentAfterReload = await loadDocumentContent(target, "读取缩进保存后的正文");
    const savedContent = contentAfterReload?.result?.content;
    assert(hasNestedBulletList(savedContent), `刷新后的 /api/documents/content 必须保留嵌套列表真源: ${JSON.stringify(savedContent).slice(0, 1600)}`);

    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);
  });
}
