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

const assert = require("node:assert");
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 TIMEOUT_MS = Number(process.env.UI_TIMEOUT_MS || 30_000);

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 requestJson(requestContext, baseUrl, pathname, init = {}) {
  const response = await requestContext.fetch(`${baseUrl}${pathname}`, {
    method: init.method || "GET",
    headers: {
      "content-type": "application/json",
      ...(init.headers || {}),
    },
    data: init.data,
    timeout: TIMEOUT_MS,
  });
  const payload = await response.json().catch(() => null);
  assert(
    response.ok(),
    `${init.method || "GET"} ${pathname} failed ${response.status()}: ${JSON.stringify(payload)}`,
  );
  return payload;
}

async function loadAggregate(requestContext, baseUrl, documentId, rootUri) {
  const url = new URL(`/api/page-aggregate/${encodeURIComponent(documentId)}`, baseUrl);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", rootUri);
  const payload = await requestJson(requestContext, baseUrl, `${url.pathname}${url.search}`);
  return payload.result || payload;
}

async function effectivePreferences(requestContext, baseUrl, documentId, rootUri) {
  const url = new URL("/api/ui/preferences/effective", baseUrl);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", rootUri);
  url.searchParams.set("documentId", documentId);
  const payload = await requestJson(requestContext, baseUrl, `${url.pathname}${url.search}`);
  return payload.result;
}

async function main() {
  const port = await pickPort();
  const baseUrl = `http://127.0.0.1:${port}`;
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-ui-pref-smoke-"));
  const policyRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-ui-pref-policy-"));
  const policyFile = path.join(policyRoot, "access-policy.json");
  const actorId = `ui-pref-smoke-${process.pid}-${Date.now()}`;
  const otherActorId = `${actorId}-other`;
  const documentId = "local-md:README.md";
  const rootUri = `file://${root}`;
  fs.writeFileSync(path.join(root, "README.md"), "# README\n\n正文\n", "utf8");
  fs.writeFileSync(
    policyFile,
    JSON.stringify({
      grants: [
        {
          userId: actorId,
          rootUri,
          permission: "write",
          recursive: true,
        },
      ],
    }),
    "utf8",
  );

  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_ACCESS_POLICY_FILE: policyFile,
      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 browser = await chromium.launch({ headless: true });
  const firstContext = await browser.newContext({
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  const secondContext = await browser.newContext({
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  const otherContext = await browser.newContext({
    extraHTTPHeaders: {
      "x-mnote-actor-id": otherActorId,
      "x-mnote-actor-type": "user",
    },
  });

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

    const initialAggregate = await loadAggregate(firstContext.request, baseUrl, documentId, rootUri);
    assert.equal(
      initialAggregate.layout.pageOptions.hideTitleHeader,
      true,
      "普通外部 local folder 默认隐藏本地 Markdown 标题",
    );

    await requestJson(firstContext.request, baseUrl, "/api/ui/preferences", {
      method: "PUT",
      data: {
        sourceKind: "local_folder",
        rootUri,
        documentId,
        updates: {
          hideTitleHeader: false,
          showHeadingNumbers: true,
          wideLayout: true,
          pageFont: "song",
        },
      },
    });

    assert(
      !fs.existsSync(path.join(root, ".mnote", "page-options.json")),
      "SQLite 偏好写入不应生成 .mnote/page-options.json",
    );

    const sameUserEffective = await effectivePreferences(secondContext.request, baseUrl, documentId, rootUri);
    assert.equal(sameUserEffective.pageOptions.hideTitleHeader, false, "同用户第二浏览器应读到隐藏标题偏好");
    assert.equal(sameUserEffective.pageOptions.showHeadingNumbers, true, "同用户第二浏览器应读到标题编号偏好");
    assert.equal(sameUserEffective.pageOptions.wideLayout, true, "同用户第二浏览器应读到页面宽度偏好");
    assert.equal(sameUserEffective.pageOptions.pageFont, "song", "同用户第二浏览器应读到页面字体偏好");

    const otherUserEffective = await effectivePreferences(otherContext.request, baseUrl, documentId, rootUri);
    assert.equal(otherUserEffective.pageOptions.hideTitleHeader, true, "不同用户不应串读 source family 偏好");
    assert.equal(otherUserEffective.pageOptions.showHeadingNumbers, false, "不同用户不应串读 global 偏好");

    console.log("task493 page settings sqlite preferences smoke passed");
  } finally {
    await firstContext.close().catch(() => {});
    await secondContext.close().catch(() => {});
    await otherContext.close().catch(() => {});
    await browser.close().catch(() => {});
    server.kill("SIGINT");
    fs.rmSync(root, { recursive: true, force: true });
    fs.rmSync(policyRoot, { 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);
});
