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

if (process.env.MNOTE_ALLOW_RETIRED_AI_AGENT_RUN_SMOKE !== "1") {
  console.log(JSON.stringify({
    ok: true,
    retired: true,
    script: "task155-e27-ai-edit-smoke.js",
    reason: "旧 /api/ai-agent/run E27 AI 编辑 smoke 已退役；当前请运行 scripts/task-hermes-page-ai-retirement-guard.js 验证 legacy guard。",
  }, null, 2));
  process.exit(0);
}

const assert = require("node:assert");
const fs = require("node:fs");
const { chromium } = require("playwright");
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(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const SCREENSHOT_DIR = process.env.MNOTE_PHASE_E_SCREENSHOT_DIR || "/mnt/Data1T/mnote/tmp/wolai-editor-parity/task155-e27-ai-edit-local-smoke";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";
const TARGET_BLOCK_ID = "e27-ai-target";

function assertAiSourceBoundary() {
  const spike = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
  assert(spike.includes("/api/ai-agent/run"), "E27 AI 入口必须调用 /api/ai-agent/run 在线主路径，Hermes 只能作为后端 fallback");
  assert(spike.includes('"provider": "online"'), "E27 AI 请求必须使用 provider=online 进入 openai-agents-python 主路径");
  assert(spike.includes('"stream": true'), "E27 AI 请求必须开启 stream=true，确保 /api/ai-agent/run 路由进入 agents sidecar");
  assert(spike.includes("mnote-leptos-tiptap-ai-status"), "E27 必须暴露 AI bridge 状态，供 smoke 和后续流式状态复用");
  assert(spike.includes("selectedBlockId"), "E27 AI 请求必须携带 Rust blockId 作为 selectedBlockId");
  assert(spike.includes("tiptapDocument"), "E27 AI 请求必须携带当前 Tiptap JSON 快照");
}

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);
  assert(payload?.result, `${label} 缺少 result`);
  return payload.result;
}

async function createTempDocument() {
  const title = `task155-e27-ai-${Date.now().toString(36)}`;
  const result = await postTreeCommand({ action: "create", title }, "创建 E27 临时文档");
  assert(result.documentId, "创建 E27 临时文档缺少 documentId");
  assert(result.workspaceId, "创建 E27 临时文档缺少 workspaceId");
  return { documentId: result.documentId, workspaceId: result.workspaceId, title };
}

async function purgeTempDocument(target) {
  if (!target?.documentId || !target?.workspaceId) return;
  await postTreeCommand({ action: "purge", workspaceId: target.workspaceId, documentId: target.documentId }, "清理 E27 临时文档");
}

async function waitForRuntimeIsland(page) {
  const root = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first();
  await root.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const editor = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]').first();
  await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.waitForFunction(() => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const editorNode = host?.querySelector('.editor-surface .ProseMirror[contenteditable="true"]');
    return host?.getAttribute("data-runtime-editor-status") !== "error" && editorNode instanceof HTMLElement && editorNode.isContentEditable;
  }, null, { timeout: UI_TIMEOUT_MS });
  return editor;
}

async function screenshot(page, name) {
  fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
  await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
}

async function setAiFixture(page) {
  await page.evaluate((targetBlockId) => {
    const editor = document.querySelector('.editor-surface .ProseMirror')?.editor;
    if (!editor) throw new Error('找不到 Tiptap editor');
    editor.commands.setContent({
      type: 'doc',
      content: [
        {
          type: 'paragraph',
          attrs: { blockId: targetBlockId },
          content: [{ type: 'text', text: 'E27 Ask AI source paragraph' }],
        },
      ],
    }, true);
    editor.commands.focus('start');
  }, TARGET_BLOCK_ID);
  await page.waitForFunction((targetBlockId) => {
    return document.querySelector(`[data-block-id="${targetBlockId}"]`) instanceof HTMLElement;
  }, TARGET_BLOCK_ID, { timeout: UI_TIMEOUT_MS });
}

async function openBlockMenuForTarget(page) {
  const target = page.locator(`[data-block-id="${TARGET_BLOCK_ID}"]`).first();
  await target.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
  await target.hover({ timeout: UI_TIMEOUT_MS });
  const handle = page.locator('[data-testid="block-drag-handle-trigger"]').first();
  await handle.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await handle.click({ timeout: UI_TIMEOUT_MS });
  const menu = page.locator('[data-testid="block-drag-menu"]').first();
  await menu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return menu;
}

