"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", "task436-local-markdown-open-document-external-change-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));
  return url.toString();
}

function markdown(title, lines) {
  return [
    "---",
    `title: ${title}`,
    "---",
    "",
    ...lines,
    "",
  ].join("\n");
}

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}:task436`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit"],
    }, 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 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 waitForEditorText(page, text) {
  await page.waitForFunction(
    (expected) => {
      const editor = document.querySelector(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror");
      return (editor?.textContent || "").includes(expected);
    },
    text,
    { timeout: UI_TIMEOUT_MS },
  );
}

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 readEditorRuntime(page) {
  return await page.evaluate(() => {
    const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const editor = document.querySelector(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror");
    return {
      status: root?.getAttribute("data-runtime-editor-status") || "",
      error: root?.getAttribute("data-runtime-editor-error") || "",
      text: editor?.textContent || "",
    };
  });
}

async function typeDirtyText(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.type(text, { delay: 10 });
  await waitForEditorText(page, text.trim());
}

async function callMarkdownEdit(root, relativePath, search, replace) {
  const response = await fetch(`${BASE_URL}/api/hermes/tools/mnote/call`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
    body: JSON.stringify({
      toolName: "mnote.doc.markdown_edit",
      workspaceId: "local-ws:user_real:task436",
      documentId: localMdDocumentId(relativePath),
      sourceKind: "local_folder",
      rootUri: fileUrl(root),
      sessionId: `sess-task436-${Date.now()}`,
      runId: `run-task436-${Date.now()}`,
      toolCallId: `call-task436-${Date.now()}`,
      traceId: `trace-task436-${Date.now()}`,
      idempotencyKey: `idem-task436-${Date.now()}`,
      dryRun: false,
      args: {
        operations: [{ search, replace }],
      },
    }),
  });
  const payload = await response.json().catch(() => null);
  assert.equal(response.status, 200, `AI markdown_edit 应成功写入: ${JSON.stringify(payload)}`);
  assert.equal(payload?.result?.source, "local_folder", `AI markdown_edit 应走 local_folder: ${JSON.stringify(payload)}`);
  return payload;
}

async function runStep(label, navigationEvents, action) {
  const before = navigationEvents.length;
  await action();
  const after = navigationEvents.length;
  assert.equal(after, before, `${label} 不应触发浏览器导航或 reload`);
  return {
    label,
    navigationEventsBefore: before,
    navigationEventsAfter: after,
  };
}

async function run() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-local-open-doc-external-"));
  const files = {
    clean: "clean-sync.md",
    aiClean: "clean-ai-sync.md",
    dirty: "dirty-conflict.md",
    aiDirty: "dirty-ai-conflict.md",
    rename: "rename-open.md",
    delete: "delete-open.md",
  };
  writeWorkspaceManifest(root, "user_real");
  fs.writeFileSync(path.join(root, files.clean), markdown("Clean Sync", ["initial clean"]), "utf8");
  fs.writeFileSync(path.join(root, files.aiClean), markdown("Clean AI Sync", ["initial ai clean"]), "utf8");
  fs.writeFileSync(path.join(root, files.dirty), markdown("Dirty Conflict", ["initial dirty"]), "utf8");
  fs.writeFileSync(path.join(root, files.aiDirty), markdown("Dirty AI Conflict", ["initial ai dirty"]), "utf8");
  fs.writeFileSync(path.join(root, files.rename), markdown("Rename Open", ["initial rename"]), "utf8");
  fs.writeFileSync(path.join(root, files.delete), markdown("Delete Open", ["initial delete"]), "utf8");

  const browser = await chromium.launch({
    headless: true,
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1280, height: 860 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();
  const navigationEvents = [];
  page.on("framenavigated", (frame) => {
    if (frame === page.mainFrame()) {
      navigationEvents.push({ url: frame.url(), timestamp: Date.now() });
    }
  });

  const steps = [];
  try {
    await quickLogin(page);

    await openDocument(page, root, files.clean);
    await waitForEditorText(page, "initial clean");
    await page.waitForTimeout(300);
    navigationEvents.length = 0;
    steps.push(await runStep("打开文档外部修改后自动同步内容", navigationEvents, async () => {
      const token = `external-clean-${Date.now()}`;
      fs.writeFileSync(path.join(root, files.clean), markdown("Clean Sync", ["initial clean", token]), "utf8");
      await waitForEditorText(page, token);
      await waitForEditorStatus(page, "synced-external-change");
    }));

    await openDocument(page, root, files.aiClean);
    await waitForEditorText(page, "initial ai clean");
    await page.waitForTimeout(300);
    navigationEvents.length = 0;
    steps.push(await runStep("clean 文档 AI 后台写入后自动同步内容", navigationEvents, async () => {
      const aiToken = `ai-clean-${Date.now()}`;
      await callMarkdownEdit(root, files.aiClean, "initial ai clean", `initial ai clean ${aiToken}`);
      await waitForEditorText(page, aiToken);
      await waitForEditorStatus(page, "synced-external-change");
    }));

    await openDocument(page, root, files.dirty);
    await waitForEditorText(page, "initial dirty");
    await page.waitForTimeout(300);
    navigationEvents.length = 0;
    steps.push(await runStep("dirty 文档外部修改后进入冲突提示", navigationEvents, async () => {
      const localToken = `local-dirty-${Date.now()}`;
      const externalToken = `external-dirty-${Date.now()}`;
      await typeDirtyText(page, ` ${localToken}`);
      fs.writeFileSync(path.join(root, files.dirty), markdown("Dirty Conflict", ["initial dirty", externalToken]), "utf8");
      await waitForEditorStatus(page, "external-change-conflict");
      const runtime = await readEditorRuntime(page);
      assert(runtime.error.includes("本地 Markdown 文件已在外部更新"), `冲突提示不正确: ${JSON.stringify(runtime)}`);
      assert(runtime.text.includes(localToken), "dirty 冲突时不应静默覆盖用户正在编辑的内容");
    }));

    await openDocument(page, root, files.aiDirty);
    await waitForEditorText(page, "initial ai dirty");
    await page.waitForTimeout(300);
    navigationEvents.length = 0;
    steps.push(await runStep("dirty 文档 AI 后台写入后进入冲突提示", navigationEvents, async () => {
      const localToken = `local-ai-dirty-${Date.now()}`;
      const aiToken = `ai-background-${Date.now()}`;
      await typeDirtyText(page, ` ${localToken}`);
      await callMarkdownEdit(root, files.aiDirty, "initial ai dirty", `initial ai dirty ${aiToken}`);
      await waitForEditorStatus(page, "external-change-conflict");
      const runtime = await readEditorRuntime(page);
      assert(runtime.error.includes("本地 Markdown 文件已在外部更新"), `AI 写入冲突提示不正确: ${JSON.stringify(runtime)}`);
      assert(runtime.text.includes(localToken), "AI 写入冲突时不应静默覆盖用户正在编辑的内容");
      const saved = fs.readFileSync(path.join(root, files.aiDirty), "utf8");
      assert(saved.includes(aiToken), "AI 后台写入应已落盘，供后续合并处理");
    }));

    await openDocument(page, root, files.rename);
    await waitForEditorText(page, "initial rename");
    await page.waitForTimeout(300);
    navigationEvents.length = 0;
    steps.push(await runStep("打开文档外部重命名后给出冲突提示", navigationEvents, async () => {
      fs.renameSync(path.join(root, files.rename), path.join(root, "rename-open-renamed.md"));
      await waitForEditorStatus(page, "external-change-conflict");
      const runtime = await readEditorRuntime(page);
      assert(runtime.error.includes("本地 Markdown 文件已在外部更新"), `重命名提示不正确: ${JSON.stringify(runtime)}`);
    }));

    await openDocument(page, root, files.delete);
    await waitForEditorText(page, "initial delete");
    await page.waitForTimeout(300);
    navigationEvents.length = 0;
    steps.push(await runStep("打开文档外部删除后给出冲突提示", navigationEvents, async () => {
      fs.rmSync(path.join(root, files.delete));
      await waitForEditorStatus(page, "external-change-conflict");
      const runtime = await readEditorRuntime(page);
      assert(runtime.error.includes("已被删除"), `删除提示不正确: ${JSON.stringify(runtime)}`);
    }));

    const result = {
      ok: true,
      baseUrl: BASE_URL,
      root,
      steps,
      navigationEvents,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(`task436 local markdown open document external change smoke passed: ${RESULT_PATH}`);
  } finally {
    await browser.close().catch(() => {});
    fs.rmSync(root, { recursive: true, force: true });
  }
}

run().catch((error) => {
  const result = {
    ok: false,
    baseUrl: BASE_URL,
    error: error && error.stack ? error.stack : String(error),
  };
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
  console.error(error && error.stack ? error.stack : error);
  process.exit(1);
});
