#!/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 PPTX_PATH = process.env.MNOTE_UPLOAD_TEST_FILE || "/home/lix/Downloads/1768096586803-672be7a7-5cb3-454d-9b1b-6230f86ba392.pptx";
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}:task509`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

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 uploadAttachmentViaSlash(page, filePath) {
  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(filePath);
}

async function typeEditorText(page, text) {
  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(process.platform === "darwin" ? "Meta+End" : "Control+End").catch(() => undefined);
  await page.keyboard.type(`\n${text}`, { delay: 2 });
}

async function waitForEditorStatus(page, status) {
  await page.waitForFunction(
    (expected) => {
      const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      return root?.getAttribute("data-runtime-editor-status") === expected;
    },
    status,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function main() {
  assert(fs.existsSync(PPTX_PATH), `测试 pptx 不存在: ${PPTX_PATH}`);
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task509-upload-409-"));
  const relativePath = "README/README.md";
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.mkdirSync(path.join(root, "README"), { recursive: true });
  fs.writeFileSync(path.join(root, relativePath), "# Upload 409\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();
  let interceptedSave = null;
  await page.route("**/api/documents/save", async (route) => {
    const payload = JSON.parse(route.request().postData() || "{}");
    if (payload.editorSource === "local-upload-runtime") {
      interceptedSave = {
        expectedFileVersion: String(payload.expectedFileVersion || ""),
        writeIntentId: String(payload.writeIntentId || ""),
        saveOperationId: String(payload.saveOperationId || ""),
      };
      await route.fulfill({
        status: 409,
        contentType: "application/json",
        body: JSON.stringify({
          ok: false,
          error: {
            message: "本地 Markdown 文件已在外部更新，请刷新或保存前先处理冲突",
            code: "local_markdown_external_change",
          },
          conflict: {
            code: "local_markdown_external_change",
            currentDiskVersion: "simulated-disk-version",
            editorBaseVersion: payload.expectedFileVersion || "",
          },
        }),
      });
      return;
    }
    await route.continue();
  });

  try {
    await openDocument(page, root, relativePath);
    await uploadAttachmentViaSlash(page, PPTX_PATH);
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-last-upload-orphaned-policy") === "asset-kept-reference-unsaved-retry-required",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    const state = await page.evaluate(() => ({
      saveError: document.documentElement.getAttribute("data-mnote-last-upload-save-error") || "",
      orphanedAssetId: document.documentElement.getAttribute("data-mnote-last-upload-orphaned-asset-id") || "",
      orphanedPolicy: document.documentElement.getAttribute("data-mnote-last-upload-orphaned-policy") || "",
      inserted: document.documentElement.getAttribute("data-mnote-last-upload-inserted") || "",
      links: Array.from(document.querySelectorAll('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror a')).map((link) => ({
        text: link.textContent || "",
        href: link.getAttribute("href") || "",
      })),
    }));
    assert(interceptedSave?.expectedFileVersion, `local-upload save 应携带 expectedFileVersion: ${JSON.stringify(interceptedSave)}`);
    assert(interceptedSave?.writeIntentId && interceptedSave?.saveOperationId, `local-upload save 应携带写入意图: ${JSON.stringify(interceptedSave)}`);
    assert(state.saveError.includes("本地 Markdown 文件已在外部更新"), `应显示保存冲突错误: ${JSON.stringify(state)}`);
    assert(state.orphanedAssetId, `409 后应标记已落盘孤儿附件: ${JSON.stringify(state)}`);
    assert(state.links.some((link) => /\.pptx/i.test(link.text)), `编辑器中应保留未落盘引用以便用户重试/处理: ${JSON.stringify(state)}`);
    const assetPath = path.join(root, "README", path.basename(PPTX_PATH));
    assert(fs.existsSync(assetPath), `附件文件应已落盘并由 orphan policy 显式保留: ${assetPath}`);

    const blockedRelativePath = "Blocked.md";
    const blockedPath = path.join(root, blockedRelativePath);
    const blockedToken = `blocked-conflict-${Date.now()}`;
    fs.writeFileSync(blockedPath, "# Blocked\n\n初始正文\n", "utf8");
    await openDocument(page, root, blockedRelativePath);
    await typeEditorText(page, blockedToken);
    fs.writeFileSync(blockedPath, `# Blocked\n\n外部版本 ${blockedToken}\n`, "utf8");
    await waitForEditorStatus(page, "external-change-conflict");
    await page.evaluate(() => {
      document.documentElement.removeAttribute("data-mnote-last-upload-blocked-conflict");
    });
    const beforeBlockedFiles = new Set(fs.readdirSync(root));
    await uploadAttachmentViaSlash(page, PPTX_PATH);
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-last-upload-blocked-conflict") === "true",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    const afterBlockedFiles = new Set(fs.readdirSync(root));
    assert.deepEqual(
      [...afterBlockedFiles].sort(),
      [...beforeBlockedFiles].sort(),
      "session 已冲突时不应继续写入新的附件文件",
    );
    const blockedState = await page.evaluate(() => ({
      blockedConflict: document.documentElement.getAttribute("data-mnote-last-upload-blocked-conflict") || "",
      saveError: document.documentElement.getAttribute("data-mnote-last-upload-save-error") || "",
    }));
    assert.equal(blockedState.blockedConflict, "true", `冲突 session 应阻断上传: ${JSON.stringify(blockedState)}`);
    assert(blockedState.saveError.includes("冲突"), `冲突 session 阻断应给出提示: ${JSON.stringify(blockedState)}`);

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