#!/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 = "task492-sidebar-starred-shortcuts-smoke";
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_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 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();
      });
    };
    const retry = () => {
      if (Date.now() > deadline) {
        reject(new Error(`server_not_ready: ${url}`));
        return;
      }
      setTimeout(tick, 250);
    };
    tick();
  });
}

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

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();
  const page = await context.newPage();
  const browserDiagnostics = [];
  let holdStarredSidebarProjection = false;
  let releaseStarredSidebarProjection = null;
  let starredSidebarProjectionCompleted = false;
  let scopedFileProjectionStartedAt = 0;
  let scopedFileProjectionCompletedAt = 0;
  await page.route("**/api/tree/projections/sidebar**", async (route) => {
    const url = new URL(route.request().url());
    if (holdStarredSidebarProjection && url.searchParams.get("sourceKind") === "local_folder") {
      await new Promise((resolve) => {
        releaseStarredSidebarProjection = resolve;
      });
      starredSidebarProjectionCompleted = true;
    }
    await route.continue();
  });
  await page.route("**/api/tree/projections/file**", async (route) => {
    const url = new URL(route.request().url());
    if (
      holdStarredSidebarProjection
      && url.pathname.endsWith("/api/tree/projections/file")
      && url.searchParams.get("parentRelativePath") === "design"
    ) {
      scopedFileProjectionStartedAt = scopedFileProjectionStartedAt || Date.now();
      await route.continue();
      scopedFileProjectionCompletedAt = Date.now();
      return;
    }
    await route.continue();
  });
  page.on("console", (message) => {
    browserDiagnostics.push(`console:${message.type()}:${message.text()}`);
  });
  page.on("pageerror", (error) => {
    browserDiagnostics.push(`pageerror:${error.message}`);
  });
  page.on("request", (request) => {
    const url = request.url();
    if (url.includes("/api/tree/projections/file")) {
      browserDiagnostics.push(`request:${url}`);
    }
  });

  try {
    await waitForHttpOk(`${baseUrl}/health`, 60_000);
    const authResponse = 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(authResponse.ok(), `测试账号注册失败: ${authResponse.status()} ${await authResponse.text()}`);
    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 rootUri = new URL(page.url()).searchParams.get("rootUri")
      || await page.evaluate(() => document.body.getAttribute("data-mnote-root-uri") || "");
    assert(rootUri, "应进入 local_folder workspace");
    const rootPath = fileUrlToPath(rootUri);
    fs.mkdirSync(path.join(rootPath, "design"), { recursive: true });
    fs.mkdirSync(path.join(rootPath, "other"), { recursive: true });
    fs.writeFileSync(path.join(rootPath, "Home.md"), "# Home\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "design", "Brief.md"), "# Brief\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "other", "Other.md"), "# Other\n", "utf8");

    const activeDocumentId = "local-md:Home.md";
    const url = new URL(page.url());
    url.pathname = `/documents/${encodeURIComponent(activeDocumentId)}`;
    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('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator("#sidebar-file-tree-root").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    assert.equal(await page.locator('[data-testid="wolai-public-state"]').isVisible(), false, "未公开页面不应显示全网公开");
    await page.locator('[data-mnote-action="toggle-sidebar-shortcut"][data-mnote-shortcut-kind="page"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="page"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    }).catch(async (error) => {
      const debug = await page.evaluate(() => ({
        href: location.href,
        action: document.documentElement.getAttribute("data-mnote-sidebar-shortcut-last-action"),
        workspaceId: document.getElementById("sidebar-file-tree-root")?.getAttribute("data-workspace-id") || "",
        rootUri: document.body.getAttribute("data-mnote-root-uri") || "",
        topbar: document.querySelector(".wolai-topbar-actions")?.innerHTML || "",
      }));
      throw new Error(`${error.message}; debug=${JSON.stringify(debug)}; browser=${browserDiagnostics.slice(-8).join(" | ")}`);
    });

    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 });
    const designShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first();
    await designShortcut.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    const cloudSpaceUrl = new URL(baseUrl);
    cloudSpaceUrl.searchParams.set("workspaceId", "default");
    await page.goto(cloudSpaceUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    const cloudDesignShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first();
    await cloudDesignShortcut.waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    assert.equal(
      await cloudDesignShortcut.getAttribute("data-mnote-shortcut-root-uri"),
      rootUri,
      "回到我的空间后，本地文件夹星标应携带自己的 rootUri",
    );
    await page.evaluate(() => {
      const panel = document.querySelector("#wolai-sidebar-page-tree-panel, [data-mnote-sidebar-tree-panel='page']");
      let root = document.querySelector("#sidebar-tree-root");
      if (!(root instanceof HTMLElement) && panel instanceof HTMLElement) {
        root = document.createElement("div");
        root.id = "sidebar-tree-root";
        root.className = "sidebar-tree";
        root.setAttribute("data-tree-shell-mode", "page");
        panel.appendChild(root);
      }
      if (!(root instanceof HTMLElement)) throw new Error("无法注入旧页面树 root");
      root.innerHTML = [
        '<ul class="tree-root" role="tree">',
        '<li class="tree-node" data-node-id="stale-my-space-page">',
        '<div class="tree-row" role="treeitem" data-shell-mode="page" data-node-id="stale-my-space-page" data-active="true">',
        '<button type="button" class="tree-link" data-rust-action="open" data-node-id="stale-my-space-page">',
        '<span class="tree-link-title">我的空间旧页面</span>',
        "</button>",
        "</div>",
        "</li>",
        "</ul>",
      ].join("");
    });

    holdStarredSidebarProjection = true;
    const shortcutClickAt = Date.now();
    await cloudDesignShortcut.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"] .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/Brief.md"]').waitFor({
      state: "visible",
      timeout: 1_500,
    }).catch((error) => {
      if (releaseStarredSidebarProjection) releaseStarredSidebarProjection();
      throw new Error(`星标文件夹 scoped FileTree 应先于页面树 projection 可交互: elapsed=${Date.now() - shortcutClickAt}ms fileStarted=${scopedFileProjectionStartedAt} fileDone=${scopedFileProjectionCompletedAt} sidebarDone=${starredSidebarProjectionCompleted}; ${error.message}`);
    });
    assert.equal(starredSidebarProjectionCompleted, false, "scoped FileTree 可见时，延迟中的 page tree projection 不应已经完成");
    assert(scopedFileProjectionStartedAt > 0, "点击星标文件夹后应立即启动 scoped file projection");
    assert(scopedFileProjectionCompletedAt > 0, "点击星标文件夹后 scoped file projection 应先完成");
    if (releaseStarredSidebarProjection) releaseStarredSidebarProjection();
    await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    holdStarredSidebarProjection = false;
    await page.waitForFunction(() => {
      const root = document.querySelector("#sidebar-tree-root");
      if (!(root instanceof HTMLElement)) return false;
      const stale = root.querySelectorAll('.tree-row[data-shell-mode="page"][data-node-id="stale-my-space-page"]').length;
      return stale === 0 && /Brief/.test(root.innerText || "");
    }, { timeout: UI_TIMEOUT_MS });
    const scopedExplorerUrl = new URL(page.url());
    assert.equal(scopedExplorerUrl.searchParams.get("sourceKind"), "local_folder", "点击星标文件夹后应切到本地文件夹 source");
    assert.equal(scopedExplorerUrl.searchParams.get("rootUri"), rootUri, "点击星标文件夹后 URL 应保留显式 rootUri");
    assert.equal(scopedExplorerUrl.searchParams.get("fileTreeScope"), "design", "点击星标文件夹后 URL 应进入 design scope");
    assert.equal(
      await page.evaluate(() => document.documentElement.getAttribute("data-mnote-sidebar-shortcut-open-error") || ""),
      "",
      "星标文件夹打开不应依赖 workspaceId 反推 rootUri",
    );
    const scopedText = await page.locator("#sidebar-file-tree-root").innerText({ timeout: UI_TIMEOUT_MS });
    assert.match(scopedText, /Brief/);
    assert.doesNotMatch(scopedText, /Other/);
    const scopedPageTreeState = await page.evaluate(() => {
      const root = document.querySelector("#sidebar-tree-root");
      return {
        text: root?.innerText || "",
        rowCount: root?.querySelectorAll('.tree-row[data-shell-mode="page"]').length || 0,
        staleRowCount: root?.querySelectorAll('.tree-row[data-shell-mode="page"][data-node-id="stale-my-space-page"]').length || 0,
        activeRows: Array.from(root?.querySelectorAll('.tree-row[data-shell-mode="page"][data-active="true"]') || []).map((row) => ({
          nodeId: row.getAttribute("data-node-id") || "",
          title: row.querySelector(".tree-link-title")?.textContent?.trim() || "",
        })),
      };
    });
    assert.equal(
      scopedPageTreeState.staleRowCount,
      0,
      `打开星标本地文件夹后不应保留原我的空间页面树: ${JSON.stringify(scopedPageTreeState)}`,
    );
    assert(
      scopedPageTreeState.rowCount > 0 && /Brief/.test(scopedPageTreeState.text),
      `打开星标本地文件夹后应显示本地 Markdown 页面树投影: ${JSON.stringify(scopedPageTreeState)}`,
    );

    await page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/Brief.md"] .tree-link').first().click({
      timeout: UI_TIMEOUT_MS,
    });
    await page.waitForURL((nextUrl) => nextUrl.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
    const scopedDocumentUrl = page.url();
    const scopedDocumentResponse = await context.request.fetch(scopedDocumentUrl);
    const scopedDocumentHtml = await scopedDocumentResponse.text();
    assert(scopedDocumentHtml.includes('data-mnote-filetree-scope="design"'), "SSR document shell 应输出 filetree scope");
    assert(scopedDocumentHtml.includes("Brief.md"), "SSR document shell 应输出 scoped 文件树内容");
    await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const documentScopedText = await page.locator("#sidebar-file-tree-root").innerText({ timeout: UI_TIMEOUT_MS });
    assert.match(documentScopedText, /Brief/, `打开 scoped md 后应保留 design scope: url=${page.url()} text=${documentScopedText} browser=${browserDiagnostics.slice(-12).join(" | ")}`);
    assert.doesNotMatch(documentScopedText, /Other/, `打开 scoped md 后不应回到根目录: url=${page.url()} text=${documentScopedText} browser=${browserDiagnostics.slice(-12).join(" | ")}`);

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    const reloadedDesignShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first();
    await reloadedDesignShortcut.waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await reloadedDesignShortcut.hover({ timeout: UI_TIMEOUT_MS });
    await reloadedDesignShortcut.locator('[data-mnote-shortcut-action="menu"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-sidebar-shortcut-menu"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.getByRole("menuitem", { name: "取消星标" }).click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').waitFor({
      state: "detached",
      timeout: UI_TIMEOUT_MS,
    });
    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    assert.equal(
      await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').count(),
      0,
      "三点菜单取消星标后刷新不应恢复该文件夹星标",
    );

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

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