#!/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}:task461`,
      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 });
  }
}

async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) {
  return await page.evaluate(
    async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => {
      const form = new FormData();
      form.append("rootUri", rootUri);
      form.append("documentId", documentId);
      form.append("kind", kind);
      form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType }));
      const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form });
      const payload = await response.json().catch(() => null);
      if (!response.ok || !payload || payload.ok !== true) {
        throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`);
      }
      return payload.asset;
    },
    { rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind },
  );
}

/** Open a resource tab via `tree.asset.open` event. */
async function openResourceTab(page, asset, documentId) {
  return await page.evaluate(({ asset, documentId }) => {
    window.dispatchEvent(new CustomEvent("tree.asset.open", {
      detail: {
        assetId: asset.id,
        documentId,
        title: asset.file_name || "resource",
        assetType: asset.asset_type || "attachment",
      },
    }));
  }, { asset, documentId });
}

/** Query badge kind for the active tab. */
async function activeTabBadgeKind(page) {
  return await page.evaluate(() => {
    const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
    if (!tab) return "";
    const badge = tab.querySelector(".mnote-main-tab-badge");
    return {
      badgeKind: tab.getAttribute("data-mnote-tab-badge-kind") || "",
      badgeColor: badge ? getComputedStyle(badge).backgroundColor : "",
    };
  });
}

/** Check active tab's content panel has an iframe/image/editor. */
async function activeTabContentIsInline(page) {
  return await page.evaluate(() => {
    const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
    if (!panel) return { inline: false, reason: "no_active_panel" };
    // Check for various inline content types
    const iframe = panel.querySelector('iframe.mnote-resource-tab-frame');
    if (iframe) return { inline: true, contentType: "iframe", src: iframe.getAttribute("src") || "" };
    const img = panel.querySelector('img.mnote-resource-tab-image');
    if (img) return { inline: true, contentType: "img", src: img.getAttribute("src") || "" };
    const editor = panel.querySelector('.ProseMirror[contenteditable="true"]');
    if (editor) return { inline: true, contentType: "editor" };
    const errorDiv = panel.querySelector('[data-resource-tab-error="true"]');
    if (errorDiv) return { inline: true, contentType: "error_fallback" };
    return { inline: false, reason: "no_content_found" };
  });
}

async function main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task461-resource-kind-"));
  const relativePath = "README.md";
  const documentId = localMdDocumentId(relativePath);
  writeWorkspaceManifest(root, "user_real");
  fs.writeFileSync(path.join(root, relativePath), "# Page\n\n正文\n", "utf8");

  const browser = await chromium.launch({
    headless: true,
    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();

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

    // Upload a variety of resource types
    const assets = {};
    const resourceTypes = [
      { key: "markdown", fileName: "doc.md", mimeType: "text/markdown", bytes: Buffer.from("# Doc\n", "utf8"), expectKind: "markdown" },
      { key: "txt", fileName: "notes.txt", mimeType: "text/plain", bytes: Buffer.from("text content\n", "utf8"), expectKind: "text" },
      { key: "json", fileName: "data.json", mimeType: "application/json", bytes: Buffer.from('{"key":"value"}', "utf8"), expectKind: "code" },
      { key: "ts_code", fileName: "script.ts", mimeType: "text/typescript", bytes: Buffer.from("const x = 1;\n", "utf8"), expectKind: "code" },
      { key: "image", fileName: "photo.png", mimeType: "image/png", bytes: Buffer.from("fake-png-data", "utf8"), expectKind: "image" },
    ];

    for (const rt of resourceTypes) {
      const asset = await uploadLocalAsset(page, root, documentId, rt.fileName, rt.mimeType, rt.bytes, "attachment");
      assets[rt.key] = { ...asset, expectKind: rt.expectKind };
    }

    // Reload to pick up assets
    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,
    });

    // ======== Test: resource kind badge matrix ========
    for (const [key, asset] of Object.entries(assets)) {
      console.log(`Test: ${key} (${asset.file_name}) → expect kind=${asset.expectKind}`);

      await openResourceTab(page, asset, documentId);
      await page.waitForTimeout(500);

      const badge = await activeTabBadgeKind(page);
      assert.ok(badge.badgeKind, `${key}: active tab should have badge kind, got ${JSON.stringify(badge)}`);
      console.log(`  badgeKind: ${badge.badgeKind}, color: ${badge.badgeColor}`);

      // Check content is inline (not a new window)
      const contentInfo = await activeTabContentIsInline(page);
      assert.ok(contentInfo.inline, `${key}: content should render inline, got ${JSON.stringify(contentInfo)}`);
      console.log(`  content: ${contentInfo.contentType} ${contentInfo.src || ""}`);
    }

    // ======== Test: PDF badge ========
    console.log("Test: PDF badge should be independent (not 'ppt')");
    const pdfAsset = await uploadLocalAsset(
      page, root, documentId,
      "manual.pdf", "application/pdf",
      Buffer.from("%PDF-1.4 fake pdf\n", "utf8"),
      "attachment",
    );
    // Reload again
    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,
    });

    await openResourceTab(page, pdfAsset, documentId);
    await page.waitForTimeout(500);
    const pdfBadge = await activeTabBadgeKind(page);
    console.log(`  PDF badge: ${JSON.stringify(pdfBadge)}`);
    assert.equal(pdfBadge.badgeKind, "pdf", `PDF tab should have badgeKind "pdf", got "${pdfBadge.badgeKind}"`);
    assert.ok(pdfBadge.badgeColor, "PDF badge should have a color");

    // ======== Test: Unknown file fallback shouldn't break page tab ========
    console.log("Test: unknown file fallback should not break page tab");
    const pageTabActive = await page.evaluate(() => {
      const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
      return pageTab?.classList.contains("is-active") || false;
    });
    // Should be false since we just opened a PDF
    console.log(`  page tab active after PDF open: ${pageTabActive}`);

    // Close the PDF tab
    await page.evaluate(() => {
      const pdfTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
      const closeBtn = pdfTab?.querySelector('.mnote-main-tab-close');
      if (closeBtn instanceof HTMLElement) closeBtn.click();
    });
    await page.waitForTimeout(300);

    const pageTabActiveAfter = await page.evaluate(() => {
      const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
      return pageTab?.classList.contains("is-active") || false;
    });
    assert.ok(pageTabActiveAfter, "after closing resource tab, page tab should be active");

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