// MNote debug /tree shell filetree row normalization helpers.

import {
  normalizeTreeShellNumber,
  normalizeTreeShellText,
} from "./tree-shell-state-runtime.js";

export function buildFileTreeRuntimeEnvironment(runtimeContext) {
  const fileTreeRowById = runtimeContext.fileTreeRowById || new Map();
  return {
    visibleRowIds: Array.isArray(runtimeContext.visibleFileTreeRowIds)
      ? runtimeContext.visibleFileTreeRowIds
      : [],
    rows: Array.from(fileTreeRowById.values()).map((entry) => ({
      rowId: entry.rowId,
      rowKind: entry.rowKind,
      documentId: entry.documentId || null,
      assetId: entry.assetId || null,
    })),
    rootUri: runtimeContext.sourceKind === "local_folder" ? runtimeContext.rootUri || null : null,
  };
}

export function compareTreeShellItems(left, right) {
  const byPosition = left.position - right.position;
  if (byPosition !== 0) return byPosition;
  return left.title.localeCompare(right.title, "zh-CN");
}

export function normalizeTreeShellResourceMeta(value) {
  if (!value || typeof value !== "object") {
    return {
      resourceKind: "",
      documentId: "",
      assetId: "",
      assetKind: "",
      objectIdentity: null,
      blockAssetRelation: null,
    };
  }
  const objectIdentity =
    value?.objectIdentity && typeof value.objectIdentity === "object"
      ? value.objectIdentity
      : null;
  const blockAssetRelation =
    value?.blockAssetRelation && typeof value.blockAssetRelation === "object"
      ? value.blockAssetRelation
      : null;
  return {
    resourceKind: normalizeTreeShellText(value?.resourceKind),
    documentId: normalizeTreeShellText(value?.documentId),
    assetId: normalizeTreeShellText(value?.assetId),
    assetKind: normalizeTreeShellText(value?.assetKind),
    objectIdentity,
    blockAssetRelation,
  };
}

export function normalizeTreeShellRowKind(value) {
  const normalized = normalizeTreeShellText(value).toLowerCase();
  if (normalized === "index") return "index";
  if (normalized === "asset") return "asset";
  if (normalized === "folder") return "folder";
  if (normalized === "markdown") return "markdown";
  if (normalized === "asset_folder") return "asset_folder";
  return "document";
}

export function normalizeTreeShellTreeItems(items, options = {}) {
  const excludedIds = options.excludedIds instanceof Set ? options.excludedIds : new Set();
  return Array.isArray(items)
    ? items
        .map((item) => {
          const nodeId = normalizeTreeShellText(item?.nodeId);
          const resourceMeta = normalizeTreeShellResourceMeta(item?.resourceMeta);
          const rowKind = normalizeTreeShellRowKind(item?.rowKind);
          const fallbackRowId =
            rowKind === "index"
              ? `index:${resourceMeta.documentId || nodeId.replace(/^index:/, "")}`
              : rowKind === "asset"
                ? `asset:${resourceMeta.assetId || nodeId.replace(/^asset:/, "")}`
                : rowKind === "asset_folder"
                  ? `asset-folder:${resourceMeta.assetId || nodeId.replace(/^asset-folder:/, "")}`
                  : `doc:${resourceMeta.documentId || nodeId}`;
          return {
            rowId: normalizeTreeShellText(item?.rowId, fallbackRowId),
            rowKind,
            nodeId,
            parentNodeId: normalizeTreeShellText(item?.parentNodeId) || null,
            title: normalizeTreeShellText(item?.title, rowKind === "index" ? "index.md" : "无标题"),
            depth: normalizeTreeShellNumber(item?.depth, 0),
            childCount: normalizeTreeShellNumber(item?.childCount, 0),
            position: normalizeTreeShellNumber(item?.position),
            expandedByDefault: item?.expandedByDefault !== false,
            iconHint: normalizeTreeShellText(item?.iconHint),
            capabilities: Array.isArray(item?.capabilities)
              ? item.capabilities
                  .map((capability) => normalizeTreeShellText(capability))
                  .filter(Boolean)
              : [],
            resourceMeta,
          };
        })
        .filter((item) => item.nodeId && !excludedIds.has(item.nodeId))
    : [];
}

export function getFileTreeRowDocumentId(item) {
  if (!item) return "";
  if (item.rowKind === "document" || item.rowKind === "markdown") return item.nodeId;
  if (item.rowKind === "index") return item.nodeId.replace(/^index:/, "");
  return "";
}

export function getFileTreeRowOwnerDocumentId(item) {
  if (!item) return "";
  if (item.resourceMeta?.documentId) return item.resourceMeta.documentId;
  return getFileTreeRowDocumentId(item);
}

export function getFileTreeRowAssetId(item) {
  if (!item) return "";
  if (item.resourceMeta?.assetId) return item.resourceMeta.assetId;
  if (item.rowKind === "asset") return item.nodeId.replace(/^asset:/, "");
  if (item.rowKind === "asset_folder") return item.nodeId.replace(/^asset-folder:/, "");
  return "";
}

export function getFileTreeRowIconKind(item) {
  if (!item) return "file";
  const iconHint = normalizeTreeShellText(item.iconHint).toLowerCase();
  if (iconHint === "mindmap") return "mindmap";
  if (iconHint === "table") return "table";
  if (iconHint === "index") return "index";
  if (iconHint === "page") return "page";
  if (iconHint === "pdf") return "pdf";
  if (iconHint === "office" || iconHint === "onlyoffice") return "office";
  if (iconHint === "word" || iconHint === "ppt" || iconHint === "sheet") return iconHint;
  if (iconHint === "image") return "image";
  if (iconHint === "code" || iconHint === "web" || iconHint === "config") return iconHint;
  if (item.rowKind === "document") return "page";
  if (item.rowKind === "folder") return "folder";
  if (item.rowKind === "markdown") return "markdown";
  if (item.rowKind === "index") return "index";
  if (item.rowKind === "asset_folder") return "mindmap";
  if (item.resourceMeta?.resourceKind === "table") return "table";
  if (item.resourceMeta?.resourceKind === "mindmap") return "mindmap";
  if (item.resourceMeta?.resourceKind === "office") return "office";
  if (item.resourceMeta?.resourceKind === "pdf") return "pdf";
  return "file";
}

export function getFileTreeRowMetaLabel(item) {
  if (!item) return "";
  if (item.rowKind === "document") {
    return `${getFileTreeRowDocumentId(item)} · 页面`;
  }
  if (item.rowKind === "folder") {
    return "本地文件夹";
  }
  if (item.rowKind === "markdown") {
    return `${getFileTreeRowDocumentId(item)} · Markdown`;
  }
  if (item.rowKind === "index") {
    return "页面正文";
  }
  if (item.rowKind === "asset_folder") {
    return `${item.resourceMeta?.resourceKind || "mindmap"} · 资源目录`;
  }
  return `${item.resourceMeta?.resourceKind || item.resourceMeta?.assetKind || "asset"} · ${getFileTreeRowAssetId(item)}`;
}
