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

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

const 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(process.cwd(), "tmp", "task455-local-folder-mindmap-clean-smoke");
const RESULT_PATH = path.join(OUT_DIR, "result.json");
const ACTOR_ID = "user_real";
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}

function documentUrl(root, relativePath) {
  const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", fileUrl(root));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

function writeWorkspaceManifest(root) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: `local-ws:${ACTOR_ID}:task455`,
      ownerId: ACTOR_ID,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function screenshot(page, name) {
  const file = path.join(OUT_DIR, `${name}.png`);
  await page.screenshot({ path: file, fullPage: true });
  return file;
}

async function openDocument(page, root, relativePath) {
  await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function insertMindmapThroughSlash(page) {
  const editor = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror[contenteditable="true"]').first();
  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 });
  await page.locator('[data-testid="mnote-mindmap-editor-root"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function assertSlashMenuAnchorsAfterMindmap(page) {
  const editor = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror[contenteditable="true"]').first();
  await editor.click({ timeout: UI_TIMEOUT_MS });
  await page.keyboard.press(process.platform === "darwin" ? "Meta+End" : "Control+End");
  await page.keyboard.type("/");
  await page.getByTestId("mnote-leptos-tiptap-slash-menu").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.waitForFunction(
    () => document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]')?.getAttribute("data-mnote-slash-positioned") === "host",
    null,
    { timeout: UI_TIMEOUT_MS },
  );
  const state = await page.evaluate(() => {
    const menu = document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]');
    const mindmap = document.querySelector('[data-testid="mnote-mindmap-editor-root"]');
    const menuRect = menu?.getBoundingClientRect();
    const mindmapRect = mindmap?.getBoundingClientRect();
    const pointNode = menuRect
      ? document.elementFromPoint(menuRect.left + 24, menuRect.top + 24)
      : null;
    return {
      menuRect: menuRect ? { top: menuRect.top, bottom: menuRect.bottom, left: menuRect.left, right: menuRect.right } : null,
      mindmapRect: mindmapRect ? { top: mindmapRect.top, bottom: mindmapRect.bottom, left: mindmapRect.left, right: mindmapRect.right } : null,
      menuPosition: menu instanceof HTMLElement ? getComputedStyle(menu).position : "",
      menuZIndex: menu instanceof HTMLElement ? getComputedStyle(menu).zIndex : "",
      hostPositioned: menu instanceof HTMLElement ? menu.getAttribute("data-mnote-slash-positioned") || "" : "",
      hitInsideMenu: Boolean(pointNode && menu && menu.contains(pointNode)),
      viewportHeight: window.innerHeight,
    };
  });
  assert(state.menuRect, `slash 菜单应可见: ${JSON.stringify(state)}`);
  assert.equal(state.menuPosition, "fixed", `slash 菜单应由宿主定位到 viewport 层: ${JSON.stringify(state)}`);
  assert(Number(state.menuZIndex) >= 120, `slash 菜单层级应高于 mindmap/块工具: ${JSON.stringify(state)}`);
  assert(state.hitInsideMenu, `slash 菜单不应被思维导图或其它层遮挡: ${JSON.stringify(state)}`);
  assert(state.menuRect.top >= 0 && state.menuRect.bottom <= state.viewportHeight, `slash 菜单不应超出视口: ${JSON.stringify(state)}`);
  if (state.mindmapRect) {
    assert(
      state.menuRect.top > state.mindmapRect.top - 80,
      `mindmap 后输入 / 时菜单不应回退到编辑器左上固定旧位置: ${JSON.stringify(state)}`,
    );
  }
  await page.keyboard.press("Escape");
  return state;
}

async function readState(page) {
  return page.evaluate(() => {
    const editorRoot = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const mindmapRoot = document.querySelector('[data-testid="mnote-mindmap-editor-root"]');
    const rustShell = document.querySelector('[data-testid="mindmap-rust-shell"]');
    const fileTreeRows = Array.from(document.querySelectorAll('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"]'))
      .map((row) => {
        const element = row;
        return {
          rowId: element.getAttribute("data-row-id") || "",
          rowKind: element.getAttribute("data-row-kind") || "",
          title: element.textContent || "",
          assetId: element.getAttribute("data-asset-id") || "",
          objectKind: element.getAttribute("data-object-kind") || "",
          documentId: element.getAttribute("data-document-id") || element.getAttribute("data-doc-id") || "",
          expanded: element.getAttribute("aria-expanded") || "",
        };
      });
    const mindmapRows = fileTreeRows.filter((row) => row.objectKind === "mindmap" || row.assetId.endsWith(".json") || row.title.includes("思维导图"));
    return {
      url: window.location.href,
      editorStatus: editorRoot instanceof HTMLElement ? editorRoot.getAttribute("data-runtime-editor-status") || "" : "",
      mindmapId: mindmapRoot instanceof HTMLElement ? mindmapRoot.dataset.mnoteMindmapId || "" : "",
      shellMindmapId: rustShell instanceof HTMLElement ? rustShell.getAttribute("data-mnote-mindmap-id") || "" : "",
      bodyText: document.body?.innerText || "",
      fileTreeRows,
      mindmapRows,
      consoleMarker: document.documentElement.getAttribute("data-mnote-last-mindmap-asset-id") || "",
    };
  });
}

