#!/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", "task488-local-attachment-link-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}:task488`,
      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, fileName, content) {
  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({
    name: fileName,
    mimeType: "text/markdown",
    buffer: Buffer.from(content, "utf8"),
  });
  await page.waitForFunction(
    (name) => {
      const link = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a');
      return link instanceof HTMLAnchorElement
        && (link.textContent || "").includes(name)
        && (link.getAttribute("href") || "").includes("/api/local-folder/files/open");
    },
    fileName,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function selectAttachmentLinkText(page, fileName) {
  await page.evaluate((name) => {
    const editorElement = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
    const editor = editorElement?.editor;
    if (!editor || !editor.state || !editor.commands) throw new Error("editor_unavailable");
    let match = null;
    editor.state.doc.descendants((node, pos) => {
      if (match || !node || !node.isText) return;
      const text = node.text || "";
      const offset = text.indexOf(name);
      if (offset < 0) return;
      const hasAttachmentLink = Array.isArray(node.marks) && node.marks.some((mark) => {
        const href = mark && mark.attrs ? String(mark.attrs.href || "") : "";
        return mark.type && mark.type.name === "link" && href.includes("/api/local-folder/files/open");
      });
      if (!hasAttachmentLink) return;
      match = { from: pos + offset, to: pos + offset + name.length };
    });
    if (!match) throw new Error("attachment_link_text_range_missing");
    editor.commands.focus();
    editor.commands.setTextSelection(match);
  }, fileName);
}

async function editorDiagnostics(page) {
  return await page.evaluate(() => {
    const editorElement = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
    const editor = editorElement?.editor;
    const feedback = document.querySelector("#command-feedback")?.textContent || "";
    if (!editor || !editor.state) {
      return { feedback, editorReady: false };
    }
    return {
      feedback,
      editorReady: true,
      selection: {
        from: editor.state.selection.from,
        to: editor.state.selection.to,
        empty: editor.state.selection.empty,
      },
      linkAttributes: typeof editor.getAttributes === "function" ? editor.getAttributes("link") : null,
      windowSelection: String(window.getSelection?.() || ""),
      canUndo: typeof editor.can === "function" ? editor.can().undo() : null,
    };
  });
}

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 () => {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task488-"));
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.writeFileSync(path.join(root, "UndoLink.md"), "# Undo Link\n\n正文\n", "utf8");

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

  try {
    await quickLogin(page);
    await openDocument(page, root, "UndoLink.md");
    await uploadAttachmentViaSlash(page, fileName, "# 附件\n");
    result.states.push({ step: "uploaded", text: await editorText(page) });
    await page.waitForTimeout(700);

    await selectAttachmentLinkText(page, fileName);
    result.states.push({ step: "selected", diagnostics: await editorDiagnostics(page) });
    await page.keyboard.press("Delete");
    await waitForEditorText(page, "(text, name) => !text.includes(name)", fileName);
    result.states.push({ step: "deleted", text: await editorText(page), diagnostics: await editorDiagnostics(page) });

    await page.keyboard.press("Control+Z");
    try {
      await waitForEditorText(page, "(text, name) => text.includes(name)", fileName);
    } catch (error) {
      const afterKeyboardUndo = await editorText(page);
      const directUndo = await page.evaluate(() => {
        const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.editor;
        if (!editor || !editor.commands || typeof editor.commands.undo !== "function") {
          return { ok: false, reason: "editor_undo_unavailable" };
        }
        return { ok: editor.commands.undo() === true };
      });
      const afterDirectUndo = await editorText(page);
      result.states.push({ step: "keyboard-undo-timeout", text: afterKeyboardUndo, directUndo, afterDirectUndo });
      throw error;
    }
    result.states.push({ step: "undo", text: await editorText(page) });

    await page.keyboard.press("Control+Y");
    await waitForEditorText(page, "(text, name) => !text.includes(name)", fileName);
    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 === "uploaded").text.includes(fileName), "上传后应插入附件链接");
    assert(!result.states.find((state) => state.step === "deleted").text.includes(fileName), "Delete 后应删除附件链接");
    assert(result.states.find((state) => state.step === "undo").text.includes(fileName), "Ctrl+Z 应恢复附件链接");
    assert(!result.states.find((state) => state.step === "redo").text.includes(fileName), "Ctrl+Y 应再次删除附件链接");

    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
    await browser.close();
    console.log(`task488 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, root, error: error && error.stack ? error.stack : String(error), states: result.states }, null, 2)}\n`,
      "utf8",
    );
    await browser.close().catch(() => undefined);
    console.error(`task488 failed: ${RESULT_PATH}`);
    process.exit(1);
  }
})();
