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

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/task152-e24-image-local-smoke";
const IMAGE_SRC = "/api/editor/image-placeholder.svg";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";

function assertOfficialImageBridge() {
  const source = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
  assert(
    source.includes("editor.set_image(TiptapImageResource"),
    "E24 图片入口必须通过 leptos-tiptap 的 set_image / TiptapImageResource bridge",
  );
  assert(
    !source.includes('TiptapContent::json(json!({ "type": "image"'),
    "E24 图片入口不能手写 image JSON 绕过 Tiptap setImage",
  );
  const imageExtension = fs.readFileSync("/mnt/Data1T/mnote/design/05-editor-mainline/reference-code/leptos-tiptap/tiptap/src/extensions/tiptap_image.ts", "utf8");
  assert(
    imageExtension.includes("Image.extend") && imageExtension.includes('"data-align"'),
    "E24 图片对齐必须复用 Tiptap Image.extend/addAttributes，而不是在 UI 里伪造样式",
  );
}

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 = `task152-e24-image-${Date.now().toString(36)}`;
  const result = await postTreeCommand({ action: "create", title }, "创建 E24 临时文档");
  assert(result.documentId, "创建 E24 临时文档缺少 documentId");
  assert(result.workspaceId, "创建 E24 临时文档缺少 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 }, "清理 E24 临时文档");
}

async function loadDocumentContent(target, label) {
  const url = `${BASE_URL}/api/documents/content?documentId=${encodeURIComponent(target.documentId)}&workspaceId=${encodeURIComponent(target.workspaceId)}`;
  const response = await fetchWithTimeout(url, { method: "GET" });
  return readJsonResponse(response, label);
}

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 waitForSavedImage(page) {
  await page.waitForFunction((expectedSrc) => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const image = host?.querySelector('.editor-surface .ProseMirror img[src]');
    return host?.getAttribute("data-runtime-editor-status") === "saved"
      && image instanceof HTMLImageElement
      && image.getAttribute("src") === expectedSrc
      && image.naturalWidth > 0
      && image.naturalHeight > 0;
  }, IMAGE_SRC, { timeout: UI_TIMEOUT_MS });
}

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