async function waitForStableEditorSave(page, networkRecords, label) {
  const beforeCount = networkRecords.length;
  let lastState = null;
  const deadline = Date.now() + UI_TIMEOUT_MS;
  while (Date.now() < deadline) {
    lastState = await readState(page);
    const pageBodyWrites = networkRecords
      .slice(beforeCount)
      .filter((record) => record.url.includes("/api/page-body/write"));
    const lastWrite = pageBodyWrites[pageBodyWrites.length - 1] || null;
    if (lastWrite && lastWrite.status >= 200 && lastWrite.status < 300 && lastState.editorStatus === "saved") {
      return { ok: true, label, lastState, pageBodyWrites };
    }
    if (lastState.editorStatus === "error" || lastState.editorStatus === "external-change-conflict") {
      break;
    }
    await page.waitForTimeout(250);
  }
  return {
    ok: false,
    label,
    lastState,
    pageBodyWrites: networkRecords.slice(beforeCount).filter((record) => record.url.includes("/api/page-body/write")),
  };
}

async function waitForMindmapId(page) {
  await page.waitForFunction(
    () => {
      const root = document.querySelector('[data-testid="mnote-mindmap-editor-root"]');
      return root instanceof HTMLElement && /^思维导图\d{6}\.json$/.test(root.dataset.mnoteMindmapId || "");
    },
    null,
    { timeout: UI_TIMEOUT_MS },
  );
  const state = await readState(page);
  return state.mindmapId;
}

function rowMatchesMindmap(row, mindmapId) {
  const assetId = String(row && row.assetId || "");
  const title = String(row && row.title || "");
  return assetId === mindmapId
    || assetId.endsWith(`/${mindmapId}`)
    || assetId.endsWith(`:${mindmapId}`)
    || title.includes(mindmapId);
}

async function sampleFileTree(page, mindmapId, durationMs = 5_000) {
  const samples = [];
  const deadline = Date.now() + durationMs;
  while (Date.now() < deadline) {
    const state = await readState(page);
    samples.push({
      at: Date.now(),
      mindmapId: state.mindmapId,
      mindmapRows: state.mindmapRows.map((row) => ({
        rowId: row.rowId,
        assetId: row.assetId,
        title: row.title,
        objectKind: row.objectKind,
      })),
    });
    assert.equal(
      state.mindmapRows.filter((row) => rowMatchesMindmap(row, mindmapId)).length,
      1,
      `本轮 mindmap 文件树行应稳定存在且仅一行: ${JSON.stringify(state.mindmapRows)}`,
    );
    assert(
      !state.mindmapRows.some((row) => row.assetId === "mindmap" || row.title.includes("思维导图.json")),
      `不应出现退化的 mindmap 资源行: ${JSON.stringify(state.mindmapRows)}`,
    );
    await page.waitForTimeout(250);
  }
  return samples;
}

async function postMindmapCommand(page, documentId, mindmapId) {
  return page.evaluate(async ({ documentId, mindmapId }) => {
    const response = await fetch(`/api/mindmap/${encodeURIComponent(documentId)}/${encodeURIComponent(mindmapId)}`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        commandName: "mindmap.command.apply",
        commands: [{
          type: "updateText",
          mindmapId,
          nodeId: "root",
          text: "KMIND 本轮验证",
        }],
        projectionRevision: 1,
      }),
    });
    const payload = await response.json().catch(() => null);
    if (!response.ok) {
      throw new Error(`mindmap_command_failed_${response.status}:${JSON.stringify(payload)}`);
    }
    return payload;
  }, { documentId, mindmapId });
}

