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

const assert = require("node:assert");
const fs = require("node:fs/promises");
const path = require("node:path");
const { chromium } = require("playwright");

const ROOT = path.resolve(__dirname, "..");
const BASE_URL = (process.env.MNOTE_UI_BASE_URL || process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const OUT_DIR = path.join(ROOT, "tmp", "task426-mnote-web-main-no-reload-smoke");

function cssString(value) {
  return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}

async function quickLogin(page) {
  await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
  if (await quickLoginButton.count()) {
    await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS });
  }
}

async function readCreatedState(page, documentId) {
  return page.evaluate((id) => {
    const pageRows = Array.from(document.querySelectorAll(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(id)}"]`));
    const fileRows = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]"))
      .filter((row) => row.getAttribute("data-doc-id") === id || row.getAttribute("data-document-id") === id)
      .map((row) => row.getAttribute("data-row-id"));
    return {
      url: location.href,
      title: document.title,
      localApplied: document.documentElement.getAttribute("data-mnote-tree-local-command-applied") || "",
      pageRows: pageRows.length,
      fileRows,
      nodeCount: document.querySelectorAll("li[data-node-id]").length,
    };
  }, documentId);
}

async function insertMindmapThroughSlash(page) {
  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 editor.click({ timeout: UI_TIMEOUT_MS });
  await page.keyboard.type("/");
  const item = page.getByTestId("slash-item-mindmap").first();
  await item.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await item.click({ timeout: UI_TIMEOUT_MS });
  const root = page.getByTestId("mnote-mindmap-editor-root").first();
  await root.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const mindmapId = await root.evaluate((node) => node instanceof HTMLElement ? node.dataset.mnoteMindmapId || "" : "");
  assert(mindmapId, "新建思维导图后缺少 mindmapId");
  return mindmapId;
}

async function readMindmapAssetState(page, documentId, mindmapId) {
  return page.evaluate(
    ({ documentId: docId, mindmapId: assetId }) => {
      const rows = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]"))
        .filter((row) => row.getAttribute("data-asset-id") === assetId)
        .map((row) => ({
          rowId: row.getAttribute("data-row-id"),
          docId: row.getAttribute("data-doc-id") || row.getAttribute("data-document-id"),
          title: row.textContent?.trim() || "",
          kind: row.querySelector(".tree-kind-badge")?.getAttribute("data-kind") || "",
        }));
      return {
        rows,
        localApplied: document.documentElement.getAttribute("data-mnote-assets-local-applied") || "",
        expectedDocId: docId,
      };
    },
    { documentId, mindmapId },
  );
}

async function main() {
  await fs.mkdir(OUT_DIR, { recursive: true });
  const browser = await chromium.launch({ headless: process.env.HEADFUL !== "1" });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  const requests = [];
  page.on("response", (response) => {
    const url = response.url();
    if (url.includes("/api/tree/commands") || url.includes("/api/sidebar") || url.includes("/api/tree/events") || url.includes("/api/mindmap/")) {
      requests.push({ url, status: response.status() });
    }
  });

  try {
    await quickLogin(page);
    await page.goto(BASE_URL, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    const beforeCount = await page.locator("li[data-node-id]").count();

    await page.getByRole("button", { name: "新建页面" }).click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
    const createdDocumentId = new URL(page.url()).pathname.split("/").filter(Boolean).pop();
    assert(createdDocumentId, "新建后 URL 缺少 documentId");
    await page.waitForFunction(
      (id) => {
        const pageRow = document.querySelector(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(id)}"]`);
        const fileRows = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]"))
          .filter((row) => row.getAttribute("data-doc-id") === id || row.getAttribute("data-document-id") === id);
        return pageRow && fileRows.some((row) => row.getAttribute("data-row-id") === `doc:${id}`);
      },
      createdDocumentId,
      { timeout: UI_TIMEOUT_MS },
    );
    const afterCreate = await readCreatedState(page, createdDocumentId);
    assert.equal(afterCreate.localApplied, "create", "新建页面应由主文档壳本地 apply");
    assert.equal(afterCreate.pageRows, 1, "Page Tree 应立即出现新页面");
    assert.deepEqual(afterCreate.fileRows.sort(), [`doc:${createdDocumentId}`], "File Tree 应立即出现新页面 .md 行");

    const mindmapId = await insertMindmapThroughSlash(page);
    await page.waitForFunction(
      ({ assetId }) => {
        return Boolean(document.querySelector(`#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-asset-id="${CSS.escape(assetId)}"]`));
      },
      { assetId: mindmapId },
      { timeout: UI_TIMEOUT_MS },
    );
    const afterMindmapCreate = await readMindmapAssetState(page, createdDocumentId, mindmapId);
    assert.equal(afterMindmapCreate.localApplied, "true", "新建思维导图应由 assets-changed 本地 apply 到 File Tree");
    assert.equal(afterMindmapCreate.rows.length, 1, "File Tree 应立即出现新建思维导图 asset 行");
    assert.equal(afterMindmapCreate.rows[0].rowId, `asset:${mindmapId}`, "File Tree mindmap rowId 应匹配 asset id");
    assert.equal(afterMindmapCreate.rows[0].docId, createdDocumentId, "File Tree mindmap asset 应挂在当前页面下");

    const rowSelector = `#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${cssString(createdDocumentId)}"]`;
    await page.locator(rowSelector).scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
    page.once("dialog", async (dialog) => {
      await dialog.accept();
    });
    await page.locator(rowSelector).click({ button: "right", timeout: UI_TIMEOUT_MS });
    await page.getByRole("menuitem", { name: /删除/ }).click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      (id) => {
        const pageRow = document.querySelector(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(id)}"]`);
        const fileRows = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]"))
          .filter((row) => row.getAttribute("data-doc-id") === id || row.getAttribute("data-document-id") === id);
        return !pageRow && fileRows.length === 0;
      },
      createdDocumentId,
      { timeout: UI_TIMEOUT_MS },
    );
    const afterDelete = await readCreatedState(page, createdDocumentId);
    assert.equal(afterDelete.localApplied, "remove", "删除页面应由主文档壳本地 apply");
    assert.equal(afterDelete.pageRows, 0, "Page Tree 应立即移除删除页面");
    assert.equal(afterDelete.fileRows.length, 0, "File Tree 应立即移除删除页面");

    const result = {
      ok: true,
      baseUrl: BASE_URL,
      beforeCount,
      createdDocumentId,
      mindmapId,
      afterCreate,
      afterMindmapCreate,
      afterDelete,
      requests,
    };
    await fs.writeFile(path.join(OUT_DIR, "result.json"), `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(JSON.stringify(result, null, 2));
  } finally {
    await browser.close();
  }
}

main().catch(async (error) => {
  await fs.mkdir(OUT_DIR, { recursive: true });
  const result = {
    ok: false,
    baseUrl: BASE_URL,
    error: error && error.stack ? error.stack : String(error),
  };
  await fs.writeFile(path.join(OUT_DIR, "result.json"), `${JSON.stringify(result, null, 2)}\n`, "utf8");
  console.error(result.error);
  process.exit(1);
});
