#!/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 OUTPUT_DIR = path.join(process.cwd(), "tmp", "task489-block-menu-delete-undo-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 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: `local-ws:${ownerId}:task489`,
      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 editorText(page) {
  return await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().evaluate((node) =>
    node instanceof HTMLElement ? node.innerText : "",
  );
}

async function waitForEditorText(page, predicateSource, arg) {
  await page.waitForFunction(
    ({ predicateSource, arg }) => {
      const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
      const text = editor instanceof HTMLElement ? editor.innerText : "";
      return Function("text", "arg", `return (${predicateSource})(text, arg);`)(text, arg);
    },
    { predicateSource, arg },
    { timeout: UI_TIMEOUT_MS },
  );
}

async function deleteBlockByVisibleText(page, text) {
  const block = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror > *', {
    hasText: text,
  }).first();
  await block.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const box = await block.boundingBox();
  assert(box, `找不到块可点击区域: ${text}`);
  await page.mouse.move(box.x + Math.min(20, box.width / 2), box.y + Math.min(12, box.height / 2), { steps: 8 });
  const trigger = page.locator('[data-testid="block-drag-handle-trigger"]').first();
  await trigger.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await trigger.click({ timeout: UI_TIMEOUT_MS });
  const menu = page.locator('[data-testid="block-drag-menu"]').first();
  await menu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="block-drag-menu-item-delete"]').first().click({ timeout: UI_TIMEOUT_MS });
}

(async () => {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task489-"));
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.writeFileSync(
    path.join(root, "BlockUndo.md"),
    ["# Block Undo", "", "Alpha block", "", "Beta block", "", "Gamma block", ""].join("\n"),
    "utf8",
  );

  const browser = await chromium.launch({
    headless: true,
    executablePath: CHROMIUM_EXECUTABLE_PATH,
  });
  const page = await browser.newPage({ viewport: { width: 1366, height: 900 } });
  const result = { root, states: [] };

  try {
    await quickLogin(page);
    await openDocument(page, root, "BlockUndo.md");
    await waitForEditorText(page, "(text, expected) => text.includes(expected)", "Beta block");
    result.states.push({ step: "opened", text: await editorText(page) });

    await deleteBlockByVisibleText(page, "Beta block");
    await waitForEditorText(page, "(text, expected) => !text.includes(expected)", "Beta block");
    result.states.push({ step: "deleted", text: await editorText(page) });

    await page.keyboard.press("Control+Z");
    await waitForEditorText(page, "(text, expected) => text.includes(expected)", "Beta block");
    result.states.push({ step: "undo", text: await editorText(page) });

    await page.keyboard.press("Control+Y");
    await waitForEditorText(page, "(text, expected) => !text.includes(expected)", "Beta block");
    result.states.push({ step: "redo", text: await editorText(page) });

    await page.screenshot({
      path: path.join(OUTPUT_DIR, "after-redo.png"),
      fullPage: true,
    });

    assert(result.states.find((state) => state.step === "opened").text.includes("Beta block"), "初始文档应包含目标块");
    assert(!result.states.find((state) => state.step === "deleted").text.includes("Beta block"), "块菜单删除后应移除目标块");
    assert(result.states.find((state) => state.step === "undo").text.includes("Beta block"), "Ctrl+Z 应恢复目标块");
    assert(!result.states.find((state) => state.step === "redo").text.includes("Beta block"), "Ctrl+Y 应再次删除目标块");

    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
    await browser.close();
    console.log(`task489 ok: ${RESULT_PATH}`);
  } catch (error) {
    await page.screenshot({
      path: path.join(OUTPUT_DIR, "failure.png"),
      fullPage: true,
    }).catch(() => undefined);
    fs.writeFileSync(
      RESULT_PATH,
      `${JSON.stringify({ ok: false, error: error.message, stack: error.stack, ...result }, null, 2)}\n`,
      "utf8",
    );
    await browser.close().catch(() => undefined);
    console.error(`task489 failed: ${RESULT_PATH}`);
    console.error(error);
    process.exit(1);
  }
})();
