#!/usr/bin/env node
"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const http = require("node:http");
const net = require("node:net");
const os = require("node:os");
const path = require("node:path");
const { spawn } = require("node:child_process");
const { chromium } = require("playwright");

const TASK = "task498-starred-page-tree-scope-and-local-edit-smoke";
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 35_000);
const TEST_PASSWORD = process.env.MNOTE_E2E_PASSWORD || ["Mnote", "E2E", "123!"].join("");

function resolveChromiumExecutablePath() {
  const explicit = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH || "";
  if (explicit && fs.existsSync(explicit)) return explicit;
  return [
    "/usr/bin/google-chrome-stable",
    "/usr/bin/google-chrome",
    "/snap/bin/chromium",
    "/usr/bin/chromium",
    "/usr/bin/chromium-browser",
  ].find((candidate) => fs.existsSync(candidate)) || "";
}

function pickPort() {
  return new Promise((resolve, reject) => {
    const server = net.createServer();
    server.listen(0, "127.0.0.1", () => {
      const address = server.address();
      const port = address && typeof address === "object" ? address.port : 0;
      server.close(() => resolve(port));
    });
    server.on("error", reject);
  });
}

function waitForHttpOk(url, timeoutMs) {
  const deadline = Date.now() + timeoutMs;
  return new Promise((resolve, reject) => {
    const retry = () => {
      if (Date.now() > deadline) {
        reject(new Error(`server_not_ready: ${url}`));
        return;
      }
      setTimeout(tick, 250);
    };
    const tick = () => {
      const request = http.get(url, (response) => {
        response.resume();
        if (response.statusCode >= 200 && response.statusCode < 500) {
          resolve();
          return;
        }
        retry();
      });
      request.on("error", retry);
      request.setTimeout(1000, () => {
        request.destroy();
        retry();
      });
    };
    tick();
  });
}

function fileUrlToPath(value) {
  const url = new URL(value);
  return decodeURIComponent(url.pathname);
}

