#!/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}:task505`,
      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 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("uploadIntent", "editor.markdown.attach");
      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 openResourceTab(page, asset, documentId) {
  await page.evaluate(({ asset, documentId }) => {
    window.dispatchEvent(new CustomEvent("tree.asset.open", {
      detail: {
        assetId: asset.id,
        documentId,
        title: asset.file_name || "resource-note.md",
        assetType: asset.asset_type || "attachment",
      },
    }));
  }, { asset, documentId });
  await page.locator('[data-testid="mnote-resource-tab-host"]:not([hidden])').waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  await page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task505-resource-watch-"));
  const relativePath = "README.md";
  const documentId = localMdDocumentId(relativePath);
  const resourceRelativePath = "README/resource-note.md";
  const resourcePath = path.join(root, resourceRelativePath);
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.writeFileSync(path.join(root, relativePath), "# Page\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, resourceRelativePath, states: [] };
  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 asset = await uploadLocalAsset(
      page,
      root,
      documentId,
      "resource-note.md",
      "text/markdown",
      Buffer.from("# Resource Note\n\n旧资源正文\n", "utf8"),
      "attachment",
    );
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await openResourceTab(page, asset, documentId);
    await page.waitForFunction(
      (resourceNeedle) => {
        const snapshot = typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
          ? window.__mnoteDebugDocumentSessions.snapshot()
          : null;
        return Array.isArray(snapshot?.localFolderRoots)
          && snapshot.localFolderRoots.some((item) => String(item || "").includes(`resource:${resourceNeedle}`));
      },
      resourceRelativePath,
      { timeout: UI_TIMEOUT_MS },
    );

    const externalCleanToken = `外部资源更新 ${Date.now()}`;
    fs.writeFileSync(resourcePath, `# Resource Note\n\n${externalCleanToken}\n`, "utf8");
    await page.waitForFunction(
      (needle) => {
        const resourceText = document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror')?.textContent || "";
        const pageConflict = Boolean(document.querySelector('.document-pane[data-pane-role="primary"] > [data-testid="mnote-editor-conflict-panel"]'));
        return resourceText.includes(needle) && !pageConflict;
      },
      externalCleanToken,
      { timeout: UI_TIMEOUT_MS },
    );
    result.states.push({ step: "clean-resource-external-update", externalCleanToken });

    const editor = page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first();
    const dirtyToken = `资源未保存 ${Date.now()}`;
    const externalDirtyToken = `资源外部二次更新 ${Date.now()}`;
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.press(process.platform === "darwin" ? "Meta+End" : "Control+End").catch(() => undefined);
    await page.keyboard.type(`\n${dirtyToken}`, { delay: 2 });
    fs.writeFileSync(resourcePath, `# Resource Note\n\n${externalDirtyToken}\n`, "utf8");
    await page.waitForFunction(
      ({ dirtyNeedle }) => {
        const resourceText = document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror')?.textContent || "";
        const resourceConflict = document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-testid="mnote-editor-conflict-panel"]');
        const pageConflict = Boolean(document.querySelector('.document-pane[data-pane-role="primary"] > [data-testid="mnote-editor-conflict-panel"]'));
        return resourceText.includes(dirtyNeedle)
          && Boolean(resourceConflict)
          && /资源文件已在外部更新|文件冲突/.test(resourceConflict.textContent || "")
          && !pageConflict;
      },
      { dirtyNeedle: dirtyToken },
      { timeout: UI_TIMEOUT_MS },
    );
    result.states.push({ step: "dirty-resource-external-conflict", dirtyToken, externalDirtyToken });

    const finalState = await page.evaluate(() => ({
      resourceStatus: document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "",
      resourceText: document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror')?.textContent || "",
      resourceConflictText: document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-testid="mnote-editor-conflict-panel"]')?.textContent || "",
      pageText: document.querySelector('.document-pane[data-pane-role="primary"] > .document-shell .editor-surface .ProseMirror')?.textContent || "",
      pageConflictVisible: Boolean(document.querySelector('.document-pane[data-pane-role="primary"] > [data-testid="mnote-editor-conflict-panel"]')),
      sessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
        ? window.__mnoteDebugDocumentSessions.snapshot()
        : null,
    }));
    assert.equal(finalState.pageConflictVisible, false, `资源冲突不应污染正文页面: ${JSON.stringify(finalState)}`);
    assert(finalState.resourceText.includes(dirtyToken), `资源冲突后应保留未保存内容: ${JSON.stringify(finalState)}`);
    result.states.push({ step: "final", finalState });
    const officeAsset = await uploadLocalAsset(
      page,
      root,
      documentId,
      "resource-office.docx",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      Buffer.from("task505 office initial", "utf8"),
      "attachment",
    );
    const officePath = path.join(root, "README", "resource-office.docx");
    await page.evaluate(({ asset, documentId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: asset.id,
          documentId,
          title: asset.file_name || "resource-office.docx",
          assetType: asset.asset_type || "attachment",
        },
      }));
    }, { asset: officeAsset, documentId });
    await page.locator('.mnote-resource-tab-panel:not([hidden]) iframe.mnote-resource-tab-frame').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.locator('.mnote-resource-tab-panel:not([hidden])[data-mnote-resource-watch-ready="true"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const officeFrameBefore = await page.locator('.mnote-resource-tab-panel:not([hidden]) iframe.mnote-resource-tab-frame').first().getAttribute("src");
    fs.writeFileSync(officePath, "task505 office externally updated", "utf8");
    await page.waitForFunction(
      (previousSrc) => {
        const frame = document.querySelector('.mnote-resource-tab-panel:not([hidden]) iframe.mnote-resource-tab-frame');
        const src = frame instanceof HTMLIFrameElement ? String(frame.getAttribute('src') || frame.src || '') : '';
        return src && src !== previousSrc && src.includes('mnoteResourceReload=');
      },
      officeFrameBefore,
      { timeout: UI_TIMEOUT_MS },
    );
    result.states.push({ step: "passive-office-external-update", officeFrameBefore });
    fs.unlinkSync(officePath);
    await page.locator('.mnote-resource-tab-panel:not([hidden]) [data-mnote-resource-missing="true"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const officeMissingState = await page.evaluate(() => ({
      activeKind: document.querySelector('.mnote-main-tab.is-active')?.getAttribute('data-mnote-tab-kind') || '',
      missingText: document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-mnote-resource-missing="true"]')?.textContent || '',
      pageConflictVisible: Boolean(document.querySelector('.document-pane[data-pane-role="primary"] > [data-testid="mnote-editor-conflict-panel"]')),
    }));
    assert.equal(officeMissingState.pageConflictVisible, false, `Office 删除态不应污染正文页面: ${JSON.stringify(officeMissingState)}`);
    result.states.push({ step: "passive-office-delete-missing", officeMissingState });
    console.log(JSON.stringify({ ok: true, ...result }, null, 2));
  } catch (error) {
    const diagnostics = await page.evaluate(() => ({
      url: location.href,
      resourceText: document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror')?.textContent || "",
      resourceStatus: document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "",
      resourceConflictText: document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-testid="mnote-editor-conflict-panel"]')?.textContent || "",
      pageText: document.querySelector('.document-pane[data-pane-role="primary"] > .document-shell .editor-surface .ProseMirror')?.textContent || "",
      pageConflictVisible: Boolean(document.querySelector('.document-pane[data-pane-role="primary"] > [data-testid="mnote-editor-conflict-panel"]')),
      sessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
        ? window.__mnoteDebugDocumentSessions.snapshot()
        : null,
    })).catch((diagnosticsError) => ({ diagnosticsError: String(diagnosticsError) }));
    console.error(JSON.stringify({ ok: false, ...result, diagnostics, error: String(error && error.stack || error) }, null, 2));
    process.exitCode = 1;
  } 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);
});
