#!/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_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, extra = {}) {
  const result = await postTreeCommand(
    {
      action: "create",
      title,
      ...extra,
    },
    `创建临时页面 ${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 waitForSidebarRow(page, documentId) {
  const row = page.locator(`[data-testid="wolai-sidebar-row"][data-node-id="${documentId}"]`).first();
  await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return row;
}

async function armTreeLiveProbe(page) {
  await page.evaluate(() => {
    const key = "__task177TreeLiveEvents";
    window[key] = [];
    if (window.__task177TreeLiveProbeArmed) return;
    const push = (kind, detail) => {
      const payload = detail && typeof detail === "object" && "payload" in detail ? detail.payload : detail;
      window[key].push({
        kind,
        applied: document.documentElement.getAttribute("data-mnote-tree-live-applied") || "",
        payload,
      });
      if (window[key].length > 40) window[key].shift();
    };
    window.addEventListener("tree:delta", (event) => push("delta", event.detail));
    window.addEventListener("tree:resync", (event) => push("resync", event.detail));
    window.__task177TreeLiveProbeArmed = true;
  });
}

async function resetTreeLiveProbe(page) {
  await page.evaluate(() => {
    document.documentElement.removeAttribute("data-mnote-tree-live-applied");
    document.documentElement.removeAttribute("data-mnote-tree-live-apply-error");
    window.__task177TreeLiveEvents = [];
  });
}

async function waitForTreeLivePayload(page, label, op, documentId) {
  await page.waitForFunction(
    ({ expectedOp, expectedDocumentId }) => {
      const events = Array.isArray(window.__task177TreeLiveEvents) ? window.__task177TreeLiveEvents : [];
      return events.some((event) => {
        if (!event || (event.kind !== "delta" && event.kind !== "resync")) return false;
        const applied = event.applied || document.documentElement.getAttribute("data-mnote-tree-live-applied") || "";
        if (applied !== "delta" && applied !== "resync") return false;
        try {
          const raw = JSON.stringify(event.payload || {});
          return raw.includes(expectedOp) && raw.includes(expectedDocumentId);
        } catch {
          return false;
        }
      });
    },
    { expectedOp: op, expectedDocumentId: documentId },
    { timeout: UI_TIMEOUT_MS },
  );
  const state = await page.evaluate(() => ({
    applied: document.documentElement.getAttribute("data-mnote-tree-live-applied") || "",
    error: document.documentElement.getAttribute("data-mnote-tree-live-apply-error") || "",
  }));
  assert(["delta", "resync"].includes(state.applied), `${label} 应应用 delta/resync，实际: ${JSON.stringify(state)}`);
  assert(!state.error, `${label} 不应留下 live apply error: ${state.error}`);
}

async function assertPageStillStable(page, rootTitle) {
  await page.waitForFunction(
    (title) => {
      const headerText = document.querySelector("header")?.textContent ?? "";
      const input = document.querySelector('[data-page-title-input="true"][data-pane-role="primary"]');
      const titleValue =
        input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement ? input.value : "";
      return headerText.includes(title) && titleValue.includes(title);
    },
    rootTitle,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function main() {
  const suffix = Date.now().toString(36);
  const rootTitle = `task177-root-${suffix}`;
  const childTitle = `task177-child-${suffix}`;
  const targetTitle = `task177-target-${suffix}`;
  const archiveTitle = `task177-archive-${suffix}`;
  let rootPage = null;
  let childPage = null;
  let targetPage = null;
  let archivedPage = null;
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();

  try {
    rootPage = await createTempPage(rootTitle);
    childPage = await createTempPage(childTitle, {
      workspaceId: rootPage.workspaceId,
      parentId: rootPage.documentId,
    });
    targetPage = await createTempPage(targetTitle, {
      workspaceId: rootPage.workspaceId,
      parentId: rootPage.documentId,
    });
    archivedPage = await createTempPage(archiveTitle, {
      workspaceId: rootPage.workspaceId,
      parentId: rootPage.documentId,
    });

    const rootUrl = `${BASE_URL}/documents/${encodeURIComponent(rootPage.documentId)}?workspaceId=${encodeURIComponent(rootPage.workspaceId)}`;
    const response = await page.goto(rootUrl, { 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 waitForSidebarRow(page, rootPage.documentId);
    await waitForSidebarRow(page, childPage.documentId);
    await waitForSidebarRow(page, targetPage.documentId);
    await waitForSidebarRow(page, archivedPage.documentId);
    await assertPageStillStable(page, rootTitle);
    await armTreeLiveProbe(page);

    await resetTreeLiveProbe(page);
    await postTreeCommand(
      {
        action: "move",
        workspaceId: rootPage.workspaceId,
        documentId: childPage.documentId,
        parentId: targetPage.documentId,
        sortOrder: 0,
      },
      "移动临时子页面",
    );
    await waitForTreeLivePayload(page, "移动后 tree live", "move_document", childPage.documentId);
    await page.waitForFunction(
      ({ childId, targetId }) => {
        const pageRow = document.querySelector(`[data-testid="wolai-sidebar-row"][data-node-id="${childId}"]`);
        const fileRow = document.querySelector(`.tree-row[data-shell-mode="filetree"][data-doc-id="${childId}"], .tree-row[data-shell-mode="filetree"][data-document-id="${childId}"]`);
        return pageRow?.getAttribute("data-parent-id") === targetId && fileRow?.getAttribute("data-parent-id") === targetId;
      },
      { childId: childPage.documentId, targetId: targetPage.documentId },
      { timeout: UI_TIMEOUT_MS },
    );
    await assertPageStillStable(page, rootTitle);

    await resetTreeLiveProbe(page);
    await postTreeCommand(
      {
        action: "archive",
        workspaceId: rootPage.workspaceId,
        documentId: archivedPage.documentId,
      },
      "归档临时页面",
    );
    await waitForTreeLivePayload(page, "归档后 tree live", "remove_document", archivedPage.documentId);
    await page.waitForFunction(
      (documentId) =>
        !document.querySelector(`[data-testid="wolai-sidebar-row"][data-node-id="${documentId}"]`) &&
        !document.querySelector(`.tree-row[data-shell-mode="filetree"][data-doc-id="${documentId}"], .tree-row[data-shell-mode="filetree"][data-document-id="${documentId}"]`),
      archivedPage.documentId,
      { timeout: UI_TIMEOUT_MS },
    );
    await assertPageStillStable(page, rootTitle);

    console.log(
      JSON.stringify(
        {
          ok: true,
          baseUrl: BASE_URL,
          workspaceId: rootPage.workspaceId,
          rootDocumentId: rootPage.documentId,
          movedDocumentId: childPage.documentId,
          movedParentId: targetPage.documentId,
          archivedDocumentId: archivedPage.documentId,
        },
        null,
        2,
      ),
    );
  } finally {
    if (archivedPage) await purgeTempPage(archivedPage).catch(() => undefined);
    if (childPage) await purgeTempPage(childPage).catch(() => undefined);
    if (targetPage) await purgeTempPage(targetPage).catch(() => undefined);
    if (rootPage) await purgeTempPage(rootPage).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);
  });
}
