#!/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 = "task500-navigation-page-route-guard-smoke";
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 45_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 signUp(context, baseUrl, actorId) {
  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()}`);
}

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 current = new URL(page.url());
  const rootUri = current.searchParams.get("rootUri")
    || await page.evaluate(() => document.body.getAttribute("data-mnote-root-uri") || "");
  assert(rootUri, "应进入 local_folder workspace");
  return {
    rootUri,
    workspaceId: current.searchParams.get("workspaceId") || "",
  };
}

async function assertNavigationPage(page) {
  await page.locator('[data-testid="mnote-navigation-page"]').waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  assert.equal(await page.locator("#__MNOTE_PAGE_AGGREGATE__").count(), 0, "导航页不应注入 Page Aggregate");
  assert.equal(await page.locator("#__MNOTE_EDITOR_BOOTSTRAP__").count(), 0, "导航页不应注入 editor bootstrap");
  assert.equal(await page.locator(".mnote-leptos-tiptap-spike-island").count(), 0, "导航页不应启动 tiptap island");
}

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,
    },
    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: 1440, height: 960 } });
  const page = await context.newPage();
  const diagnostics = [];
  page.on("console", (message) => diagnostics.push(`console:${message.type()}:${message.text()}`));
  page.on("pageerror", (error) => diagnostics.push(`pageerror:${error.message}`));

  try {
    await waitForHttpOk(`${baseUrl}/health`, 60_000);

    const unauthContext = await browser.newContext();
    const unauthPage = await unauthContext.newPage();
    await unauthPage.goto(`${baseUrl}/documents/local-md%3Adocs%7E2FPlan.md?sourceKind=local_folder&rootUri=file:///tmp/missing`, {
      waitUntil: "domcontentloaded",
      timeout: UI_TIMEOUT_MS,
    });
    assert.equal(new URL(unauthPage.url()).pathname, "/auth", "未登录文档访问应跳转 auth");
    assert(new URL(unauthPage.url()).searchParams.get("next") || "", "auth 跳转应保留 next");
    await unauthContext.close();

    await signUp(context, baseUrl, actorId);
    const { rootUri, workspaceId } = await openDefaultLocalWorkspace(page, baseUrl);
    const rootPath = fileUrlToPath(rootUri);
    fs.mkdirSync(path.join(rootPath, "docs"), { 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, "docs", "Plan.md"), "# Plan\n正文\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "other", "Other.md"), "# Other\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "Report.pdf"), "%PDF-1.4\n", "utf8");

    const rootUrl = new URL(baseUrl);
    if (workspaceId) rootUrl.searchParams.set("workspaceId", workspaceId);
    rootUrl.searchParams.set("sourceKind", "local_folder");
    rootUrl.searchParams.set("rootUri", rootUri);
    rootUrl.searchParams.set("treeView", "filetree");
    await page.goto(rootUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await assertNavigationPage(page);
    assert.equal(await page.locator('[data-root-active-page-id="local-md:Home.md"]').count(), 0, "打开文件夹 root 不应自动打开 Home.md");
    await page.waitForFunction(() => Boolean(window.__mnoteDocumentPaneRuntime?.openResourceInActiveTab), null, {
      timeout: UI_TIMEOUT_MS,
    });
    const popupPromise = page.waitForEvent("popup", { timeout: 3000 }).then((popup) => popup.url()).catch(() => null);
    const reportRow = page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="Report.pdf"]').first();
    await reportRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await reportRow.locator('[data-rust-action="open"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-mnote-tab-kind="pdf"] .mnote-main-tab-title', { hasText: "Report.pdf" }).waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.locator('[data-mnote-resource-tab-panel][data-resource-kind="pdf"] iframe.mnote-resource-tab-frame').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    assert.equal(await popupPromise, null, "导航页打开 PDF 应进入 mnoteTab，不应新开浏览器 Tab");
    assert.equal(new URL(page.url()).pathname, "/", "导航页打开 PDF 不应离开主页");
    await page.locator('[data-mnote-main-tab="page"][data-pane-role="primary"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-navigation-page"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    const docsRow = page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="docs"]').first();
    await docsRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const rootNavigationUrl = page.url();
    await docsRow.locator('[data-rust-action="open"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const row = document.querySelector('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="docs"]');
      return row && row.getAttribute("aria-expanded") === "true";
    }, null, { timeout: UI_TIMEOUT_MS });
    assert.equal(new URL(page.url()).searchParams.get("fileTreeScope"), null, "文件树文件夹点击只应展开，不应进入 scoped 导航页");
    assert.equal(page.url(), rootNavigationUrl, "文件树文件夹展开不应改 URL");

    await page.locator('[data-testid="mnote-navigation-folders"] [data-navigation-item-kind="folder"][data-local-relative-path="docs"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.searchParams.get("fileTreeScope") === "docs", {
      timeout: UI_TIMEOUT_MS,
    });
    await assertNavigationPage(page);
    assert(await page.locator('[data-testid="mnote-navigation-pages"] >> text=Plan.md').isVisible({ timeout: UI_TIMEOUT_MS }), "scope 导航页应展示当前层 Markdown");
    assert.equal(await page.locator('text=Other.md').count(), 0, "scope 导航页不应渲染 root 兄弟目录页面");

    const planRow = page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-document-id="local-md:docs~2FPlan.md"]').first();
    await planRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await planRow.locator('[data-rust-action="open"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname.includes("/documents/local-md%3Adocs~2FPlan.md"), {
      timeout: UI_TIMEOUT_MS,
    });
    await page.locator("#__MNOTE_PAGE_AGGREGATE__").waitFor({ state: "attached", timeout: UI_TIMEOUT_MS });

    const scopedUrl = new URL(baseUrl);
    if (workspaceId) scopedUrl.searchParams.set("workspaceId", workspaceId);
    scopedUrl.searchParams.set("sourceKind", "local_folder");
    scopedUrl.searchParams.set("rootUri", rootUri);
    scopedUrl.searchParams.set("treeView", "filetree");
    scopedUrl.searchParams.set("fileTreeScope", "docs");
    await page.goto(scopedUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await assertNavigationPage(page);
    assert(await page.locator('[data-testid="mnote-navigation-recent-folders"] >> text=docs').isVisible({ timeout: UI_TIMEOUT_MS }), "recent folders 应展示 docs");
    assert(await page.locator('[data-testid="mnote-navigation-recent-pages"] >> text=Plan').isVisible({ timeout: UI_TIMEOUT_MS }), "recent pages 应展示 Plan");

    const documentUrl = `${baseUrl}/documents/local-md%3Adocs%7E2FPlan.md?sourceKind=local_folder&rootUri=${encodeURIComponent(rootUri)}&treeView=filetree&fileTreeScope=docs`;
    await page.goto(documentUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    fs.unlinkSync(path.join(rootPath, "docs", "Plan.md"));
    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname === "/" && url.searchParams.get("missingPage") === "local-md:docs~2FPlan.md", {
      timeout: UI_TIMEOUT_MS,
    });
    await assertNavigationPage(page);

    console.log(JSON.stringify({
      ok: true,
      task: TASK,
      rootUri,
      finalUrl: page.url(),
    }, null, 2));
  } catch (error) {
    error.message += `\nserver stderr:\n${stderr.slice(-4000)}\nbrowser diagnostics:\n${diagnostics.slice(-20).join("\n")}`;
    throw error;
  } finally {
    await browser.close().catch(() => {});
    server.kill("SIGTERM");
  }
}

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