async function waitForCondition(label, predicate, timeoutMs = UI_TIMEOUT_MS) {
  const started = Date.now();
  let lastError = null;
  while (Date.now() - started < timeoutMs) {
    try {
      if (predicate()) return;
    } catch (error) {
      lastError = error;
    }
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  throw new Error(`${label} 超时${lastError ? `: ${lastError.message || lastError}` : ""}`);
}

function findImage(value) {
  if (!value || typeof value !== "object") return null;
  if (Array.isArray(value)) return value.map(findImage).find(Boolean) || null;
  if (value.type === "image" || value.blockType === "image") return value;
  return findImage(value.content) || findImage(value.children) || findImage(value.props?.tiptapImage);
}

function imageSrc(value) {
  const image = findImage(value);
  return image?.attrs?.src || image?.props?.src || image?.src || null;
}

function imageAlign(value) {
  const image = findImage(value);
  return image?.attrs?.["data-align"]
    || image?.props?.["data-align"]
    || image?.props?.tiptapImage?.attrs?.["data-align"]
    || null;
}

async function main() {
  assertOfficialImageBridge();

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, acceptDownloads: true });
  const page = await context.newPage();
  const saveRequests = [];
  page.on("request", (request) => {
    if (!request.url().includes("/api/documents/save")) return;
    const body = request.postData();
    if (!body) return;
    try {
      saveRequests.push(JSON.parse(body));
    } catch {
      saveRequests.push({ raw: body });
    }
  });

  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()}`);

    const editor = await waitForRuntimeIsland(page);
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("/");
    const slash = page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first();
    await slash.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const slashText = await slash.innerText();
    assert(slashText.includes("媒体与附件"), `slash 菜单缺少媒体与附件分组: ${slashText}`);
    assert(slashText.includes("图片"), `slash 菜单缺少图片入口: ${slashText}`);
    assert(slashText.includes("/tp"), `slash 菜单缺少图片快捷码 /tp: ${slashText}`);

    const imageItem = page.locator('[data-testid="slash-item-image"]').first();
    await imageItem.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
    await screenshot(page, "01-slash-image-entry");
    await imageItem.click({ timeout: UI_TIMEOUT_MS });
    await waitForSavedImage(page);
    await screenshot(page, "02-after-image-insert");

    const image = page.locator('.editor-surface .ProseMirror img[src]').first();
    await image.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const selectedImage = document.querySelector('.editor-surface .ProseMirror img.ProseMirror-selectednode[src]');
      const toolbar = document.querySelector('[data-testid="image-floating-toolbar"]');
      return selectedImage instanceof HTMLImageElement
        && toolbar instanceof HTMLElement
        && getComputedStyle(toolbar).display !== "none"
        && toolbar.getBoundingClientRect().width > 0
        && toolbar.getBoundingClientRect().height > 0;
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03-image-floating-toolbar");

    const imageToolbar = page.locator('[data-testid="image-floating-toolbar"]').first();
    await imageToolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    for (const testid of [
      "image-align-left",
      "image-align-center",
      "image-align-right",
      "image-download",
      "image-delete",
    ]) {
      await imageToolbar.locator(`[data-testid="${testid}"]`).first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    }
    assert.equal(await imageToolbar.locator('[data-testid="image-download"]').first().isDisabled(), false, "同源图片下载入口应可用");
    assert.equal(await imageToolbar.locator('[data-testid="image-delete"]').first().isDisabled(), true, "删除图片入口本切片应保持禁用，真实删除保存链后续单列");
    const currentUrlAfterImageSelect = page.url();

    const downloadPromise = page.waitForEvent("download", { timeout: UI_TIMEOUT_MS });
    await imageToolbar.locator('[data-testid="image-download"]').first().click({ timeout: UI_TIMEOUT_MS });
    const download = await downloadPromise;
    const suggestedFilename = download.suggestedFilename();
    assert(suggestedFilename.includes("E24"), `图片下载文件名应来自图片 title/alt: ${suggestedFilename}`);
    assert(/\.svg$/i.test(suggestedFilename), `图片下载文件名应保留 SVG 扩展名: ${suggestedFilename}`);
    await download.delete().catch(() => undefined);
    assert.equal(page.url(), currentUrlAfterImageSelect, "下载图片不应触发页面跳转");

    await imageToolbar.locator('[data-testid="image-align-center"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      const image = document.querySelector('.editor-surface .ProseMirror img[src]');
      const toolbar = document.querySelector('[data-testid="image-floating-toolbar"]');
      return host?.getAttribute("data-runtime-editor-status") === "saved"
        && image instanceof HTMLImageElement
        && image.getAttribute("data-align") === "center"
        && toolbar instanceof HTMLElement
        && toolbar.getAttribute("data-align") === "center";
    }, null, { timeout: UI_TIMEOUT_MS });
    await waitForCondition("等待图片对齐保存请求", () => saveRequests.some((request) => imageAlign(request.tiptapDocument) === "center"));
    await screenshot(page, "03-image-floating-toolbar");

    const imgAttrs = await image.evaluate((img) => ({
      src: img.getAttribute("src"),
      alt: img.getAttribute("alt"),
      title: img.getAttribute("title"),
      dataAlign: img.getAttribute("data-align"),
    }));
    assert.equal(imgAttrs.src, IMAGE_SRC, `图片 src 应保持稳定测试 URL: ${JSON.stringify(imgAttrs)}`);
    assert.equal(imgAttrs.alt, "E24 图片占位", `图片 alt 应由 setImage 写入: ${JSON.stringify(imgAttrs)}`);
    assert.equal(imgAttrs.title, "E24 图片", `图片 title 应由 setImage 写入: ${JSON.stringify(imgAttrs)}`);
    assert.equal(imgAttrs.dataAlign, "center", `图片居中应通过 data-align 写入 DOM: ${JSON.stringify(imgAttrs)}`);
    assert.equal(page.url(), currentUrlAfterImageSelect, "点击图片打开工具条不应触发页面跳转");

    const lastSave = [...saveRequests].reverse().find((request) => imageAlign(request.tiptapDocument) === "center") || saveRequests.at(-1);
    assert(lastSave?.tiptapDocument, `图片插入后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
    assert.equal(imageSrc(lastSave.tiptapDocument), IMAGE_SRC, `保存请求 Tiptap JSON 必须包含 image attrs.src: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
    assert.equal(imageAlign(lastSave.tiptapDocument), "center", `保存请求 Tiptap JSON 必须保留 image data-align: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);

    const contentAfterImage = await loadDocumentContent(target, "读取图片保存后的正文");
    const savedContent = contentAfterImage?.result?.content;
    assert.equal(imageSrc(savedContent), IMAGE_SRC, `/api/documents/content 必须保留 image 真源: ${JSON.stringify(savedContent).slice(0, 1600)}`);
    assert.equal(imageAlign(savedContent), "center", `/api/documents/content 必须保留 image data-align: ${JSON.stringify(savedContent).slice(0, 1600)}`);

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction((expectedSrc) => {
      const image = document.querySelector('.editor-surface .ProseMirror img[src]');
      return image instanceof HTMLImageElement
        && image.getAttribute("src") === expectedSrc
        && image.getAttribute("data-align") === "center"
        && image.naturalWidth > 0
        && image.naturalHeight > 0;
    }, IMAGE_SRC, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "04-after-reload-image");

    console.log(JSON.stringify({ ok: true, baseUrl: BASE_URL, documentId: target.documentId, screenshotDir: SCREENSHOT_DIR }, 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);
  });
}
