#!/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 OUTPUT_DIR = path.join(process.cwd(), "tmp", "task504-local-md-external-conflict-recovery-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 workspaceId(ownerId) {
  return `local-ws:${ownerId}:task504`;
}

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: workspaceId(ownerId),
      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 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 typeUnsavedEditorText(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("End").catch(() => undefined);
  await page.keyboard.press("Enter");
  await page.keyboard.type(text, { delay: 2 });
}

async function waitForFileContent(filePath, predicate, timeoutMs) {
  const startedAt = Date.now();
  let lastContent = "";
  while (Date.now() - startedAt < timeoutMs) {
    if (fs.existsSync(filePath)) {
      lastContent = fs.readFileSync(filePath, "utf8");
      if (predicate(lastContent)) return lastContent;
    }
    await new Promise((resolve) => setTimeout(resolve, 120));
  }
  throw new Error(`文件内容未达到预期: ${filePath}; lastContent=${JSON.stringify(lastContent)}`);
}

function withTimeout(promise, timeoutMs, makeError) {
  let timer = 0;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(async () => {
      try {
        const error = typeof makeError === "function"
          ? await makeError()
          : new Error(String(makeError || "operation_timeout"));
        reject(error instanceof Error ? error : new Error(String(error)));
      } catch (err) {
        reject(err);
      }
    }, timeoutMs);
  });
  return Promise.race([promise, timeout]).finally(() => {
    if (timer) clearTimeout(timer);
  });
}

async function captureEditorDiagnostics(page, extra = {}) {
  return await page.evaluate((extraData) => ({
    ...extraData,
    url: location.href,
    status: document.querySelector('[data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "",
    statusError: document.querySelector('[data-runtime-editor-error]')?.getAttribute('data-runtime-editor-error') || "",
    conflictVisible: Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]')),
    editorText: document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "",
    panelText: document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "",
    sessions: typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
      ? window.__mnoteDebugDocumentSessions.snapshot()
      : null,
  }), extra).catch((err) => ({ ...extra, diagnosticsError: String(err) }));
}

async function waitForConflictState(page, expectedEditorText, expectedDiskText) {
  await page.locator('[data-testid="mnote-editor-conflict-panel"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  await page.waitForFunction(
    ({ editorNeedle, diskNeedle }) => {
      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');
      const panel = document.querySelector('[data-testid="mnote-editor-conflict-panel"]');
      return root?.getAttribute("data-runtime-editor-status") === "external-change-conflict"
        && (editor?.textContent || "").includes(editorNeedle)
        && (panel?.textContent || "").includes("文件冲突")
        && diskNeedle;
    },
    { editorNeedle: expectedEditorText, diskNeedle: expectedDiskText },
    { timeout: UI_TIMEOUT_MS },
  );
  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');
    const panel = document.querySelector('[data-testid="mnote-editor-conflict-panel"]');
    const sessions = typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
      ? window.__mnoteDebugDocumentSessions.snapshot()
      : null;
    return {
      status: root?.getAttribute("data-runtime-editor-status") || "",
      statusError: root?.getAttribute("data-runtime-editor-error") || "",
      editorText: editor?.textContent || "",
      panelText: panel?.textContent || "",
      sessions,
    };
  });
}

async function triggerExternalConflict(page, markdownPath, editorToken, diskToken) {
  await typeUnsavedEditorText(page, editorToken);
  fs.writeFileSync(markdownPath, `# Conflict Base\n\n${diskToken}\n`, "utf8");
  const conflictState = await waitForConflictState(page, editorToken, diskToken);
  assert(conflictState.editorText.includes(editorToken), `冲突后应保留编辑器未保存内容: ${JSON.stringify(conflictState)}`);
  assert(conflictState.status === "external-change-conflict", `应进入外部冲突态: ${JSON.stringify(conflictState)}`);
  return conflictState;
}

