#!/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_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");

function excerpt(html) {
  return html.replace(/\s+/g, " ").trim().slice(0, 600);
}

function assertContains(html, pattern, label) {
  assert.match(html, pattern, `${label} 缺失；当前页面片段: ${excerpt(html)}`);
}

function assertNotContains(html, pattern, label) {
  assert.doesNotMatch(html, pattern, `${label} 仍存在；当前页面片段: ${excerpt(html)}`);
}

async function validateWolaiUiParity(baseUrl) {
  const response = await fetchWithTimeout(`${baseUrl}/`);
  const html = await response.text();

  assert.equal(response.status, 200, `/ 请求失败: ${response.status}; body: ${excerpt(html)}`);
  assert.equal(response.headers.get("x-mnote-web-owner"), "mnote-web");
  assert.match(response.headers.get("content-type") || "", /text\/html/);

  assertContains(html, /data-mnote-shell="workspace"/, "workspace shell 标记");
  assertContains(html, /data-testid="wolai-(workspace-identity|account|account-menu)"|工作区|个人空间|账号/, "账号/工作区身份");
  assertContains(html, /星标置顶/, "星标置顶入口");
  assertContains(html, /我的页面/, "我的页面入口");
  assertContains(html, /垃圾箱/, "垃圾箱入口");
  assertContains(html, /模板中心/, "模板中心入口");
  assertContains(html, /data-testid="wolai-topbar"/, "Wolai topbar");
  assertContains(html, /data-testid="wolai-floating-ai"/, "Wolai 浮动 AI 入口");
  assertNotContains(html, /欢迎使用 MNOTE 知识管理平台/, "极简欢迎页文案");
}

async function main() {
  await validateWolaiUiParity(BASE_URL);
  console.log(
    JSON.stringify(
      {
        ok: true,
        baseUrl: BASE_URL,
        shell: "workspace",
        owner: "mnote-web",
      },
      null,
      2,
    ),
  );
}

module.exports = {
  validateWolaiUiParity,
};

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