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

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

async function fetchPageAggregate(target) {
  const response = await fetchWithTimeout(
    `${BASE_URL}/api/page-aggregate/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`,
  );
  const payload = await readJsonResponse(response, "读取 Page Aggregate");
  assert.equal(response.headers.get("x-mnote-web-owner"), "mnote-web", "Page Aggregate 必须由 mnote-web 拥有");
  return payload;
}

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 observability = document.querySelector('[data-editor-host-observability]');
      const editorNode = host?.querySelector('.editor-surface .ProseMirror[contenteditable="true"]');
      return (
        host?.getAttribute("data-editor-host-kind") === "leptos_tiptap_island" &&
        host?.getAttribute("data-runtime-editor-status") !== "error" &&
        observability?.getAttribute("data-editor-host-active") === "leptos_tiptap_island" &&
        editorNode instanceof HTMLElement &&
        editorNode.isContentEditable
      );
    },
    null,
    { timeout: UI_TIMEOUT_MS },
  );
  return editor;
}

async function readEditorText(page) {
  return page.evaluate(() => {
    const editor = document.querySelector(
      '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror',
    );
    return editor?.textContent ?? "";
  });
}

async function waitForSaved(page, expectedText) {
  await page.waitForFunction(
    (text) => {
      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(text);
    },
    expectedText,
    { timeout: UI_TIMEOUT_MS },
  );
}

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();
  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()}`);
    assert.equal(response.headers()["x-mnote-web-owner"], "mnote-web", "文档页必须由 mnote-web 拥有");

    const bootstrap = await page.locator('script#__MNOTE_EDITOR_BOOTSTRAP__[type="application/json"]').textContent({ timeout: UI_TIMEOUT_MS });
    assert(bootstrap && bootstrap.includes(target.documentId), "editor bootstrap 未包含当前 documentId");
    const aggregateScript = await page.locator('script#__MNOTE_PAGE_AGGREGATE__[type="application/json"]').textContent({ timeout: UI_TIMEOUT_MS });
    assert(aggregateScript && aggregateScript.includes(target.documentId), "Page Aggregate script 未包含当前 documentId");

    const editor = await waitForRuntimeIsland(page);
    const text = `task121-persist-${Date.now().toString(36)}`;
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type(text, { delay: 25 });
    await waitForSaved(page, text);
    assert((await readEditorText(page)).includes(text), "输入文本未进入 ProseMirror");

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction(
      (expected) => {
        const editorNode = document.querySelector(
          '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror',
        );
        return (editorNode?.textContent ?? "").includes(expected);
      },
      text,
      { timeout: UI_TIMEOUT_MS },
    );

    const aggregate = await fetchPageAggregate(target);
    const aggregateText = JSON.stringify(aggregate.result ?? aggregate);
    assert(aggregateText.includes(text), "保存后 Page Aggregate 未读回唯一文本");

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