#!/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 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}:task459`,
      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 activatePrimaryPageTab(page) {
  const pageTab = page.locator('[data-mnote-main-tab="page"][data-pane-role="primary"]').first();
  if (await pageTab.count()) {
    await pageTab.click({ timeout: UI_TIMEOUT_MS }).catch(() => undefined);
  }
  await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function uploadAttachmentViaPrimarySlash(page, fileName, markdown) {
  await activatePrimaryPageTab(page);
  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(markdown, "utf8"),
  });
  await page.waitForFunction(
    (name) => {
      const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
      return editor instanceof HTMLElement && (editor.textContent || "").includes(name);
    },
    fileName,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function clickPrimaryAttachmentAndExpectTab(page, fileName) {
  await activatePrimaryPageTab(page);
  const link = page
    .locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a[href*="/api/local-folder/files/open"]', {
      hasText: fileName,
    })
    .first();
  await link.click({ timeout: UI_TIMEOUT_MS });
  await page.locator('.mnote-main-tab.is-active[data-pane-role="primary"][data-mnote-tab-kind="markdown"]', {
    hasText: fileName,
  }).waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task459-md-attachment-"));
  const relativePath = "README.md";
  const documentId = localMdDocumentId(relativePath);
  writeWorkspaceManifest(root, "user_real");
  fs.mkdirSync(path.join(root, "README"), { recursive: true });
  fs.writeFileSync(
    path.join(root, relativePath),
    [
      "---",
      "title: MD Attachment",
      "---",
      "",
      "# MD Attachment",
      "",
      "[resource-note.md](README/resource-note.md)",
      "",
    ].join("\n"),
    "utf8",
  );
  fs.writeFileSync(path.join(root, "README", "resource-note.md"), "# Resource Note\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: 1360, height: 900 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();
  const popups = [];
  page.on("popup", (popup) => popups.push(popup));
  try {
    await quickLogin(page);
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const link = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a[href*="/api/local-folder/files/open"][href*="README%2Fresource-note.md"]').first();
    await link.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const node = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a[href*="/api/local-folder/files/open"][href*="README%2Fresource-note.md"]');
      return node instanceof HTMLAnchorElement
        && (node.classList.contains("mnote-uploaded-attachment-row") || getComputedStyle(node).display === "inline-flex");
    }, null, { timeout: UI_TIMEOUT_MS });

    await link.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-resource-tab-host"]:not([hidden])').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const resourceEditor = page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first();
    await resourceEditor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const resourceText = await resourceEditor.innerText({ timeout: UI_TIMEOUT_MS });
    assert(resourceText.includes("资源正文"), `MD 附件应在资源 tab 中用 tiptap 打开：${resourceText}`);
    assert.equal(popups.length, 0, `点击 MD 附件不应打开浏览器新窗口，实际 popup=${popups.length}`);

    const pageTab = page.locator('[data-mnote-main-tab="page"]').first();
    await pageTab.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const pagePanel = document.querySelector("[data-mnote-page-tab-panel]");
      const resourceHost = document.querySelector("[data-mnote-resource-tab-host]");
      const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
      return pagePanel && !pagePanel.hidden
        && resourceHost && resourceHost.hidden
        && pageTab && pageTab.classList.contains("is-active");
    }, null, { timeout: UI_TIMEOUT_MS });

    const pageText = await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().innerText({
      timeout: UI_TIMEOUT_MS,
    });
    assert(pageText.includes("resource-note.md"), "主页面正文应保持原附件链接");

    const resourceTab = page.locator('.mnote-main-tab[data-mnote-tab-kind="markdown"]').first();
    await resourceTab.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await resourceEditor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    await uploadAttachmentViaPrimarySlash(page, "uploaded-one.md", "# Uploaded One\n\n第一个上传附件\n");
    await clickPrimaryAttachmentAndExpectTab(page, "uploaded-one.md");
    await uploadAttachmentViaPrimarySlash(page, "uploaded-two.md", "# Uploaded Two\n\n第二个上传附件\n");
    await clickPrimaryAttachmentAndExpectTab(page, "uploaded-one.md");
    await clickPrimaryAttachmentAndExpectTab(page, "uploaded-two.md");
    assert.equal(popups.length, 0, `连续上传两个 MD 附件后点击不应打开浏览器新窗口，实际 popup=${popups.length}`);

    console.log(JSON.stringify({ ok: true, root, documentId, popups: popups.length }, null, 2));
  } 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);
});
