#!/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 PPTX_PATH = process.env.MNOTE_TASK503_PPTX_PATH
  || "/home/lix/Downloads/1768096586803-672be7a7-5cb3-454d-9b1b-6230f86ba392.pptx";
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task503-local-pptx-upload-filetree-open-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

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

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

function workspaceId(ownerId) {
  return `local-ws:${ownerId}:task503`;
}

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, ownerId) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: workspaceId(ownerId),
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

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 }).catch(() => undefined);
  }
}

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 uploadAttachmentViaSlash(page, filePath) {
  const editor = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first();
  await editor.click({ timeout: UI_TIMEOUT_MS });
  await page.keyboard.press("End").catch(() => undefined);
  await page.keyboard.type("/");
  const item = page.locator('.document-pane[data-pane-role="primary"] [data-testid="slash-item-upload-attachment"]').first();
  await item.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const [fileChooser] = await Promise.all([
    page.waitForEvent("filechooser", { timeout: UI_TIMEOUT_MS }),
    item.click({ timeout: UI_TIMEOUT_MS }),
  ]);
  await fileChooser.setFiles(filePath);
}

async function waitForEditorLinks(page, expectedCount) {
  await page.waitForFunction(
    ({ count }) => {
      const links = Array.from(document.querySelectorAll('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a'));
      return links.filter((link) => /\.pptx(?:\?|$)/i.test(link.textContent || "")).length >= count;
    },
    { count: expectedCount },
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate(() => Array.from(document.querySelectorAll('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a'))
    .filter((link) => /\.pptx(?:\?|$)/i.test(link.textContent || ""))
    .map((link) => ({
      text: link.textContent || "",
      href: link.getAttribute("href") || "",
      assetId: link.getAttribute("data-asset-id") || "",
      className: link.getAttribute("class") || "",
    })));
}

function assertStandardMarkdownAttachmentLinks(links, label) {
  assert(links.length > 0, `${label}: 应存在编辑器附件链接`);
  for (const link of links) {
    assert(!link.href.includes("/office-preview"), `${label}: 附件 href 不应持久写入 /office-preview: ${JSON.stringify(link)}`);
    assert(!link.href.includes("/api/local-folder/files/open"), `${label}: 附件 href 不应持久写入本地 open API: ${JSON.stringify(link)}`);
    assert(/^(?:\.{1,2}\/|[^:/?#]+(?:\/|$))/.test(link.href), `${label}: 附件 href 应为 Markdown 相对链接: ${JSON.stringify(link)}`);
  }
}

function assertMarkdownSourceUsesStandardAttachmentLinks(root, relativePath, label) {
  const markdown = fs.readFileSync(path.join(root, relativePath), "utf8");
  assert(!markdown.includes("/office-preview"), `${label}: Markdown 原文不应包含 /office-preview\n${markdown}`);
  assert(!markdown.includes("/api/local-folder/files/open"), `${label}: Markdown 原文不应包含本地 open API\n${markdown}`);
  assert(/\[[^\]]+\.pptx\]\(\.\/[^)]+\.pptx\)/i.test(markdown), `${label}: Markdown 原文应包含标准相对 PPTX 链接\n${markdown}`);
  return markdown;
}

async function readPageAggregate(page) {
  return await page.evaluate(() => {
    const script = document.getElementById("__MNOTE_PAGE_AGGREGATE__");
    if (!script) return null;
    try {
      return JSON.parse(script.textContent || "null");
    } catch (_error) {
      return null;
    }
  });
}

async function assertAttachmentRefProjection(page, expectedCount, label) {
  const aggregate = await readPageAggregate(page);
  const refs = Array.isArray(aggregate?.body?.attachmentRefs) ? aggregate.body.attachmentRefs : [];
  assert(refs.length >= expectedCount, `${label}: attachmentRefs 数量不足: ${JSON.stringify(refs)}`);
  const pptxRefs = refs.filter((ref) => /\.pptx$/i.test(String(ref.rawHref || "")));
  assert(pptxRefs.length >= expectedCount, `${label}: attachmentRefs 应包含 PPTX: ${JSON.stringify(refs)}`);
  for (const ref of pptxRefs.slice(0, expectedCount)) {
    assert(/^\.\//.test(String(ref.rawHref || "")), `${label}: rawHref 应保持同目录 Markdown 相对链接: ${JSON.stringify(ref)}`);
    assert.equal(ref.kind, "pageLocal", `${label}: 同目录附件应为 pageLocal: ${JSON.stringify(ref)}`);
    assert.equal(ref.openKind, "office", `${label}: PPTX openKind 应为 office: ${JSON.stringify(ref)}`);
    assert.equal(ref.authorized, true, `${label}: 当前授权 root 内附件应 authorized=true: ${JSON.stringify(ref)}`);
  }
  return pptxRefs;
}

async function assertNoConflict(page, label) {
  await page.waitForTimeout(1500);
  const state = await page.evaluate(() => {
    const pane = document.querySelector('.document-pane[data-pane-role="primary"]');
    const runtimeRoot = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    return {
      status: runtimeRoot?.getAttribute("data-runtime-editor-status") || "",
      statusError: runtimeRoot?.getAttribute("data-runtime-editor-error") || "",
      conflictVisible: Boolean(pane?.querySelector('[data-testid="mnote-editor-conflict-panel"]')),
      lastSaveError: document.documentElement.getAttribute("data-mnote-last-upload-save-error") || "",
    };
  });
  assert.notEqual(state.status, "external-change-conflict", `${label}: 不应进入文件冲突态: ${JSON.stringify(state)}`);
  assert.equal(state.conflictVisible, false, `${label}: 不应显示文件冲突面板: ${JSON.stringify(state)}`);
  assert.equal(state.lastSaveError, "", `${label}: 上传保存不应失败: ${JSON.stringify(state)}`);
  return state;
}

async function setPptPageWidth(context, root, relativePath, mode) {
  const response = await context.request.fetch(`${BASE_URL}/api/ui/preferences`, {
    method: "PUT",
    data: {
      documentId: localMdDocumentId(relativePath),
      workspaceId: workspaceId("mnote-e2e"),
      sourceKind: "local_folder",
      rootUri: fileUrl(root),
      updates: {
        "pageWidth.ppt": { mode, custom: null },
      },
    },
  });
  assert(response.ok(), `PPT 页面宽度偏好写入失败: ${response.status()} ${await response.text()}`);
}

async function waitForActivePptxResourceTabLayout(page, expectedMode) {
  await page.waitForFunction(
    ({ mode }) => {
      const shell = document.querySelector('.document-pane[data-pane-role="primary"] .document-shell');
      const panel = Array.from(document.querySelectorAll(".mnote-resource-tab-panel"))
        .find((node) => node instanceof HTMLElement && !node.hidden && node.getAttribute("data-resource-kind") === "office");
      const frame = panel?.querySelector("iframe.mnote-resource-tab-frame");
      const frameDocument = frame instanceof HTMLIFrameElement ? frame.contentDocument : null;
      return shell instanceof HTMLElement
        && shell.getAttribute("data-page-width-content-type") === "ppt"
        && shell.getAttribute("data-page-width-resolved-mode") === mode
        && frameDocument?.documentElement?.getAttribute("data-mnote-office-preview-status") === "完成"
        && frameDocument.documentElement.getAttribute("data-page-width-resolved-mode") === mode
        && frameDocument.querySelector(".mnote-office-pptx-stage");
    },
    { mode: expectedMode },
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate((mode) => {
    const rectOf = (node) => {
      if (!(node instanceof Element)) return null;
      const rect = node.getBoundingClientRect();
      return { left: rect.left, width: rect.width };
    };
    const shell = document.querySelector('.document-pane[data-pane-role="primary"] .document-shell');
    const panel = Array.from(document.querySelectorAll(".mnote-resource-tab-panel"))
      .find((node) => node instanceof HTMLElement && !node.hidden && node.getAttribute("data-resource-kind") === "office");
    const frame = panel?.querySelector("iframe.mnote-resource-tab-frame");
    const frameDocument = frame instanceof HTMLIFrameElement ? frame.contentDocument : null;
    const viewer = frameDocument?.querySelector("#mnote-office-viewer");
    const stage = frameDocument?.querySelector(".mnote-office-pptx-stage");
    const viewerRect = rectOf(viewer);
    const stageRect = rectOf(stage);
    return {
      expectedMode: mode,
      viewportWidth: window.innerWidth,
      shellMode: shell?.getAttribute("data-page-width-resolved-mode") || "",
      shellContentType: shell?.getAttribute("data-page-width-content-type") || "",
      documentMode: document.documentElement.getAttribute("data-page-width-resolved-mode") || "",
      activeResourceWidthType: document.documentElement.getAttribute("data-mnote-active-resource-width-type") || "",
      iframeMode: frameDocument?.documentElement?.getAttribute("data-page-width-resolved-mode") || "",
      shell: rectOf(shell),
      panel: rectOf(panel),
      frame: rectOf(frame),
      viewer: viewerRect,
      stage: stageRect,
    };
  }, expectedMode);
}

async function clickEditorPptxLink(page, context, titleContains) {
  await page.waitForFunction(
    (needle) => {
      return Array.from(document.querySelectorAll('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a'))
        .some((node) => {
          const rect = node.getBoundingClientRect();
          return (node.textContent || "").includes(needle) && rect.width > 0 && rect.height > 0;
        });
    },
    titleContains,
    { timeout: UI_TIMEOUT_MS },
  );
  const target = await page.evaluate((needle) => {
    const candidates = Array.from(document.querySelectorAll('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a'));
    for (let index = candidates.length - 1; index >= 0; index -= 1) {
      const node = candidates[index];
      const rect = node.getBoundingClientRect();
      if (!(node.textContent || "").includes(needle) || rect.width <= 0 || rect.height <= 0) continue;
      return {
        href: node instanceof HTMLAnchorElement ? node.href : "",
        rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
      };
    }
    return null;
  }, titleContains);
  assert(target?.href, `编辑器附件缺少 href: ${titleContains}`);
  assert(target?.rect, `编辑器附件链接不可见或无坐标: ${titleContains}`);
  await page.mouse.click(target.rect.x + target.rect.width / 2, target.rect.y + target.rect.height / 2);
  await page.waitForFunction(
    (needle) => {
      const activePanel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
      const activeFrame = activePanel?.querySelector?.('iframe.mnote-resource-tab-frame');
      const frameSrc = activeFrame instanceof HTMLIFrameElement ? activeFrame.getAttribute('src') || '' : '';
      return decodeURIComponent(frameSrc.replace(/\+/g, ' ')).includes(needle)
        || decodeURIComponent(location.href.replace(/\+/g, ' ')).includes(needle);
    },
    titleContains,
    { timeout: UI_TIMEOUT_MS },
  );
  await page.locator('.mnote-resource-tab-panel:not([hidden]) iframe.mnote-resource-tab-frame').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function activatePrimaryPageTab(page) {
  const pageTab = page.locator('[data-mnote-main-tab="page"][data-pane-role="primary"]').first();
  await pageTab.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await pageTab.click({ timeout: UI_TIMEOUT_MS });
  await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

function assertLocalUploadSaveVersions(result, expectedCount) {
  const saves = result.documentSaveRequests.filter((item) => item.editorSource === "local-upload-runtime");
  assert(
    saves.length >= expectedCount,
    `local-upload-runtime 保存次数不足: expected>=${expectedCount}, actual=${saves.length}`,
  );
  saves.slice(0, expectedCount).forEach((item, index) => {
    assert(
      item.expectedFileVersion,
      `第 ${index + 1} 次附件正文保存缺少 expectedFileVersion: ${JSON.stringify(item)}`,
    );
    assert(
      item.writeIntentId,
      `第 ${index + 1} 次附件正文保存缺少 writeIntentId: ${JSON.stringify(item)}`,
    );
    assert(
      item.saveOperationId,
      `第 ${index + 1} 次附件正文保存缺少 saveOperationId: ${JSON.stringify(item)}`,
    );
  });
}

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function typeLineAfterUpload(page, text) {
  const editor = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first();
  await editor.click({ timeout: UI_TIMEOUT_MS });
  await page.keyboard.press("End").catch(() => undefined);
  await page.keyboard.press("Enter");
  await page.keyboard.type(text);
}

async function waitForFileTreeAssetRows(page, expectedCount) {
  await page.waitForFunction(
    ({ count }) => {
      return Array.from(document.querySelectorAll('#sidebar-file-tree-root [data-testid="filetree-asset-row"]'))
        .filter((row) => /\.pptx/i.test(row.textContent || ""))
        .length >= count;
    },
    { count: expectedCount },
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate(() => Array.from(document.querySelectorAll('#sidebar-file-tree-root [data-testid="filetree-asset-row"]'))
    .filter((row) => /\.pptx/i.test(row.textContent || ""))
    .map((row) => ({
      title: row.textContent?.trim() || "",
      rowId: row.getAttribute("data-row-id") || "",
      assetId: row.getAttribute("data-asset-id") || "",
      localRelativePath: row.getAttribute("data-local-relative-path") || "",
      objectIdentity: row.getAttribute("data-object-identity") || "",
    })));
}

async function clickPptxFileTreeRow(page, titleContains) {
  const row = page.locator('#sidebar-file-tree-root [data-testid="filetree-asset-row"]', { hasText: titleContains }).last();
  await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await row.click({ timeout: UI_TIMEOUT_MS });
  await page.waitForFunction(
    (needle) => {
      const active = document.querySelector('[data-testid="document-resource-tab"][data-active="true"], [data-mnote-resource-tab][data-active="true"]');
      if (active instanceof HTMLElement && (active.textContent || "").includes(needle)) return true;
      return decodeURIComponent(location.href.replace(/\+/g, " ")).includes(needle);
    },
    titleContains,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function waitForLocalFile(filePath) {
  const startedAt = Date.now();
  while (Date.now() - startedAt < UI_TIMEOUT_MS) {
    if (fs.existsSync(filePath)) return;
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  assert(fs.existsSync(filePath), `文件应存在: ${filePath}`);
}

async function dispatchPptxDrop(page, filePath, targetText) {
  const buffer = fs.readFileSync(filePath);
  const base64 = buffer.toString("base64");
  const fileName = path.basename(filePath);
  const target = page.locator('#sidebar-file-tree-root .tree-row[data-row-kind="folder"]', { hasText: targetText }).first();
  await target.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await target.dispatchEvent("dragover", {
    dataTransfer: await page.evaluateHandle(({ name, payload }) => {
      const bytes = Uint8Array.from(atob(payload), (char) => char.charCodeAt(0));
      const transfer = new DataTransfer();
      transfer.items.add(new File([bytes], name, {
        type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      }));
      return transfer;
    }, { name: fileName, payload: base64 }),
  });
  await target.dispatchEvent("drop", {
    dataTransfer: await page.evaluateHandle(({ name, payload }) => {
      const bytes = Uint8Array.from(atob(payload), (char) => char.charCodeAt(0));
      const transfer = new DataTransfer();
      transfer.items.add(new File([bytes], name, {
        type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      }));
      return transfer;
    }, { name: fileName, payload: base64 }),
  });
}

async function main() {
  assert(fs.existsSync(PPTX_PATH), `测试 pptx 不存在: ${PPTX_PATH}`);
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task503-pptx-"));
  const relativePath = "README/README.md";
  const resourceDir = path.join(root, "README");
  const fileName = path.basename(PPTX_PATH);
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.mkdirSync(resourceDir, { recursive: true });
  fs.writeFileSync(path.join(root, relativePath), "# PPTX Upload\n\n正文\n", "utf8");

  const browser = await chromium.launch({
    headless: process.env.HEADFUL !== "1",
    executablePath: CHROMIUM_EXECUTABLE_PATH,
  });
  const context = await browser.newContext({
    viewport: { width: 1366, height: 900 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "mnote-e2e",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();
  const result = { root, fileName, states: [], console: [], pageErrors: [], documentSaveRequests: [] };
  page.on("console", (message) => result.console.push({ type: message.type(), text: message.text() }));
  page.on("pageerror", (error) => result.pageErrors.push(String(error && error.stack || error)));
  page.on("request", (request) => {
    try {
      const url = new URL(request.url());
      if (url.pathname !== "/api/documents/save" || request.method() !== "POST") return;
      const payload = JSON.parse(request.postData() || "{}");
      result.documentSaveRequests.push({
        editorSource: String(payload.editorSource || ""),
        documentId: String(payload.documentId || ""),
        expectedFileVersion: String(payload.expectedFileVersion || ""),
        writeIntentId: String(payload.writeIntentId || ""),
        saveOperationId: String(payload.saveOperationId || ""),
        blockCount: Number(payload.blockCount || 0),
      });
    } catch (_error) {
      // ignore diagnostics-only capture failures
    }
  });

  try {
    await quickLogin(page);
    await setPptPageWidth(context, root, relativePath, "full");
    await openDocument(page, root, relativePath);

    await uploadAttachmentViaSlash(page, PPTX_PATH);
    const firstLinks = await waitForEditorLinks(page, 1);
    assertStandardMarkdownAttachmentLinks(firstLinks, "first-editor-upload");
    const firstConflictState = await assertNoConflict(page, "first-editor-upload");
    assertLocalUploadSaveVersions(result, 1);
    const firstMarkdown = assertMarkdownSourceUsesStandardAttachmentLinks(root, relativePath, "first-editor-upload");
    result.states.push({ step: "first-editor-upload", links: firstLinks, conflictState: firstConflictState, markdown: firstMarkdown });
    await typeLineAfterUpload(page, "第一份附件后的正文");
    const afterFirstEditConflictState = await assertNoConflict(page, "after-first-upload-edit");
    result.states.push({ step: "after-first-upload-edit", conflictState: afterFirstEditConflictState });

    await uploadAttachmentViaSlash(page, PPTX_PATH);
    const secondLinks = await waitForEditorLinks(page, 2);
    assertStandardMarkdownAttachmentLinks(secondLinks, "second-editor-upload");
    const secondConflictState = await assertNoConflict(page, "second-editor-upload");
    assertLocalUploadSaveVersions(result, 2);
    const secondMarkdown = assertMarkdownSourceUsesStandardAttachmentLinks(root, relativePath, "second-editor-upload");
    await delay(1800);
    const editorRows = await waitForFileTreeAssetRows(page, 2);
    result.states.push({ step: "second-editor-upload", links: secondLinks, conflictState: secondConflictState, markdown: secondMarkdown, fileTreeRows: editorRows });
    assert(editorRows.every((row) => row.localRelativePath), `文件树上传行缺少本地路径: ${JSON.stringify(editorRows)}`);
    await openDocument(page, root, relativePath);
    assertStandardMarkdownAttachmentLinks(await waitForEditorLinks(page, 2), "reopen-editor-upload");
    const attachmentRefs = await assertAttachmentRefProjection(page, 2, "reopen-editor-upload");
    result.states.push({ step: "reopen-editor-upload", attachmentRefs });
    await clickEditorPptxLink(page, context, fileName);
    await activatePrimaryPageTab(page);
    await clickEditorPptxLink(page, context, fileName.replace(/\.pptx$/i, "-1.pptx"));
    await clickPptxFileTreeRow(page, fileName.replace(/\.pptx$/i, "-1.pptx"));
    const fullWidthLayout = await waitForActivePptxResourceTabLayout(page, "full");
    assert(fullWidthLayout.panel?.width >= fullWidthLayout.viewportWidth - 320, `PPT 资源 tab 面板应使用主编辑区宽度: ${JSON.stringify(fullWidthLayout)}`);
    assert(fullWidthLayout.frame?.width >= fullWidthLayout.viewportWidth - 320, `PPT 资源 tab iframe 应使用主编辑区宽度: ${JSON.stringify(fullWidthLayout)}`);
    result.states.push({ step: "pptx-resource-tab-full-width", layout: fullWidthLayout });

    await dispatchPptxDrop(page, PPTX_PATH, "README");
    const droppedFileName = fileName.replace(/\.pptx$/i, " 2.pptx");
    const droppedPath = path.join(resourceDir, droppedFileName);
    await page.waitForFunction(
      (targetPath) => document.documentElement.getAttribute("data-mnote-assets-local-applied") === "true" && targetPath,
      droppedPath,
      { timeout: UI_TIMEOUT_MS },
    ).catch(() => undefined);
    await waitForLocalFile(droppedPath);
    const finalRows = await waitForFileTreeAssetRows(page, 3);
    result.states.push({ step: "filetree-drop-upload", droppedPath, fileTreeRows: finalRows });
    await clickPptxFileTreeRow(page, droppedFileName);

    await page.screenshot({ path: path.join(OUTPUT_DIR, "success.png"), fullPage: false });
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
    console.log(JSON.stringify({ ok: true, resultPath: RESULT_PATH, root, fileName }, null, 2));
  } catch (error) {
    const diagnostics = await page.evaluate(() => ({
      url: location.href,
      lastUploadAssetId: document.documentElement.getAttribute("data-mnote-last-upload-asset-id") || "",
      lastUploadInserted: document.documentElement.getAttribute("data-mnote-last-upload-inserted") || "",
      assetsLocalApplied: document.documentElement.getAttribute("data-mnote-assets-local-applied") || "",
      filetreeRows: Array.from(document.querySelectorAll('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"]')).map((row) => ({
        text: row.textContent?.trim() || "",
        rowKind: row.getAttribute("data-row-kind") || "",
        rowId: row.getAttribute("data-row-id") || "",
        assetId: row.getAttribute("data-asset-id") || "",
        localRelativePath: row.getAttribute("data-local-relative-path") || "",
      })).slice(0, 80),
      editorLinks: Array.from(document.querySelectorAll('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a')).map((link) => ({
        text: link.textContent || "",
        href: link.getAttribute("href") || "",
        assetId: link.getAttribute("data-asset-id") || "",
        className: link.getAttribute("class") || "",
      })),
      documentSessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
        ? window.__mnoteDebugDocumentSessions.snapshot()
        : null,
      aggregate: (() => {
        try {
          const script = document.getElementById("__MNOTE_PAGE_AGGREGATE__");
          return script ? JSON.parse(script.textContent || "null") : null;
        } catch (_error) {
          return null;
        }
      })(),
    })).catch((err) => ({ diagnosticsError: String(err) }));
    await page.screenshot({ path: path.join(OUTPUT_DIR, "failure.png"), fullPage: true }).catch(() => undefined);
    fs.writeFileSync(
      RESULT_PATH,
      `${JSON.stringify({ ok: false, ...result, diagnostics, error: String(error && error.stack || error) }, null, 2)}\n`,
      "utf8",
    );
    console.error(JSON.stringify({ ok: false, resultPath: RESULT_PATH, root, diagnostics, error: String(error && error.stack || error) }, null, 2));
    process.exitCode = 1;
  } finally {
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

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