#!/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-block-edit-workflow-smoke");

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 应成功");
  return response.result.blocks.map((block) => block.text);
}

async function main() {
  const suffix = Date.now().toString(36);
  const title = `TEST-PAGE-AI-FAST-BLOCK-${suffix}`;
  const createdIds = [];
  const evidence = {
    ok: false,
    baseUrl: BASE_URL,
    title,
    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/page-ai/") && !url.includes("/api/hermes/client/")) return;
    evidence.requests.push({
      method: request.method(),
      url: url.replace(BASE_URL, ""),
      atMs: Date.now(),
    });
  });
  page.on("response", async (response) => {
    const url = response.url();
    if (!url.includes("/api/page-ai/") && !url.includes("/api/hermes/client/")) return;
    const entry = {
      method: response.request().method(),
      url: url.replace(BASE_URL, ""),
      status: response.status(),
      atMs: Date.now(),
    };
    const contentType = response.headers()["content-type"] || "";
    if (contentType.includes("application/json")) {
      entry.body = await response.json().catch(() => null);
    }
    evidence.responses = evidence.responses || [];
    evidence.responses.push(entry);
  });

  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 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: [
          { 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}` }] },
        ],
      },
    });
    assert.equal(seed.ok, true, "初始化 page.save 应成功");

    await openDocument(page, target.workspaceId, target.documentId);
    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.locator('.wolai-page-ai-panel-section:not([hidden]) [data-page-ai-tab="chat"]').click({
      timeout: UI_TIMEOUT_MS,
    });

    const prompt =
      `把「第二段 ${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_FAST_TIMEOUT_MS || 60_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(500);
    }
    evidence.timingsMs.pageAiWriteVisible = Date.now() - aiStart;
    evidence.finalTexts = finalTexts;
    assert(finalTexts.includes(`第二段已修改 ${suffix}`), "回读未包含替换后的文本");
    assert(finalTexts.includes(`插入段 ${suffix}`), "回读未包含插入文本");
    assert(!finalTexts.includes(`第三段 ${suffix}`), "回读仍包含应删除文本");

    await page.waitForFunction(
      () => ["completed", "failed"].includes(document.documentElement.getAttribute("data-mnote-page-ai-run-status") || ""),
      null,
      { timeout: Number(process.env.MNOTE_PAGE_AI_FAST_TIMEOUT_MS || 60_000) },
    ).catch(() => undefined);
    evidence.pageAiRunStatus = await page.evaluate(() =>
      document.documentElement.getAttribute("data-mnote-page-ai-run-status") || "",
    );
    evidence.conversationText = await page
      .locator('.wolai-page-ai-panel-section:not([hidden]) [data-page-ai-conversation]')
      .textContent({ timeout: UI_TIMEOUT_MS });
    evidence.usedFastWorkflow = evidence.requests.some((request) =>
      request.url.includes("/api/page-ai/block-edit-workflow"),
    );
    evidence.usedHermesRun = evidence.requests.some((request) =>
      request.url.includes("/api/hermes/client/runs"),
    );
    assert.equal(evidence.usedFastWorkflow, true, "页面 AI 应调用 block-edit-workflow 快路径");
    assert.equal(evidence.usedHermesRun, false, "块编辑快路径成功时不应进入 Hermes agent run");

    evidence.screenshot = path.join(OUT_DIR, `${suffix}.png`);
    await page.screenshot({ path: evidence.screenshot, fullPage: true });
    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 {
    const evidencePath = path.join(OUT_DIR, `${suffix}.json`);
    evidence.evidencePath = evidencePath;
    await fs.writeFile(evidencePath, JSON.stringify(evidence, null, 2), "utf8").catch(() => undefined);
    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);
});
