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

const assert = require("node:assert");
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");

const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");

async function fetchText(path) {
  const response = await fetchWithTimeout(`${BASE_URL}${path}`);
  const text = await response.text();
  assert.equal(response.status, 200, `${path} 请求失败: ${response.status} ${text.slice(0, 200)}`);
  return { response, text };
}

async function readJsonResponse(response, label) {
  const text = await response.text();
  let payload = null;
  try {
    payload = text ? JSON.parse(text) : null;
  } catch {
    throw new Error(`${label} 返回了非 JSON 内容: ${text.slice(0, 1200)}`);
  }
  assert(response.ok, `${label} 请求失败: ${response.status}; body: ${text.slice(0, 1200)}`);
  return payload;
}

async function postTreeCommand(body, label) {
  const response = await fetchWithTimeout(`${BASE_URL}/api/tree/commands`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  const payload = await readJsonResponse(response, label);
  const result = payload && typeof payload.result === "object" ? payload.result : null;
  assert(result, `${label} 缺少 result`);
  return result;
}

async function createTempPage(title) {
  const result = await postTreeCommand({ action: "create", title }, `创建临时页面 ${title}`);
  assert(result.documentId, `创建临时页面 ${title} 缺少 documentId`);
  assert(result.workspaceId, `创建临时页面 ${title} 缺少 workspaceId`);
  return {
    documentId: result.documentId,
    workspaceId: result.workspaceId,
  };
}

async function purgeTempPage(target) {
  if (!target?.documentId || !target?.workspaceId) return;
  await postTreeCommand(
    {
      action: "purge",
      workspaceId: target.workspaceId,
      documentId: target.documentId,
    },
    `清理临时页面 ${target.documentId}`,
  );
}

async function main() {
  const pageTarget = await createTempPage(`task123-live-${Date.now().toString(36)}`);
  try {
    const page = await fetchText(`/documents/${encodeURIComponent(pageTarget.documentId)}?workspaceId=${encodeURIComponent(pageTarget.workspaceId)}`);
    assert.match(page.text, /__MNOTE_TREE_LIVE_BOOTSTRAP__/);
    assert.match(page.text, /mnote\.tree_live_bootstrap\.v1/);
    assert.match(page.text, /\/api\/tree\/events/);
    assert.match(page.text, /tree:snapshot/);
    assert.match(page.text, /tree:delta/);
    assert.match(page.text, /tree:resync/);

    const events = await fetchText(`/api/tree/events?workspaceId=${encodeURIComponent(pageTarget.workspaceId)}&maxPolls=0`);
    assert.match(events.response.headers.get("content-type") || "", /text\/event-stream/);
    assert.equal(events.response.headers.get("x-mnote-tree-stream-owner"), "rust-web");
    assert.match(events.text, /event:\s*snapshot/);
    assert.match(events.text, /id:\s*/);
    assert.match(events.text, /"revision"/);

    console.log(JSON.stringify({ ok: true, owner: "rust-web", stream: "/api/tree/events", documentId: pageTarget.documentId }, null, 2));
  } finally {
    await purgeTempPage(pageTarget).catch(() => undefined);
  }
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error));
  process.exit(1);
});
