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

const assert = require("node:assert");
const fs = require("node:fs/promises");
const path = require("node:path");
const { chromium } = require("playwright");
const {
  BASE_URL,
  UI_TIMEOUT_MS,
  cleanupDocuments,
  createTempDocument,
  ensureAuthenticated,
  openDocument,
  renameDocument,
  requestJson,
} = require("./tree-shell-smoke-helpers");

const OUT_DIR = path.join(process.cwd(), "tmp", "page-ai-apply-block-ops-real-smoke");
const HERMES_SESSION_ROOTS = [
  "/home/lix/.hermes/profiles/mnoteai/sessions",
  "/home/lix/.hermes/sessions",
];

async function listRecentHermesSessions(sinceMs) {
  const rows = [];
  for (const root of HERMES_SESSION_ROOTS) {
    let entries = [];
    try {
      entries = await fs.readdir(root, { withFileTypes: true });
    } catch {
      continue;
    }
    for (const entry of entries) {
      if (!entry.isFile() || !entry.name.startsWith("session_") || !entry.name.endsWith(".json")) {
        continue;
      }
      const filePath = path.join(root, entry.name);
      const stat = await fs.stat(filePath).catch(() => null);
      if (!stat || stat.mtimeMs < sinceMs) continue;
      const content = await fs.readFile(filePath, "utf8").catch(() => "");
      const parsed = JSON.parse(content || "{}");
      rows.push({
        path: filePath,
        mtimeMs: stat.mtimeMs,
        model: parsed.model || "",
        platform: parsed.platform || "",
        toolCount: Array.isArray(parsed.tools) ? parsed.tools.length : 0,
        toolNames: Array.isArray(parsed.tools)
          ? parsed.tools.map((tool) => tool?.function?.name || tool?.name).filter(Boolean)
          : [],
        messageCount: parsed.message_count || parsed.messageCount || 0,
        hasApplyBlockOps: content.includes("mnote_doc_apply_block_ops") || content.includes("mnote.doc.apply_block_ops"),
      });
    }
  }
  return rows.sort((a, b) => b.mtimeMs - a.mtimeMs);
}

async function callMnoteTool(request, payload) {
  return requestJson(request, "/api/hermes/tools/mnote/call", {
    method: "POST",
    headers: { "x-mnote-actor-id": payload.actorId || "smoke-user" },
    data: payload,
  });
}

async function fetchBlocks(request, target, suffix, actorId) {
  const response = await callMnoteTool(request, {
    toolName: "mnote.doc.fetch",
    workspaceId: target.workspaceId,
    documentId: target.documentId,
    actorId,
    sessionId: `sess_fetch_${suffix}`,
    runId: `run_fetch_${suffix}_${Date.now().toString(36)}`,
    toolCallId: `call_fetch_${suffix}_${Date.now().toString(36)}`,
    traceId: `trace_fetch_${suffix}`,
    capabilityScope: ["page.read"],
    args: {
      scope: "full",
      detail: "with_ids",
      maxBlocks: 20,
    },
  });
  assert.equal(response.ok, true, "doc.fetch 应成功");
  assert(Array.isArray(response.result.blocks), "doc.fetch 应返回 blocks");
  return response.result.blocks.map((block) => block.text);
}

