#!/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}:task463`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

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

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 main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task463-onlyoffice-resolver-"));
  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 Office files
    const officeAssets = {};
    
    // docx
    officeAssets.docx = await uploadLocalAsset(
      page, root, documentId,
      "report.docx",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      Buffer.from("task463 docx probe", "utf8"),
      "attachment",
    );

    // pptx
    officeAssets.pptx = await uploadLocalAsset(
      page, root, documentId,
      "slides.pptx",
      "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      Buffer.from("task463 pptx probe", "utf8"),
      "attachment",
    );

    // xlsx
    officeAssets.xlsx = await uploadLocalAsset(
      page, root, documentId,
      "data.xlsx",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      Buffer.from("task463 xlsx probe", "utf8"),
      "attachment",
    );

    // 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 1: docx opens in main editor tab with /onlyoffice iframe ========
    console.log("Test 1: docx opens in main editor tab with /onlyoffice iframe");
    await page.evaluate(({ asset, documentId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: asset.id,
          documentId,
          title: asset.file_name || "report.docx",
          assetType: asset.asset_type || "attachment",
        },
      }));
    }, { asset: officeAssets.docx, documentId });
    
    // Wait for office tab to become active
    await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    const officeTabInfo = await page.evaluate(() => {
      const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
      const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
      const iframe = panel?.querySelector('iframe.mnote-resource-tab-frame');
      return {
        badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
        iframeSrc: iframe?.getAttribute("src") || "",
        iframeExists: !!iframe,
      };
    });
    console.log(`  Office tab: badgeKind=${officeTabInfo.badgeKind}, iframe=${officeTabInfo.iframeSrc}`);

    // docx should have badge kind "word"
    assert.equal(officeTabInfo.badgeKind, "word", `docx should have badgeKind 'word', got '${officeTabInfo.badgeKind}'`);
    assert.ok(officeTabInfo.iframeExists, "Office tab should have an iframe");
    assert.ok(officeTabInfo.iframeSrc.includes("/onlyoffice"), `iframe src should include /onlyoffice: ${officeTabInfo.iframeSrc}`);
    
    // Parse iframe URL and verify required params
    const iframeUrl = new URL(officeTabInfo.iframeSrc, BASE_URL);
    assert.equal(iframeUrl.pathname, "/onlyoffice", `iframe pathname should be /onlyoffice: ${iframeUrl.pathname}`);
    
    // Check that assetId is in the URL (either in query params or encoded)
    const iframeAssetId = iframeUrl.searchParams.get("assetId") || "";
    assert.ok(iframeAssetId, "iframe URL should carry assetId param");
    assert.ok(iframeUrl.searchParams.has("mode"), "iframe URL should carry mode param");
    assert.ok(iframeUrl.searchParams.has("fileUrl"), "iframe URL should carry fileUrl param");
    
    // The fileUrl for local-folder should point to /api/local-folder/files/open
    const fileUrlParam = iframeUrl.searchParams.get("fileUrl") || "";
    assert.ok(
      fileUrlParam.includes("/api/local-folder/files/open") || fileUrlParam.startsWith("/api/"),
      `fileUrl should use Rust proxy URL: ${fileUrlParam}`
    );
    console.log(`  fileUrl uses Rust-accessible URL: ${fileUrlParam}`);

    // ======== Test 1b: existing office tab refreshes from view to edit ========
    console.log("Test 1b: existing docx tab refreshes from view mode to edit mode");
    await page.evaluate(({ asset, documentId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: asset.id,
          documentId,
          title: asset.file_name || "report.docx",
          assetType: asset.asset_type || "attachment",
          openTarget: "edit-mode",
        },
      }));
    }, { asset: officeAssets.docx, documentId });
    await page.waitForFunction(() => {
      const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
      const iframe = panel?.querySelector('iframe.mnote-resource-tab-frame');
      if (!(iframe instanceof HTMLIFrameElement)) return false;
      const url = new URL(iframe.getAttribute("src") || iframe.src, window.location.origin);
      return url.searchParams.get("mode") === "edit";
    }, null, { timeout: UI_TIMEOUT_MS });
    const refreshedTabInfo = await page.evaluate(() => {
      const tabs = Array.from(document.querySelectorAll('.mnote-main-tab[data-mnote-tab-kind="office"]'));
      const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
      const iframe = panel?.querySelector('iframe.mnote-resource-tab-frame');
      return {
        officeTabCount: tabs.length,
        iframeSrc: iframe?.getAttribute("src") || "",
      };
    });
    const refreshedUrl = new URL(refreshedTabInfo.iframeSrc, BASE_URL);
    console.log(`  Refreshed active tab URL: ${refreshedUrl.toString()}`);
    assert.equal(refreshedUrl.searchParams.get("mode"), "edit", "existing Office tab should refresh to mode=edit");
    assert.equal(refreshedTabInfo.officeTabCount, 1, "edit-mode should refresh the existing docx tab instead of creating another tab");

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

    // ======== Test 2: pptx opens with ppt badge ========
    console.log("Test 2: pptx opens with ppt badge");
    await page.evaluate(({ asset, documentId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: asset.id,
          documentId,
          title: asset.file_name || "slides.pptx",
          assetType: asset.asset_type || "attachment",
        },
      }));
    }, { asset: officeAssets.pptx, documentId });
    
    await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    const pptTabInfo = await page.evaluate(() => {
      const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
      return {
        badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
      };
    });
    console.log(`  PPT tab badge: ${pptTabInfo.badgeKind}`);
    assert.equal(pptTabInfo.badgeKind, "ppt", `pptx should have badgeKind 'ppt', got '${pptTabInfo.badgeKind}'`);

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

    // ======== Test 3: xlsx opens with sheet badge ========
    console.log("Test 3: xlsx opens with sheet badge");
    await page.evaluate(({ asset, documentId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: asset.id,
          documentId,
          title: asset.file_name || "data.xlsx",
          assetType: asset.asset_type || "attachment",
        },
      }));
    }, { asset: officeAssets.xlsx, documentId });
    
    await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    const xlsxTabInfo = await page.evaluate(() => {
      const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
      return {
        badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
      };
    });
    console.log(`  XLSX tab badge: ${xlsxTabInfo.badgeKind}`);
    assert.equal(xlsxTabInfo.badgeKind, "sheet", `xlsx should have badgeKind 'sheet', got '${xlsxTabInfo.badgeKind}'`);

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

    // ======== Test 4: new-window defaults to view mode ========
    console.log("Test 4: new-window opens /onlyoffice with view mode");
    const [officePopup] = await Promise.all([
      page.waitForEvent("popup", { timeout: UI_TIMEOUT_MS }).catch(() => null),
      page.evaluate(({ asset, documentId }) => {
        window.dispatchEvent(new CustomEvent("tree.asset.open", {
          detail: {
            assetId: asset.id,
            documentId,
            title: asset.file_name || "report.docx",
            assetType: asset.asset_type || "attachment",
            openTarget: "new-window",
          },
        }));
      }, { asset: officeAssets.docx, documentId }),
    ]);

    if (officePopup) {
      await officePopup.waitForLoadState("domcontentloaded", { timeout: UI_TIMEOUT_MS }).catch(() => undefined);
      const popupUrl = new URL(officePopup.url());
      console.log(`  New-window URL: ${popupUrl.toString()}`);
      assert.equal(popupUrl.pathname, "/onlyoffice", `new-window pathname should be /onlyoffice: ${popupUrl.pathname}`);
      
      // new-window 是浏览器目标，不代表编辑权限；默认仍应只读
      const popupMode = popupUrl.searchParams.get("mode") || "";
      assert.equal(popupMode, "view", `new-window mode should be 'view', got '${popupMode}'`);
      
      // Check assetId is present
      const popupAssetId = popupUrl.searchParams.get("assetId") || "";
      assert.ok(popupAssetId, "new-window URL should carry assetId");
      
      await officePopup.close().catch(() => undefined);
    } else {
      console.warn("  No popup triggered — this may mean the run is headless and popup was blocked. Acceptable in CI.");
    }

    // ======== Test 4b: explicit edit-mode opens /onlyoffice with edit mode ========
    console.log("Test 4b: explicit edit-mode opens /onlyoffice with edit mode");
    const [editPopup] = await Promise.all([
      page.waitForEvent("popup", { timeout: UI_TIMEOUT_MS }).catch(() => null),
      page.evaluate(({ asset, documentId }) => {
        window.dispatchEvent(new CustomEvent("tree.asset.open", {
          detail: {
            assetId: asset.id,
            documentId,
            title: asset.file_name || "report.docx",
            assetType: asset.asset_type || "attachment",
            openTarget: "edit-mode",
          },
        }));
      }, { asset: officeAssets.docx, documentId }),
    ]);

    if (editPopup) {
      await editPopup.waitForLoadState("domcontentloaded", { timeout: UI_TIMEOUT_MS }).catch(() => undefined);
      const editUrl = new URL(editPopup.url());
      console.log(`  Edit-mode URL: ${editUrl.toString()}`);
      assert.equal(editUrl.pathname, "/onlyoffice", `edit-mode pathname should be /onlyoffice: ${editUrl.pathname}`);
      const editMode = editUrl.searchParams.get("mode") || "";
      assert.equal(editMode, "edit", `edit-mode target should use mode=edit, got '${editMode}'`);
      await editPopup.close().catch(() => undefined);
    } else {
      const editTabInfo = await page.evaluate(() => {
        const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
        const iframe = panel?.querySelector('iframe.mnote-resource-tab-frame');
        return {
          iframeSrc: iframe?.getAttribute("src") || "",
        };
      });
      const editUrl = new URL(editTabInfo.iframeSrc, BASE_URL);
      const editMode = editUrl.searchParams.get("mode") || "";
      console.log(`  Edit-mode active tab URL: ${editUrl.toString()}`);
      assert.equal(editMode, "edit", `edit-mode active tab target should use mode=edit, got '${editMode}'`);
    }

    // ======== Test 5: OnlyOffice /onlyoffice page self-test (config URL/document URL/callback URL) ========
    console.log("Test 5: /onlyoffice page structure validation");
    const onlyofficeUrl = new URL("/onlyoffice", BASE_URL);
    onlyofficeUrl.searchParams.set("fileUrl", "/api/local-folder/files/open?rootUri=file:///test&path=doc.docx");
    onlyofficeUrl.searchParams.set("fileName", "test.docx");
    onlyofficeUrl.searchParams.set("fileType", "docx");
    onlyofficeUrl.searchParams.set("assetId", "test-asset-id");
    onlyofficeUrl.searchParams.set("mode", "edit");
    
    const response = await page.goto(onlyofficeUrl.toString(), {
      waitUntil: "domcontentloaded",
      timeout: UI_TIMEOUT_MS,
    });
    
    // Verify the page rendered
    const pageContent = await page.evaluate(() => {
      return {
        title: document.title,
        hasFrameContainer: !!document.getElementById("onlyoffice-frame"),
        hasErrorContainer: !!document.getElementById("onlyoffice-error"),
        hasScript: typeof window.__MNOTE_ONLYOFFICE_READY__ !== "undefined",
        initialConfig: typeof window.initial !== "undefined",
      };
    });
    console.log(`  /onlyoffice page: ${JSON.stringify(pageContent)}`);
    
    assert.ok(pageContent.hasFrameContainer, "/onlyoffice should have #onlyoffice-frame container");
    assert.ok(pageContent.hasErrorContainer, "/onlyoffice should have #onlyoffice-error container");
    assert.ok(pageContent.hasScript, "/onlyoffice should have runtime script");

    // Verify the config has correct document URL and callback URL source
    const scriptContent = await page.evaluate(() => {
      const scripts = document.querySelectorAll("script");
      const relevant = Array.from(scripts).filter(s => s.textContent && s.textContent.includes("buildCallbackUrl"));
      const text = relevant.length > 0 ? relevant[0].textContent : "";
      return {
        hasCallbackUrlBuilder: text.includes("buildCallbackUrl"),
        hasResolveDocumentUrl: text.includes("resolveDocumentUrl"),
        hasProxyLogic: text.includes("/api/onlyoffice/proxy"),
        snippet: text.substring(0, 200),
      };
    });
    console.log(`  Script: hasCallbackUrl=${scriptContent.hasCallbackUrlBuilder}, hasResolveDocumentUrl=${scriptContent.hasResolveDocumentUrl}`);

    assert.ok(scriptContent.hasCallbackUrlBuilder, "OnlyOffice page should define buildCallbackUrl");
    assert.ok(scriptContent.hasResolveDocumentUrl, "OnlyOffice page should define resolveDocumentUrl");
    // The proxy logic may not appear if the script template isn't fully rendered - check for proxy handling
    const hasProxy = scriptContent.hasProxyLogic || pageContent.initialConfig;
    assert.ok(hasProxy, "OnlyOffice page should have proxy-based URL resolution strategy");

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