async function openConflictDiff(page, editorToken, diskToken) {
  await page.getByTestId("mnote-conflict-open-diff").click({ timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-conflict-diff-panel"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  await page.waitForFunction(
    ({ editorNeedle, diskNeedle }) => {
      const current = document.querySelector('[data-testid="mnote-conflict-current-text"]')?.textContent || "";
      const disk = document.querySelector('[data-testid="mnote-conflict-disk-text"]')?.textContent || "";
      return current.includes(editorNeedle) && disk.includes(diskNeedle);
    },
    { editorNeedle: editorToken, diskNeedle: diskToken },
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate(() => ({
    currentText: document.querySelector('[data-testid="mnote-conflict-current-text"]')?.textContent || "",
    diskText: document.querySelector('[data-testid="mnote-conflict-disk-text"]')?.textContent || "",
    mergeText: document.querySelector('[data-testid="mnote-conflict-merge-text"]')?.value || "",
  }));
}

async function acceptDiskVersion(page, diskToken) {
  await page.getByTestId("mnote-conflict-accept-disk").click({ timeout: UI_TIMEOUT_MS });
  await page.waitForFunction(
    (needle) => {
      const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const editorText = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "";
      const conflictVisible = Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]'));
      return !conflictVisible
        && root?.getAttribute("data-runtime-editor-status") !== "external-change-conflict"
        && editorText.includes(needle);
    },
    diskToken,
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate(() => ({
    status: document.querySelector('[data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "",
    editorText: document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "",
    conflictVisible: Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]')),
  }));
}

async function keepCurrentVersion(page, markdownPath, editorToken) {
  await page.getByTestId("mnote-conflict-keep-current").click({ timeout: UI_TIMEOUT_MS });
  await page.waitForFunction(
    (needle) => {
      const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const editorText = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "";
      const conflictVisible = Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]'));
      return !conflictVisible
        && root?.getAttribute("data-runtime-editor-status") !== "external-change-conflict"
        && editorText.includes(needle);
    },
    editorToken,
    { timeout: UI_TIMEOUT_MS },
  );
  const saved = await waitForFileContent(markdownPath, (content) => content.includes(editorToken), UI_TIMEOUT_MS);
  return await page.evaluate((savedContent) => ({
    status: document.querySelector('[data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "",
    editorText: document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "",
    conflictVisible: Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]')),
    savedContent,
  }), saved);
}

async function installDelayedFirstSave(page) {
  const gate = {
    enabled: false,
    intercepted: false,
    saveRequestCount: 0,
    release: null,
    interceptedPromise: null,
    releasePromise: null,
  };
  gate.interceptedPromise = new Promise((resolve) => {
    gate.markIntercepted = resolve;
  });
  gate.releasePromise = new Promise((resolve) => {
    gate.release = resolve;
  });
  const interceptSave = async (route) => {
    gate.saveRequestCount += 1;
    if (gate.enabled && !gate.intercepted) {
      gate.intercepted = true;
      gate.markIntercepted();
      await gate.releasePromise;
    }
    await route.continue();
  };
  await page.route("**/api/documents/save", interceptSave);
  await page.route("**/api/page-body/write", interceptSave);
  return gate;
}

async function assertSaveWhileTypingKeepsDirty(page, markdownPath, firstToken, secondToken, gate) {
  const saveRequestCountBeforeRace = gate.saveRequestCount;
  gate.enabled = true;
  await typeUnsavedEditorText(page, firstToken);
  await withTimeout(
    gate.interceptedPromise,
    UI_TIMEOUT_MS,
    async () => new Error(`保存请求未被拦截: ${JSON.stringify(await captureEditorDiagnostics(page, {
      saveRequestCount: gate.saveRequestCount,
      firstToken,
      secondToken,
    }))}`),
  );
  await typeUnsavedEditorText(page, secondToken);
  gate.release();
  await page.waitForFunction(
    ({ firstNeedle, secondNeedle }) => {
      const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const editorText = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "";
      const conflictVisible = Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]'));
      return !conflictVisible
        && root?.getAttribute("data-runtime-editor-status") !== "external-change-conflict"
        && editorText.includes(firstNeedle)
        && editorText.includes(secondNeedle);
    },
    { firstNeedle: firstToken, secondNeedle: secondToken },
    { timeout: UI_TIMEOUT_MS },
  );
  const saved = await waitForFileContent(
    markdownPath,
    (content) => content.includes(firstToken) && content.includes(secondToken),
    UI_TIMEOUT_MS,
  );
  assert(
    gate.saveRequestCount >= saveRequestCountBeforeRace + 2,
    `保存中继续输入应触发第二轮保存: before=${saveRequestCountBeforeRace}; after=${gate.saveRequestCount}`,
  );
  return await page.evaluate(({ savedContent, saveRequestCountBeforeRace, saveRequestCountAfterRace }) => ({
    status: document.querySelector('[data-runtime-editor-status]')?.getAttribute('data-runtime-editor-status') || "",
    editorText: document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror')?.textContent || "",
    conflictVisible: Boolean(document.querySelector('[data-testid="mnote-editor-conflict-panel"]')),
    savedContent,
    saveRequestCountBeforeRace,
    saveRequestCountAfterRace,
  }), {
    savedContent: saved,
    saveRequestCountBeforeRace,
    saveRequestCountAfterRace: gate.saveRequestCount,
  });
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task504-conflict-"));
  const relativePath = "README.md";
  const keepRelativePath = "Keep.md";
  const raceRelativePath = "SaveRace.md";
  const markdownPath = path.join(root, relativePath);
  const keepMarkdownPath = path.join(root, keepRelativePath);
  const raceMarkdownPath = path.join(root, raceRelativePath);
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.writeFileSync(markdownPath, "# Conflict Base\n\n原始正文\n", "utf8");
  fs.writeFileSync(keepMarkdownPath, "# Conflict Base\n\n保留当前基线\n", "utf8");
  fs.writeFileSync(raceMarkdownPath, "# Save Race\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 delayedSaveGate = await installDelayedFirstSave(page);
  const result = { root, relativePath, states: [], console: [], pageErrors: [] };
  page.on("console", (message) => result.console.push({ type: message.type(), text: message.text() }));
  page.on("pageerror", (error) => result.pageErrors.push(String(error && error.stack || error)));

  try {
    await quickLogin(page);
    await openDocument(page, root, relativePath);
    const editorToken = `编辑器未保存 ${Date.now()}`;
    const diskToken = `磁盘外部修改 ${Date.now()}`;
    const conflictState = await triggerExternalConflict(page, markdownPath, editorToken, diskToken);
    result.states.push({ step: "external-edit-conflict", conflictState, diskText: fs.readFileSync(markdownPath, "utf8") });
    const diffState = await openConflictDiff(page, editorToken, diskToken);
    result.states.push({ step: "open-diff", diffState });
    const acceptState = await acceptDiskVersion(page, diskToken);
    result.states.push({ step: "accept-disk", acceptState });

    await openDocument(page, root, keepRelativePath);
    const keepEditorToken = `保留当前编辑器 ${Date.now()}`;
    const keepDiskToken = `保留当前磁盘外部修改 ${Date.now()}`;
    const keepConflictState = await triggerExternalConflict(page, keepMarkdownPath, keepEditorToken, keepDiskToken);
    result.states.push({ step: "keep-current-conflict", conflictState: keepConflictState, diskText: fs.readFileSync(keepMarkdownPath, "utf8") });
    const keepState = await keepCurrentVersion(page, keepMarkdownPath, keepEditorToken);
    result.states.push({ step: "keep-current", keepState });

    await openDocument(page, root, raceRelativePath);
    const firstRaceToken = `保存中第一段 ${Date.now()}`;
    const secondRaceToken = `保存中第二段 ${Date.now()}`;
    const raceState = await assertSaveWhileTypingKeepsDirty(
      page,
      raceMarkdownPath,
      firstRaceToken,
      secondRaceToken,
      delayedSaveGate,
    );
    result.states.push({ step: "save-while-typing", raceState });

    await page.screenshot({ path: path.join(OUTPUT_DIR, "conflict.png"), fullPage: false });
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
    console.log(JSON.stringify({ ok: true, resultPath: RESULT_PATH, root, conflictState }, null, 2));
  } catch (error) {
    const diagnostics = await captureEditorDiagnostics(page, {
      delayedSaveGate: {
        enabled: delayedSaveGate.enabled,
        intercepted: delayedSaveGate.intercepted,
        saveRequestCount: delayedSaveGate.saveRequestCount,
      },
    });
    await page.screenshot({ path: path.join(OUTPUT_DIR, "failure.png"), fullPage: true }).catch(() => undefined);
    fs.writeFileSync(
      RESULT_PATH,
      `${JSON.stringify({ ok: false, ...result, diagnostics, diskText: fs.readFileSync(markdownPath, "utf8"), error: String(error && error.stack || error) }, null, 2)}\n`,
      "utf8",
    );
    console.error(JSON.stringify({ ok: false, resultPath: RESULT_PATH, root, 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);
});
