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

const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { chromium } = require("playwright");

const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task484-local-folder-page-body-refresh-readback-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}

function documentUrl(root, relativePath) {
  const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", fileUrl(root));
  return url.toString();
}

function markdown(title, lines) {
  return [
    "---",
    `title: ${title}`,
    "---",
    "",
    ...lines,
    "",
  ].join("\n");
}

function writeWorkspaceManifest(root, ownerId) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: `local-ws:${ownerId}:task484`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function openDocument(page, root, relativePath) {
  await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  await page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function readEditorRuntime(page) {
  return page.evaluate(() => {
    const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
    const aggregateNode = document.getElementById("__MNOTE_PAGE_AGGREGATE__");
    let aggregate = null;
    try {
      aggregate = JSON.parse(aggregateNode?.textContent || "null");
    } catch (_) {
      aggregate = null;
    }
    return {
      status: root?.getAttribute("data-runtime-editor-status") || "",
      error: root?.getAttribute("data-runtime-editor-error") || "",
      text: editor?.textContent || "",
      aggregateText: JSON.stringify(aggregate?.body || aggregate || {}),
      syncedAt: aggregateNode?.getAttribute("data-mnote-page-aggregate-synced-at") || "",
    };
  });
}

async function pageBodyWrite(page, root, relativePath, expectedText) {
  const response = await page.evaluate(async ({ documentId, rootUri, text }) => {
    const body = {
      documentId,
      workspaceId: "local-ws:user_real:task484",
      sourceKind: "local_folder",
      rootUri,
      expectedFileVersion: null,
      contentFormat: "editorBlocks",
      editorSource: "task484-smoke",
      content: [
        {
          id: "block-task484-1",
          type: "paragraph",
          content: text,
        },
      ],
      blockCount: 1,
    };
    const res = await fetch("/api/page-body/write", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(body),
    });
    return {
      ok: res.ok,
      status: res.status,
      payload: await res.json().catch(() => null),
    };
  }, { documentId: localMdDocumentId(relativePath), rootUri: fileUrl(root), text: expectedText });
  assert.equal(response.ok, true, `page-body/write 应成功: ${JSON.stringify(response)}`);
  assert.equal(response.payload?.ok, true, `page-body/write payload 应 ok: ${JSON.stringify(response)}`);
  return response.payload.result;
}

async function waitForEditorText(page, text) {
  await page.waitForFunction(
    (expected) => {
      const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
      return (editor?.textContent || "").includes(expected);
    },
    text,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function fetchPageAggregate(page, root, relativePath) {
  return page.evaluate(async ({ documentId, rootUri }) => {
    const url = new URL(`/api/page-aggregate/${encodeURIComponent(documentId)}`, window.location.origin);
    url.searchParams.set("sourceKind", "local_folder");
    url.searchParams.set("rootUri", rootUri);
    const res = await fetch(url.toString(), { headers: { accept: "application/json" } });
    return {
      ok: res.ok,
      status: res.status,
      payload: await res.json().catch(() => null),
    };
  }, { documentId: localMdDocumentId(relativePath), rootUri: fileUrl(root) });
}

async function run() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task484-local-readback-"));
  const relativePath = "readback.md";
  const initialText = "initial task484 readback";
  const token = `task484-page-body-write-${Date.now()}`;
  writeWorkspaceManifest(root, "user_real");
  fs.writeFileSync(path.join(root, relativePath), markdown("Task 484 Readback", [initialText]), "utf8");

  const browser = await chromium.launch({
    headless: true,
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1280, height: 860 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();
  const debug = { root, relativePath, token };

  try {
    await openDocument(page, root, relativePath);
    await waitForEditorText(page, initialText);
    debug.before = await readEditorRuntime(page);

    const saved = await pageBodyWrite(page, root, relativePath, token);
    debug.saved = saved;
    const disk = fs.readFileSync(path.join(root, relativePath), "utf8");
    assert(disk.includes(token), `磁盘应写入新正文: ${disk}`);

    const aggregateBeforeReload = await fetchPageAggregate(page, root, relativePath);
    debug.aggregateBeforeReload = aggregateBeforeReload;
    assert(
      JSON.stringify(aggregateBeforeReload.payload || {}).includes(token),
      `刷新前 Page Aggregate 应读回新正文: ${JSON.stringify(aggregateBeforeReload)}`,
    );

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await waitForEditorText(page, token);
    debug.afterReload = await readEditorRuntime(page);

    const aggregateAfterReload = await fetchPageAggregate(page, root, relativePath);
    debug.aggregateAfterReload = aggregateAfterReload;
    assert(
      JSON.stringify(aggregateAfterReload.payload || {}).includes(token),
      `刷新后 Page Aggregate 应读回新正文: ${JSON.stringify(aggregateAfterReload)}`,
    );

    const result = {
      ok: true,
      root,
      relativePath,
      token,
      saved,
      beforeText: debug.before.text,
      afterReloadText: debug.afterReload.text,
      resultPath: RESULT_PATH,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(`ok task484-local-folder-page-body-refresh-readback-smoke ${RESULT_PATH}`);
  } catch (error) {
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({
      ok: false,
      error: String(error && error.stack || error),
      debug,
    }, null, 2)}\n`, "utf8");
    throw error;
  } finally {
    await browser.close().catch(() => {});
    fs.rmSync(root, { recursive: true, force: true });
  }
}

run().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
