#!/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}:task506`,
      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 waitForDeletedConflict(page, retainedText) {
  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 panelText = document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "";
      const snapshot = typeof window.__mnoteDebugDocumentSessions?.snapshot === "function"
        ? window.__mnoteDebugDocumentSessions.snapshot()
        : null;
      const envelopeDirtyState = snapshot?.sessions?.[0]?.lastExternalConflictEnvelope?.dirtyState || "";
      return root?.getAttribute("data-runtime-editor-status") === "external-change-conflict"
        && editorText.includes(needle)
        && panelText.includes("已被删除")
        && envelopeDirtyState === "Deleted";
    },
    retainedText,
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate(() => ({
    status: document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]')?.getAttribute("data-runtime-editor-status") || "",
    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,
  }));
}

async function waitForExternalMoveConflict(page, retainedText) {
  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 panelText = document.querySelector('[data-testid="mnote-editor-conflict-panel"]')?.textContent || "";
      return root?.getAttribute("data-runtime-editor-status") === "external-change-conflict"
        && editorText.includes(needle)
        && panelText.includes("文件冲突");
    },
    retainedText,
    { timeout: UI_TIMEOUT_MS },
  );
  return await page.evaluate(() => ({
    status: document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]')?.getAttribute("data-runtime-editor-status") || "",
    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,
  }));
}

async function main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task506-lifecycle-"));
  const deleteRelativePath = "DeleteMe.md";
  const moveRelativePath = "MoveMe.md";
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.writeFileSync(path.join(root, deleteRelativePath), "# Delete Me\n\n保留删除 buffer\n", "utf8");
  fs.writeFileSync(path.join(root, moveRelativePath), "# Move Me\n\n保留移动 buffer\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();
  try {
    await quickLogin(page);
    await openDocument(page, root, deleteRelativePath);
    fs.rmSync(path.join(root, deleteRelativePath));
    const deletedState = await waitForDeletedConflict(page, "保留删除 buffer");

    await openDocument(page, root, moveRelativePath);
    fs.renameSync(path.join(root, moveRelativePath), path.join(root, "Moved.md"));
    const movedState = await waitForExternalMoveConflict(page, "保留移动 buffer");

    console.log(JSON.stringify({
      ok: true,
      root,
      states: [
        { step: "external-delete", deletedState },
        { step: "external-rename-as-deleted", movedState },
      ],
    }, null, 2));
  } catch (error) {
    const diagnostics = await page.evaluate(() => ({
      url: location.href,
      status: document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]')?.getAttribute("data-runtime-editor-status") || "",
      statusError: document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]')?.getAttribute("data-runtime-editor-error") || "",
      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,
    })).catch((diagnosticsError) => ({ diagnosticsError: String(diagnosticsError) }));
    console.error(JSON.stringify({ ok: false, 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);
});