function cssEscape(value) {
  return String(value).replace(/["\\]/g, "\\$&");
}

async function setPageRowExpanded(page, nodeId, expanded) {
  const selector = `#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${cssEscape(nodeId)}"]`;
  await page.locator(selector).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const current = await page.locator(selector).first().getAttribute("aria-expanded");
  if ((current === "true") !== expanded) {
    await page.locator(`${selector} [data-rust-action="toggle"]`).first().click({ timeout: UI_TIMEOUT_MS });
  }
  await page.waitForFunction(
    ({ targetNodeId, expected }) => {
      const row = document.querySelector(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(targetNodeId)}"]`);
      return row && row.getAttribute("aria-expanded") === String(expected);
    },
    { targetNodeId: nodeId, expected: expanded },
    { timeout: UI_TIMEOUT_MS },
  );
}

async function signUp(context, baseUrl, actorId) {
  const response = await context.request.fetch(`${baseUrl}/api/auth`, {
    method: "POST",
    data: {
      action: "auth:signIn",
      args: {
        provider: "password",
        params: {
          email: `${actorId}@example.com`,
          username: actorId,
          name: actorId,
          password: TEST_PASSWORD,
          flow: "signUp",
        },
      },
    },
  });
  assert(response.ok(), `测试账号注册失败: ${response.status()} ${await response.text()}`);
}

async function openDefaultLocalWorkspace(page, baseUrl) {
  await page.goto(baseUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  const createButton = page.locator('[data-testid="mnote-create-default-local-workspace"]').first();
  if (await createButton.isVisible({ timeout: 3000 }).catch(() => false)) {
    await createButton.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.searchParams.get("sourceKind") === "local_folder", {
      timeout: UI_TIMEOUT_MS,
    });
  }
  const url = new URL(page.url());
  const rootUri = url.searchParams.get("rootUri")
    || await page.evaluate(() => document.body.getAttribute("data-mnote-root-uri") || "");
  assert(rootUri, "应进入 local_folder workspace");
  return {
    rootUri,
    workspaceId: url.searchParams.get("workspaceId") || "",
  };
}

async function openLocalDocument(page, baseUrl, rootUri, workspaceId, documentId) {
  const url = new URL(`/documents/${encodeURIComponent(documentId)}`, baseUrl);
  if (workspaceId) url.searchParams.set("workspaceId", workspaceId);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", rootUri);
  url.searchParams.set("treeView", "filetree");
  await page.goto(url.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  await page.locator(".document-pane[data-pane-role='primary'] .editor-surface .ProseMirror[contenteditable='true']").first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function readEditorText(page) {
  return page.locator(".document-pane[data-pane-role='primary'] .editor-surface .ProseMirror").first().innerText({
    timeout: UI_TIMEOUT_MS,
  });
}

async function main() {
  const port = await pickPort();
  const baseUrl = `http://127.0.0.1:${port}`;
  const dataRoot = fs.mkdtempSync(path.join(os.tmpdir(), `${TASK}-`));
  const dbPath = path.join(dataRoot, "control-plane.sqlite3");
  const actorId = `${TASK}-${process.pid}-${Date.now()}`;
  const server = spawn("cargo", ["run", "-p", "mnote-web", "--bin", "mnote-web"], {
    cwd: path.join(__dirname, "..", "rust"),
    env: {
      ...process.env,
      MNOTE_WEB_BIND: `127.0.0.1:${port}`,
      MNOTE_WEB_PUBLIC_BIND: `127.0.0.1:${port}`,
      MNOTE_WEB_ENABLE_LEGACY_NEXT_COMPAT: "0",
      MNOTE_CONTROL_PLANE_DB_PATH: dbPath,
      MNOTE_LOCAL_WORKSPACE_BASE_DIR: dataRoot,
      CONVEX_SELF_HOSTED_URL: "http://127.0.0.1:9",
      NEXT_PUBLIC_CONVEX_URL: "http://127.0.0.1:9",
    },
    stdio: ["ignore", "pipe", "pipe"],
  });
  let stderr = "";
  server.stderr.on("data", (chunk) => {
    stderr += chunk.toString();
  });

  const executablePath = resolveChromiumExecutablePath();
  const browser = await chromium.launch({
    headless: true,
    ...(executablePath ? { executablePath } : {}),
  });
  const context = await browser.newContext({ viewport: { width: 1360, height: 920 } });
  const page = await context.newPage();
  const diagnostics = [];
  const viewStateRequests = [];
  page.on("console", (message) => diagnostics.push(`console:${message.type()}:${message.text()}`));
  page.on("pageerror", (error) => diagnostics.push(`pageerror:${error.message}`));
  page.on("request", (request) => {
    if (!request.url().includes("/api/tree/view-state")) return;
    viewStateRequests.push({
      method: request.method(),
      url: request.url(),
      postData: request.postData() || "",
      at: Date.now(),
    });
  });
  page.on("response", async (response) => {
    if (!response.url().includes("/api/tree/view-state")) return;
    const request = response.request();
    const entry = viewStateRequests.findLast((candidate) => candidate.url === request.url() && candidate.method === request.method() && !candidate.status);
    if (!entry) return;
    entry.status = response.status();
    entry.doneAt = Date.now();
    entry.durationMs = entry.doneAt - entry.at;
    entry.body = await response.text().catch(() => "");
  });

  try {
    await waitForHttpOk(`${baseUrl}/health`, 60_000);
    await signUp(context, baseUrl, actorId);
    const { rootUri, workspaceId } = await openDefaultLocalWorkspace(page, baseUrl);
    const rootPath = fileUrlToPath(rootUri);
    fs.mkdirSync(path.join(rootPath, "design"), { recursive: true });
    fs.writeFileSync(path.join(rootPath, "Home.md"), "# Home\n\noriginal\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "Other.md"), "# Other\n\nother\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "design", "Brief.md"), "# Brief\n\nbrief\n", "utf8");

    const fileTreeUrl = new URL(baseUrl);
    if (workspaceId) fileTreeUrl.searchParams.set("workspaceId", workspaceId);
    fileTreeUrl.searchParams.set("sourceKind", "local_folder");
    fileTreeUrl.searchParams.set("rootUri", rootUri);
    fileTreeUrl.searchParams.set("treeView", "filetree");
    await page.goto(fileTreeUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-mnote-sidebar-tree-tab="page"]').click({ timeout: UI_TIMEOUT_MS });
    const rootPageTreePut = page.waitForResponse((response) => {
      const postData = response.request().postData() || "";
      return response.url().includes("/api/tree/view-state")
        && response.request().method() === "PUT"
        && /"treeKind":"pagetree"/.test(postData)
        && /"scope":"root"/.test(postData);
    }, { timeout: UI_TIMEOUT_MS });
    await setPageRowExpanded(page, "local-dir:design", false);
    const rootPageTreeResponse = await rootPageTreePut;
    assert(rootPageTreeResponse.ok(), `root PageTree view-state 保存失败: ${rootPageTreeResponse.status()}`);
    await page.locator('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS });
    const designRow = page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design"]').first();
    await designRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await designRow.click({ button: "right", timeout: UI_TIMEOUT_MS });
    await page.getByText("加入/取消星标置顶").click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    const cloudUrl = new URL(baseUrl);
    cloudUrl.searchParams.set("workspaceId", "default");
    await page.goto(cloudUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    const designShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first();
    await designShortcut.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"] .tree-row[data-local-relative-path="design/Brief.md"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.waitForFunction(() => {
      const root = document.querySelector("#sidebar-tree-root");
      return root instanceof HTMLElement && /Brief/.test(root.innerText || "");
    }, { timeout: UI_TIMEOUT_MS }).catch(async (error) => {
      const state = await page.evaluate(() => {
        const root = document.querySelector("#sidebar-tree-root");
        return {
          href: location.href,
          pageTreeText: root instanceof HTMLElement ? root.innerText : "",
          pageTreeHtml: root instanceof HTMLElement ? root.innerHTML.slice(0, 1000) : "",
          fileTreeText: document.querySelector("#sidebar-file-tree-root")?.textContent || "",
          fileTreeScope: document.querySelector("#sidebar-file-tree-root")?.getAttribute("data-mnote-filetree-scope") || "",
        };
      });
      throw new Error(`${error.message}; state=${JSON.stringify(state)}; diagnostics=${diagnostics.slice(-20).join(" | ")}`);
    });
    const pageTreeText = await page.locator("#sidebar-tree-root").innerText({ timeout: UI_TIMEOUT_MS });
    assert.match(pageTreeText, /Brief/, `星标 design 后页面树应显示 design 内 Markdown: ${pageTreeText}`);
    assert.doesNotMatch(pageTreeText, /Home|Other/, `星标 design 后页面树不应显示根目录 Markdown: ${pageTreeText}`);
    assert(
      viewStateRequests.some((entry) => entry.method === "PUT" && entry.status === 200 && /"treeKind":"pagetree"/.test(entry.postData) && /"scope":"root"/.test(entry.postData)),
      `应记录 root PageTree view-state PUT: ${JSON.stringify(viewStateRequests)}`,
    );
    assert(
      viewStateRequests.some((entry) => entry.method === "GET" && entry.status === 200 && entry.url.includes("treeKind=pagetree") && entry.url.includes("scope=design")),
      `星标 design 应读取 scoped PageTree view-state: ${JSON.stringify(viewStateRequests)}`,
    );

    await openLocalDocument(page, baseUrl, rootUri, workspaceId, "local-md:Home.md");
    const editor = page.locator(".document-pane[data-pane-role='primary'] .editor-surface .ProseMirror[contenteditable='true']").first();
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.press(process.platform === "darwin" ? "Meta+A" : "Control+A");
    await page.keyboard.press("Backspace");
    const saveResponsePromise = page.waitForResponse(async (response) => {
      if (!response.url().includes("/api/page-body/write") || response.request().method() !== "POST") return false;
      const payload = response.request().postDataJSON();
      return payload?.documentId === "local-md:Home.md" && response.ok();
    }, { timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("111", { delay: 10 });
    await page.waitForFunction(
      (expected) => (document.querySelector(".document-pane[data-pane-role='primary'] .editor-surface .ProseMirror")?.textContent || "").includes(expected),
      "111",
      { timeout: UI_TIMEOUT_MS },
    );
    const saveResponse = await saveResponsePromise.catch(async (error) => {
      const state = await page.evaluate(() => ({
        editorText: document.querySelector(".document-pane[data-pane-role='primary'] .editor-surface .ProseMirror")?.textContent || "",
        status: document.querySelector("[data-runtime-editor-status]")?.getAttribute("data-runtime-editor-status") || "",
        debugSessions: window.__mnoteDebugDocumentSessions?.snapshot?.() || null,
      }));
      throw new Error(`${error.message}; edit_state=${JSON.stringify(state)}; diagnostics=${diagnostics.slice(-20).join(" | ")}`);
    });
    assert(saveResponse.ok(), `本地 Markdown 保存失败: ${saveResponse.status()}`);
    await page.waitForFunction(
      (expected) => (document.querySelector(".editor-surface .ProseMirror")?.textContent || "").includes(expected),
      "111",
      { timeout: UI_TIMEOUT_MS },
    );
    assert.match(fs.readFileSync(path.join(rootPath, "Home.md"), "utf8"), /111/, "保存后磁盘 Home.md 应包含 111");

    await openLocalDocument(page, baseUrl, rootUri, workspaceId, "local-md:Other.md");
    await openLocalDocument(page, baseUrl, rootUri, workspaceId, "local-md:Home.md");
    const reloadedText = await readEditorText(page);
    assert.match(reloadedText, /111/, `切换页面再回 Home.md 后编辑内容应保留: ${reloadedText}`);

    console.log(JSON.stringify({ ok: true, task: TASK, baseUrl, viewStateRequests }, null, 2));
  } finally {
    await browser.close();
    server.kill("SIGINT");
    fs.rmSync(dataRoot, { recursive: true, force: true });
    if (server.exitCode == null) {
      setTimeout(() => server.kill("SIGKILL"), 2000).unref();
    }
    if (server.exitCode && server.exitCode !== 130 && server.exitCode !== null) {
      process.stderr.write(stderr);
    }
  }
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
