#!/usr/bin/env node

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

const UI_TIMEOUT_MS = Number(process.env.UI_TIMEOUT_MS || 15_000);

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 fileUrl(filePath) {
  return `file://${filePath.split(path.sep).map((part, index) => (
    index === 0 ? "" : encodeURIComponent(part)
  )).join("/")}`;
}

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(1_000, () => {
        request.destroy();
        retry();
      });
    };
    const retry = () => {
      if (Date.now() > deadline) {
        reject(new Error(`server_not_ready: ${url}`));
        return;
      }
      setTimeout(tick, 250);
    };
    tick();
  });
}

async function main() {
  const port = await pickPort();
  const baseUrl = `http://127.0.0.1:${port}`;
  const dataRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-managed-workspace-"));
  const actorId = `no-convex-smoke-${process.pid}-${Date.now()}`;
  const managedRoot = path.join(dataRoot, "users", actorId, "workspaces", "my-space");
  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_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({
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();

  try {
    await waitForHttpOk(`${baseUrl}/health`, 60_000);
    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: 2_000 }).catch(() => false)) {
      await createButton.click({ timeout: UI_TIMEOUT_MS });
      await page.waitForURL((url) => {
        return url.pathname === "/" &&
          url.searchParams.get("sourceKind") === "local_folder" &&
          url.searchParams.get("rootUri") === fileUrl(managedRoot);
      }, { timeout: UI_TIMEOUT_MS });
    } else {
      await page.locator(".sidebar-workspace-name").first().waitFor({
        state: "visible",
        timeout: UI_TIMEOUT_MS,
      });
    }
    assert(fs.existsSync(path.join(managedRoot, ".mnote", "workspace.json")), "manifest 应落盘");
    const defaultPagePath = path.join(managedRoot, "pages", "我的空间.md");
    const hasAggregate = await page.locator("#__MNOTE_PAGE_AGGREGATE__").count();
    assert(hasAggregate > 0 || fs.existsSync(defaultPagePath) === false, "默认首页存在时应注入 Page Aggregate");

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator(".sidebar-workspace-name").first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const aggregateCount = await page.locator("#__MNOTE_PAGE_AGGREGATE__").count();
    if (aggregateCount > 0) {
      const aggregate = await page.locator("#__MNOTE_PAGE_AGGREGATE__").textContent({
        timeout: UI_TIMEOUT_MS,
      });
      assert(
        aggregate && aggregate.includes("local_markdown.content"),
        "刷新后仍应读取本地 Markdown page aggregate",
      );
    }

    console.log("task166 local-first managed workspace no-convex smoke passed");
  } 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);
});