function assertAiBridgePayload(payload, target) {
  assert.equal(payload.scope, "document", `AI 请求 scope 必须是 document: ${JSON.stringify(payload).slice(0, 1600)}`);
  assert.equal(payload.stream, true, "AI 请求必须开启 stream=true，避免退回 Hermes 非流式兼容路径");
  assert.equal(payload.options?.ai?.provider, "online", "AI 请求必须使用 provider=online，由 /api/ai-agent/run 分流到 agents sidecar");
  assert.equal(payload.context?.documentId, target.documentId, "AI 请求必须携带当前 documentId");
  assert.equal(payload.context?.workspaceId, target.workspaceId, "AI 请求必须携带当前 workspaceId");
  assert.equal(payload.context?.selectedBlockId, TARGET_BLOCK_ID, "AI 请求必须携带 Rust blockId");
  assert(Array.isArray(payload.context?.selectedUids) && payload.context.selectedUids.includes(TARGET_BLOCK_ID), "AI 请求 selectedUids 必须包含 Rust blockId");
  assert(payload.context?.selection?.currentBlockId === TARGET_BLOCK_ID, "AI 请求 selection 必须指向当前块");
  assert(payload.context?.tiptapDocument?.type === "doc", "AI 请求必须携带 tiptapDocument 快照");
  assert(JSON.stringify(payload.context.tiptapDocument).includes("E27 Ask AI source paragraph"), "AI 请求快照必须包含当前块正文");
  assert.equal(payload.context?.source, "leptos-tiptap-island", "AI 请求必须标记来源 island");
  assert.equal(payload.context?.action, "ask_ai", "块菜单 AI 入口必须使用 ask_ai action");
}

async function main() {
  assertAiSourceBoundary();

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  const aiBridgeRequests = [];

  await page.route(/\/api\/(hermes\/bridge|ai-agent\/run)$/, async (route) => {
    const request = route.request();
    const body = request.postData() || "{}";
    let payload = null;
    try {
      payload = JSON.parse(body);
    } catch {
      payload = { raw: body };
    }
    aiBridgeRequests.push({ url: request.url(), payload });
    if (request.url().includes("/api/ai-agent/run")) {
      await route.fulfill({
        status: 200,
        headers: {
          "content-type": "text/event-stream; charset=utf-8",
          "cache-control": "no-cache",
        },
        body: [
          'event: ready\n' + 'data: {"ok":true,"requestId":"task155-e27"}\n\n',
          'event: tool_result\n' + 'data: {"tool":"doc_replace_range","ok":true,"result":{"data":[{"id":"e27-ai-target","type":"paragraph","content":"E27 AI rewritten paragraph"}]}}\n\n',
          'event: completion\n' + 'data: {"ok":true,"text":"done","steps":1}\n\n',
        ].join(""),
      });
      return;
    }
    await route.fulfill({
      status: 200,
      headers: {
        "content-type": "application/json; charset=utf-8",
        "x-mnote-ai-bridge-owner": "rust-web-hermes",
      },
      body: JSON.stringify({
        ok: true,
        bridge: "e27-smoke-hermes-bridge",
        canonicalRoute: "/api/hermes/bridge",
        contract: {
          schema: "mnote.ai_bridge.v1",
          structuredWriteOwner: "rust-web-hermes",
        },
      }),
    });
  });

  let target = null;
  try {
    target = await createTempDocument();
    const url = `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`;
    const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    assert(response, "文档页没有返回响应");
    assert.equal(response.status(), 200, `文档页状态码异常: ${response.status()}`);

    await waitForRuntimeIsland(page);
    await setAiFixture(page);
    const menu = await openBlockMenuForTarget(page);
    await screenshot(page, "01-block-menu-ai-entry");

    await menu.locator('[data-testid="block-drag-menu-item-ai"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const status = document.querySelector('[data-testid="mnote-leptos-tiptap-ai-status"]');
      return status instanceof HTMLElement && ["pending", "ready"].includes(status.getAttribute("data-state") || "");
    }, null, { timeout: UI_TIMEOUT_MS });

    await page.waitForFunction(() => window.__MNOTE_E27_AI_BRIDGE_REQUEST_COUNT__ > 0, null, { timeout: UI_TIMEOUT_MS });
    assert(aiBridgeRequests.length > 0, "点击 AI 入口后必须发起 /api/ai-agent/run 请求");
    const first = aiBridgeRequests[0];
    assert(first.url.includes("/api/ai-agent/run"), `AI 请求必须走 /api/ai-agent/run 在线主路径，实际: ${first.url}`);
    assertAiBridgePayload(first.payload, target);

    await page.waitForFunction(() => {
      const status = document.querySelector('[data-testid="mnote-leptos-tiptap-ai-status"]');
      return status instanceof HTMLElement && status.getAttribute("data-state") === "ready";
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "02-ai-bridge-ready-state");

    console.log(JSON.stringify({ ok: true, baseUrl: BASE_URL, documentId: target.documentId, screenshotDir: SCREENSHOT_DIR, aiBridgeUrl: first.url }, null, 2));
  } finally {
    if (target) await purgeTempDocument(target).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);
  });
}
