#!/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", "task491-local-md-attachment-icon-refresh-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}:task491`,
      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 installChangeEventProbe(page) {
  await page.evaluate(() => {
    window.__task491ChangeEvents = [];
    const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    if (!(root instanceof HTMLElement)) throw new Error("runtime_root_missing");
    root.addEventListener("mnote:leptos-tiptap-spike:change", (event) => {
      const payload = event.detail && event.detail.payload ? event.detail.payload : event.detail;
      window.__task491ChangeEvents.push({
        at: Date.now(),
        hasPayload: Boolean(event.detail && event.detail.payload),
        documentId: payload && payload.documentId,
        contentText: JSON.stringify(payload && payload.content || {}).slice(0, 500),
        text: document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.innerText || "",
      });
    });
  });
}

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"),
  });
}

async function waitForMdAttachmentClass(page, fileName) {
  await page.waitForFunction(
    (name) => {
      const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
      const links = Array.from(editor?.querySelectorAll('a[href*="/api/local-folder/files/open"]') || []);
      const link = links.find((node) => node instanceof HTMLAnchorElement && (node.textContent || "").includes(name));
      return link instanceof HTMLAnchorElement && link.classList.contains("mnote-uploaded-attachment-code");
    },
    fileName,
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate((name) => {
    const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
    const links = Array.from(editor?.querySelectorAll('a[href*="/api/local-folder/files/open"]') || []);
    const link = links.find((node) => node instanceof HTMLAnchorElement && (node.textContent || "").includes(name));
    if (!(link instanceof HTMLAnchorElement)) return null;
    return {
      href: link.getAttribute("href") || "",
      className: link.getAttribute("class") || "",
      assetId: link.getAttribute("data-asset-id") || "",
      text: link.textContent || "",
    };
  }, fileName);
}

async function waitForFileContent(filePath, predicate, timeoutMs) {
  const startedAt = Date.now();
  let lastContent = "";
  while (Date.now() - startedAt < timeoutMs) {
    if (fs.existsSync(filePath)) {
      lastContent = fs.readFileSync(filePath, "utf8");
      if (predicate(lastContent)) return lastContent;
    }
    await new Promise((resolve) => setTimeout(resolve, 150));
  }
  throw new Error(`文件内容未达到预期: ${filePath}; lastContent=${JSON.stringify(lastContent)}`);
}

async function changeEventProbe(page) {
  return await page.evaluate(() => window.__task491ChangeEvents || []).catch(() => []);
}

(async () => {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task491-"));
  const relativePath = "README.md";
  const resourceDir = path.join(root, "README");
  const fileName = "uploaded-one.md";
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.mkdirSync(resourceDir, { recursive: true });
  fs.writeFileSync(path.join(root, relativePath), "# Attachment Icon\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: [] };
  const saveResponses = [];
  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("response", async (response) => {
    if (!response.url().includes("/api/documents/save")) return;
    saveResponses.push({
      status: response.status(),
      payload: await response.json().catch(() => null),
    });
  });

  try {
    await quickLogin(page);
    await openDocument(page, root, relativePath);
    await installChangeEventProbe(page);
    await uploadAttachmentViaSlash(page, fileName, "# Uploaded One\n\n第一个上传附件\n");
    const beforeReload = await waitForMdAttachmentClass(page, fileName);
    result.states.push({ step: "before-reload", link: beforeReload, changeEvents: await changeEventProbe(page), saveResponses });

    const expectedPath = path.join(resourceDir, fileName);
    assert(fs.existsSync(expectedPath), `上传后的 md 附件应落盘到页面资源目录: ${expectedPath}`);
    const savedMarkdown = await waitForFileContent(
      path.join(root, relativePath),
      (content) => content.includes(fileName) && content.includes("README/uploaded-one.md"),
      UI_TIMEOUT_MS,
    );
    result.states.push({ step: "saved-markdown", savedMarkdown });

    await page.reload({ 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 afterReload = await waitForMdAttachmentClass(page, fileName);
    result.states.push({ step: "after-reload", link: afterReload });

    assert(beforeReload.className.includes("mnote-uploaded-attachment-code"), "刷新前 md 附件应使用 code 图标 class");
    assert(afterReload.className.includes("mnote-uploaded-attachment-code"), "刷新后 md 附件应保留 code 图标 class");
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
    console.log(JSON.stringify({ ok: true, resultPath: RESULT_PATH, root, beforeReload, afterReload }, null, 2));
  } catch (error) {
    const diagnostics = await page.evaluate(() => {
      const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
      const status = document.querySelector('[data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "";
      const statusError = document.querySelector('[data-runtime-editor-error]')?.getAttribute('data-runtime-editor-error') || "";
      return {
        url: location.href,
        status,
        statusError,
        editorText: editor instanceof HTMLElement ? editor.innerText : "",
        links: Array.from(editor?.querySelectorAll("a") || []).map((node) => ({
          href: node.getAttribute("href") || "",
          className: node.getAttribute("class") || "",
          text: node.textContent || "",
        })),
      };
    }).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, root, fileName, states: result.states, saveResponses, diagnostics, console: result.console, pageErrors: result.pageErrors, 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 browser.close().catch(() => undefined);
  }
})();
