#!/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 = "task496-editor-open-parallel-runtime-aggregate-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 requestTimes = {
    manifest: 0,
    pageAggregate: 0,
  };

  await page.addInitScript(() => {
    window.requestIdleCallback = () => 0;
  });
  await page.route("**/api/leptos-tiptap-runtime/manifest.json", async (route) => {
    if (!requestTimes.manifest) requestTimes.manifest = Date.now();
    await new Promise((resolve) => setTimeout(resolve, 1000));
    await route.continue();
  });
  await page.route("**/api/page-aggregate/**", async (route) => {
    if (!requestTimes.pageAggregate) requestTimes.pageAggregate = Date.now();
    await route.continue();
  });

  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.writeFileSync(path.join(rootPath, "Target.md"), "# Target\n\nEditor cold open target.\n", "utf8");

    const fileTreeUrl = new URL(baseUrl);
    const workspaceId = new URL(page.url()).searchParams.get("workspaceId") || "";
    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="filetree"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('#sidebar-file-tree-root .tree-row[data-local-relative-path="Target.md"] .tree-link').click({
      timeout: UI_TIMEOUT_MS,
    });
    await page.waitForURL((url) => url.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
    await page.locator('.document-pane[data-pane-role="primary"] .editor-surface').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    assert(requestTimes.manifest > 0, "应在打开文档时加载 editor runtime manifest");
    assert(requestTimes.pageAggregate > 0, "应在打开文档时请求 Page Aggregate");
    const aggregateDelayMs = requestTimes.pageAggregate - requestTimes.manifest;
    assert(
      aggregateDelayMs < 500,
      `Page Aggregate fetch 应与 editor runtime load 并行启动，实际晚于 manifest ${aggregateDelayMs}ms`,
    );

    console.log(JSON.stringify({
      ok: true,
      task: TASK,
      aggregateDelayMs,
      requestTimes,
    }, 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();
    }
  }
}

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