async function main() {
  fs.mkdirSync(OUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task455-mindmap-"));
  const pageDir = path.join(root, "CleanPage");
  fs.mkdirSync(pageDir, { recursive: true });
  writeWorkspaceManifest(root);
  const relativePath = "CleanPage/CleanPage.md";
  const markdownPath = path.join(root, relativePath);
  fs.writeFileSync(markdownPath, "# CleanPage\n\n本轮 local mindmap clean smoke。\n", "utf8");
  const documentId = localMdDocumentId(relativePath);
  const browser = await chromium.launch({
    headless: process.env.HEADFUL !== "1",
    executablePath: CHROMIUM_EXECUTABLE_PATH,
  });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 960 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": ACTOR_ID,
      "x-mnote-actor-type": "user",
      "cache-control": "no-store",
    },
  });
  const page = await context.newPage();
  const consoleMessages = [];
  const networkRecords = [];
  page.on("console", (message) => {
    if (["error", "warning"].includes(message.type()) || /mindmap|local-folder|502|403|500/i.test(message.text())) {
      consoleMessages.push({ type: message.type(), text: message.text() });
    }
  });
  page.on("response", (response) => {
    const url = response.url();
    if (/\/api\/mindmap\/|\/api\/page-body\/write|\/api\/tree\/projections\/file|\/api\/local-folder/.test(url)) {
      networkRecords.push({ status: response.status(), method: response.request().method(), url });
    }
  });

  const result = {
    ok: false,
    baseUrl: BASE_URL,
    root,
    relativePath,
    documentId,
    mindmapId: "",
    screenshots: [],
    consoleMessages,
    networkRecords,
    diskBefore: [],
    diskAfterInsert: [],
    diskAfterRefresh: [],
    samples: [],
    markdown: "",
    saveAfterInsert: null,
    saveAfterCommand: null,
    markdownMissingMindmapReferenceAfterInsert: false,
    refreshSkippedBecauseMarkdownNotSaved: false,
    commandResponseSummary: null,
  };

  try {
    await openDocument(page, root, relativePath);
    result.screenshots.push(await screenshot(page, "01-open-clean-page"));
    await insertMindmapThroughSlash(page);
    result.mindmapId = await waitForMindmapId(page);
    result.screenshots.push(await screenshot(page, "02-after-insert-mindmap"));
    await page.waitForFunction(
      ({ expected }) => {
        const tree = document.getElementById("sidebar-file-tree-root");
        return (tree?.textContent || "").includes(expected);
      },
      { expected: result.mindmapId },
      { timeout: UI_TIMEOUT_MS },
    );
    result.saveAfterInsert = await waitForStableEditorSave(page, networkRecords, "after-insert");
    result.slashMenuAfterMindmap = await assertSlashMenuAnchorsAfterMindmap(page);

    result.diskAfterInsert = fs.readdirSync(pageDir).sort();
    assert(result.diskAfterInsert.includes("CleanPage.md"), `页面 Markdown 应存在: ${result.diskAfterInsert.join(",")}`);
    assert(result.diskAfterInsert.includes(result.mindmapId), `mindmap 应直接出现在页面文件夹下: ${result.diskAfterInsert.join(",")}`);
    assert(!fs.existsSync(path.join(root, result.mindmapId)), "root 同级不应残留 mindmap 文件");
    assert(!fs.existsSync(path.join(pageDir, "assets", result.mindmapId)), "assets 下不应残留 mindmap 文件");

    result.markdown = fs.readFileSync(markdownPath, "utf8");
    result.markdownMissingMindmapReferenceAfterInsert = !result.markdown.includes(`](${result.mindmapId})`);

    result.samples = await sampleFileTree(page, result.mindmapId, 4_000);
    result.commandResponseSummary = await postMindmapCommand(page, documentId, result.mindmapId);
    result.saveAfterCommand = await waitForStableEditorSave(page, networkRecords, "after-command");
    result.samples = result.samples.concat(await sampleFileTree(page, result.mindmapId, 4_000));
    result.screenshots.push(await screenshot(page, "03-after-command-apply"));

    if (result.markdownMissingMindmapReferenceAfterInsert) {
      result.refreshSkippedBecauseMarkdownNotSaved = true;
    } else {
      await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
      await page.locator('[data-testid="mnote-mindmap-editor-root"]').first().waitFor({
        state: "visible",
        timeout: UI_TIMEOUT_MS,
      });
      const afterRefresh = await readState(page);
      assert.equal(afterRefresh.mindmapId, result.mindmapId, `刷新后 mindmapId 应保持不变: ${JSON.stringify(afterRefresh)}`);
      assert(
        afterRefresh.mindmapRows.filter((row) => rowMatchesMindmap(row, result.mindmapId)).length === 1,
        `刷新后文件树应只有本轮 mindmap 一行: ${JSON.stringify(afterRefresh.mindmapRows)}`,
      );
      assert(
        !afterRefresh.mindmapRows.some((row) => row.assetId === "mindmap" || row.title.includes("思维导图.json")),
        `刷新后不应出现退化 mindmap 行: ${JSON.stringify(afterRefresh.mindmapRows)}`,
      );
      result.diskAfterRefresh = fs.readdirSync(pageDir).sort();
      result.screenshots.push(await screenshot(page, "04-after-refresh"));
    }

    const blockingNetworkErrors = networkRecords.filter((record) => {
      if (record.status < 400) return false;
      return !record.url.includes("/api/local-folder/events");
    });
    assert(
      blockingNetworkErrors.length === 0,
      `mindmap smoke 不应出现阻断性 4xx/5xx API 响应: ${JSON.stringify(blockingNetworkErrors)}`,
    );
    result.ok = true;
  } catch (error) {
    result.error = error && error.stack ? error.stack : String(error);
    try {
      result.screenshots.push(await screenshot(page, "99-failure"));
    } catch (_) {
      // 失败截图不可用时只保留错误文本。
    }
    throw error;
  } finally {
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ...result, resultPath: RESULT_PATH }, null, 2)}\n`, "utf8");
    await browser.close().catch(() => {});
  }

  console.log(`task455 local folder mindmap clean smoke passed: ${RESULT_PATH}`);
}

main().catch((error) => {
  console.error(error && error.stack ? error.stack : error);
  process.exit(1);
});
