#!/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", "task443-local-markdown-asset-upload-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"]
    .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));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

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}:task443`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function quickLogin(page) {
  await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
  if (await quickLoginButton.count()) {
    await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS });
  }
}

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 uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) {
  return await page.evaluate(
    async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => {
      const form = new FormData();
      form.append("rootUri", rootUri);
      form.append("documentId", documentId);
      form.append("kind", kind);
      form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType }));
      const response = await fetch("/api/local-folder/assets/upload", {
        method: "POST",
        body: form,
      });
      const payload = await response.json().catch(() => null);
      if (!response.ok || !payload || payload.ok !== true) {
        throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`);
      }
      return payload.asset;
    },
    {
      rootUri: fileUrl(root),
      documentId,
      fileName,
      mimeType,
      bytes: Array.from(bytes),
      kind,
    },
  );
}

async function fetchAggregate(page, root, documentId) {
  return await page.evaluate(
    async ({ rootUri, documentId }) => {
      const url = new URL(`/api/page-aggregate/${encodeURIComponent(documentId)}`, window.location.origin);
      url.searchParams.set("sourceKind", "local_folder");
      url.searchParams.set("rootUri", rootUri);
      const response = await fetch(url.toString(), { cache: "no-store" });
      const payload = await response.json().catch(() => null);
      if (!response.ok || !payload || payload.ok !== true) {
        throw new Error(`aggregate_failed_${response.status}:${JSON.stringify(payload)}`);
      }
      return payload.result;
    },
    { rootUri: fileUrl(root), documentId },
  );
}

async function saveBody(page, root, documentId, workspaceId, expectedFileVersion, imagePath, attachmentPath) {
  return await page.evaluate(
    async ({ rootUri, documentId, workspaceId, expectedFileVersion, imagePath, attachmentPath }) => {
      const response = await fetch("/api/page-body/write", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          documentId,
          workspaceId,
          sourceKind: "local_folder",
          rootUri,
          expectedFileVersion,
          contentFormat: "editorBlocks",
          editorSource: "task443-smoke",
          content: [
            { type: "heading", props: { level: 1 }, content: [{ type: "text", text: "Asset Smoke" }] },
            { type: "image", props: { src: imagePath, alt: "task443 图片", title: "task443 图片" } },
            { type: "media", props: { name: "task443-spec.pdf", sourcePath: attachmentPath } },
          ],
        }),
      });
      const payload = await response.json().catch(() => null);
      if (!response.ok || !payload || payload.ok !== true) {
        throw new Error(`save_failed_${response.status}:${JSON.stringify(payload)}`);
      }
      return payload.result;
    },
    { rootUri: fileUrl(root), documentId, workspaceId, expectedFileVersion, imagePath, attachmentPath },
  );
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task443-local-assets-"));
  const relativePath = "README.md";
  const documentId = localMdDocumentId(relativePath);
  writeWorkspaceManifest(root, "user_real");
  fs.writeFileSync(
    path.join(root, relativePath),
    ["---", "title: Asset Smoke", "---", "", "# Asset Smoke", "", "初始正文", ""].join("\n"),
    "utf8",
  );

  const browser = await chromium.launch({
    headless: true,
    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();
  try {
    await quickLogin(page);
    await openDocument(page, root, relativePath);
    const imageAsset = await uploadLocalAsset(
      page,
      root,
      documentId,
      "task443-image.png",
      "image/png",
      Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
      "image",
    );
    const attachmentAsset = await uploadLocalAsset(
      page,
      root,
      documentId,
      "task443-spec.pdf",
      "application/pdf",
      Buffer.from("%PDF-1.4\n% task443\n", "utf8"),
      "attachment",
    );

    const aggregate = await fetchAggregate(page, root, documentId);
    await saveBody(
      page,
      root,
      documentId,
      aggregate.identity.workspaceId || aggregate.identity.workspace_id || "",
      aggregate.body.fileVersion || aggregate.body.conflictDetectionKey || null,
      imageAsset.sourcePath,
      attachmentAsset.sourcePath,
    );
    await openDocument(page, root, relativePath);
    await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const restoredAggregate = await fetchAggregate(page, root, documentId);
    const restoredBody = JSON.stringify(restoredAggregate.body && restoredAggregate.body.content || []);
    assert(restoredBody.includes("README/task443-image.png"), restoredBody);
    assert(restoredBody.includes("README/task443-spec.pdf"), restoredBody);
    const markdown = fs.readFileSync(path.join(root, relativePath), "utf8");
    assert(markdown.includes("![task443 图片](README/task443-image.png)"), markdown);
    assert(markdown.includes("[task443-spec.pdf](README/task443-spec.pdf)"), markdown);
    assert(!markdown.includes("/api/media/"), markdown);
    assert(!markdown.includes("assetId="), markdown);
    assert(fs.existsSync(path.join(root, "README", "task443-image.png")));
    assert(fs.existsSync(path.join(root, "README", "task443-spec.pdf")));
    await page.waitForFunction(() => {
      const tree = document.getElementById("sidebar-file-tree-root");
      const text = tree ? tree.textContent || "" : "";
      return text.includes("task443-image.png") && text.includes("task443-spec.pdf");
    }, null, { timeout: UI_TIMEOUT_MS });
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({
      ok: true,
      root,
      markdownPath: path.join(root, relativePath),
      imageSourcePath: imageAsset.sourcePath,
      attachmentSourcePath: attachmentAsset.sourcePath,
    }, null, 2)}\n`, "utf8");
    console.log(`task443 local markdown asset upload smoke passed: ${RESULT_PATH}`);
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error && error.stack ? error.stack : error);
  process.exit(1);
});
