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

const assert = require("node:assert");
const { chromium } = require("playwright");
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");
const { createTempDocument, ensureAuthenticated, openDocument } = require("./tree-shell-smoke-helpers");

const BASE_URL = (process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);

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 main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  let seed = null;
  let created = null;

  try {
    await ensureAuthenticated(page, context.request);
    seed = await createTempDocument(context.request, null);
    const targetUrl = await openDocument(page, seed.workspaceId, seed.documentId);
    const response = await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    assert(response, "根页没有返回响应");
    assert.equal(response.status(), 200, `根页状态码异常: ${response.status()}`);
    assert.equal(response.headers()["x-mnote-web-owner"], "mnote-web", "文档页必须由 mnote-web 拥有");

    const createButton = page.getByTestId("wolai-sidebar-create-page").first();
    await createButton.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await createButton.click({ timeout: UI_TIMEOUT_MS });

    await page.waitForURL((url) => url.pathname.startsWith("/documents/"), {
      timeout: UI_TIMEOUT_MS,
      waitUntil: "domcontentloaded",
    });
    const createdUrl = new URL(page.url());
    const documentId = decodeURIComponent(createdUrl.pathname.replace(/^\/documents\//, ""));
    const workspaceId = createdUrl.searchParams.get("workspaceId") || "";
    assert(documentId, "新建后 URL 缺少 documentId");
    assert(workspaceId, "新建后 URL 缺少 workspaceId");
    created = { documentId, workspaceId };

    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"][data-pane-role="primary"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page
      .locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]')
      .first()
      .waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    assert(created?.documentId, "UI 新建未捕获到 documentId");
    assert(page.url().includes(created.documentId), "新建后 URL 未进入新文档");

    console.log(
      JSON.stringify(
        {
          ok: true,
          baseUrl: BASE_URL,
          documentId: created.documentId,
          workspaceId: created.workspaceId,
        },
        null,
        2,
      ),
    );
  } finally {
    if (created?.documentId && created?.workspaceId) {
      await postTreeCommand(
        { action: "purge", workspaceId: created.workspaceId, documentId: created.documentId },
        `清理 UI 新建页面 ${created.documentId}`,
      ).catch(() => undefined);
    }
    if (seed?.documentId && seed?.workspaceId) {
      await postTreeCommand(
        { action: "purge", workspaceId: seed.workspaceId, documentId: seed.documentId },
        `清理种子页面 ${seed.documentId}`,
      ).catch(() => undefined);
    }
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

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