async function main() {
  const suffix = Date.now().toString(36);
  const title = `TEST-PAGE-AI-APPLY-OPS-${suffix}`;
  const createdIds = [];
  const evidence = {
    ok: false,
    baseUrl: BASE_URL,
    title,
    profile: "mnoteai",
    timingsMs: {},
    requests: [],
  };
  await fs.mkdir(OUT_DIR, { recursive: true });

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, locale: "zh-CN" });
  const page = await context.newPage();

  page.on("request", (request) => {
    const url = request.url();
    if (!url.includes("/api/hermes/client/")) return;
    evidence.requests.push({
      method: request.method(),
      url: url.replace(BASE_URL, ""),
      postData: request.postDataJSON?.() || null,
      atMs: Date.now(),
    });
  });

  const startedAt = Date.now();
  try {
    const viewer = await ensureAuthenticated(page, context.request);
    const actorId = viewer.userId;
    const target = await createTempDocument(context.request);
    createdIds.push(target.documentId);
    evidence.documentId = target.documentId;
    evidence.workspaceId = target.workspaceId;
    await renameDocument(context.request, target.workspaceId, target.documentId, title);

    const seedContent = [
      { id: "p_1", type: "paragraph", content: [{ type: "text", text: `第一段 ${suffix}` }] },
      { id: "p_2", type: "paragraph", content: [{ type: "text", text: `第二段 ${suffix}` }] },
      { id: "p_3", type: "paragraph", content: [{ type: "text", text: `第三段 ${suffix}` }] },
    ];
    const seedStart = Date.now();
    const seed = await callMnoteTool(context.request, {
      toolName: "mnote.page.save",
      workspaceId: target.workspaceId,
      documentId: target.documentId,
      actorId,
      sessionId: `sess_seed_${suffix}`,
      runId: `run_seed_${suffix}`,
      toolCallId: `call_seed_${suffix}`,
      traceId: `trace_seed_${suffix}`,
      idempotencyKey: `idem_seed_${suffix}`,
      dryRun: false,
      capabilityScope: ["page.write"],
      args: { mode: "replace", content: seedContent },
    });
    assert.equal(seed.ok, true, "初始化 page.save 应成功");
    evidence.timingsMs.seed = Date.now() - seedStart;

    const openStart = Date.now();
    await openDocument(page, target.workspaceId, target.documentId);
    evidence.timingsMs.openDocument = Date.now() - openStart;

    const health = await requestJson(context.request, "/api/hermes/client/gateway/health?profile=mnoteai", {
      method: "GET",
    });
    evidence.gatewayHealth = health;
    assert.equal(health.gateway?.ok, true, `mnoteai gateway health 应为 ok: ${JSON.stringify(health)}`);
    assert(String(health.gateway?.upstream || "").includes(":8644"), "mnoteai profile 应路由到 8644 gateway");

    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-page-ai-icon[data-page-ai-tab="agent"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-profile-select]").selectOption("mnoteai", { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-profile") === "mnoteai",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.locator('.wolai-page-ai-panel-section:not([hidden]) [data-page-ai-tab="chat"]').click({
      timeout: UI_TIMEOUT_MS,
    });

    const prompt =
      `请使用 mnote_doc_apply_block_ops 一次完成三件事并回读验证：` +
      `把「第二段 ${suffix}」替换为「第二段已修改 ${suffix}」；` +
      `在「第一段 ${suffix}」后插入「插入段 ${suffix}」；` +
      `删除「第三段 ${suffix}」。只简短回复结果。`;
    const aiStart = Date.now();
    await page.locator("[data-page-ai-input]").fill(prompt, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });

    let finalTexts = [];
    const writeDeadline = Date.now() + Number(process.env.MNOTE_PAGE_AI_REAL_TIMEOUT_MS || 120_000);
    while (Date.now() < writeDeadline) {
      finalTexts = await fetchBlocks(context.request, target, suffix, actorId);
      if (
        finalTexts.includes(`第二段已修改 ${suffix}`) &&
        finalTexts.includes(`插入段 ${suffix}`) &&
        !finalTexts.includes(`第三段 ${suffix}`)
      ) {
        break;
      }
      await page.waitForTimeout(1000);
    }
    assert(finalTexts.includes(`第二段已修改 ${suffix}`), "回读未包含替换后的文本");
    assert(finalTexts.includes(`插入段 ${suffix}`), "回读未包含插入文本");
    assert(!finalTexts.includes(`第三段 ${suffix}`), "回读仍包含应删除文本");
    evidence.timingsMs.pageAiWriteVisible = Date.now() - aiStart;

    await page.waitForFunction(
      () => ["completed", "failed"].includes(document.documentElement.getAttribute("data-mnote-page-ai-run-status") || ""),
      null,
      { timeout: Number(process.env.MNOTE_PAGE_AI_REAL_TIMEOUT_MS || 120_000) },
    ).catch(() => undefined);
    evidence.pageAiRunStatus = await page.evaluate(() =>
      document.documentElement.getAttribute("data-mnote-page-ai-run-status") || "",
    );
    evidence.timingsMs.pageAiRunSettled = Date.now() - aiStart;

    evidence.finalTexts = finalTexts;

    evidence.conversationText = await page
      .locator('.wolai-page-ai-panel-section:not([hidden]) [data-page-ai-conversation]')
      .textContent({ timeout: UI_TIMEOUT_MS });
    evidence.screenshot = path.join(OUT_DIR, `${suffix}.png`);
    await page.screenshot({ path: evidence.screenshot, fullPage: true });
    evidence.hermesSessions = await listRecentHermesSessions(startedAt);
    evidence.ok = true;

    const evidencePath = path.join(OUT_DIR, `${suffix}.json`);
    await fs.writeFile(evidencePath, JSON.stringify(evidence, null, 2), "utf8");
    console.log(JSON.stringify({ ...evidence, evidencePath }, null, 2));
  } finally {
    await cleanupDocuments(context.request, createdIds).catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

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