/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var matching_exports = {};
__export(matching_exports, {
  hasExplicitSubModelKey: () => hasExplicitSubModelKey,
  matchesObjectChild: () => matchesObjectChild,
  normalizeChildren: () => normalizeChildren,
  planArrayChildMatches: () => planArrayChildMatches
});
module.exports = __toCommonJS(matching_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
function normalizeChildren(input) {
  if (!input) {
    return [];
  }
  return import_lodash.default.castArray(input).filter(Boolean);
}
function hasExplicitSubModelKey(node, key) {
  return !!(node == null ? void 0 : node.subModels) && Object.prototype.hasOwnProperty.call(node.subModels, key);
}
function matchesObjectChild(currentChild, desiredChild) {
  return currentChild.uid === desiredChild.uid || !desiredChild.uid && currentChild.use === desiredChild.use;
}
function planArrayChildMatches(currentChildren, desiredChildren, parentUse, subKey) {
  const matchesByDesiredIndex = /* @__PURE__ */ new Map();
  const matchedCurrentUids = /* @__PURE__ */ new Set();
  const remainingDesiredByUse = /* @__PURE__ */ new Map();
  for (const [desiredIndex, desiredChild] of desiredChildren.entries()) {
    const matchedCurrent = findExactArrayChildMatch(currentChildren, desiredChild, matchedCurrentUids);
    if (matchedCurrent) {
      matchesByDesiredIndex.set(desiredIndex, matchedCurrent);
      if (matchedCurrent.uid) {
        matchedCurrentUids.add(matchedCurrent.uid);
      }
      continue;
    }
    if ((desiredChild == null ? void 0 : desiredChild.use) && !desiredChild.uid) {
      const desiredIndexes = remainingDesiredByUse.get(desiredChild.use) || [];
      desiredIndexes.push(desiredIndex);
      remainingDesiredByUse.set(desiredChild.use, desiredIndexes);
    }
  }
  const remainingCurrentByUse = /* @__PURE__ */ new Map();
  for (const currentChild of currentChildren) {
    if (!(currentChild == null ? void 0 : currentChild.use) || matchedCurrentUids.has(currentChild.uid || "")) {
      continue;
    }
    const currentGroup = remainingCurrentByUse.get(currentChild.use) || [];
    currentGroup.push(currentChild);
    remainingCurrentByUse.set(currentChild.use, currentGroup);
  }
  const uses = /* @__PURE__ */ new Set([...remainingCurrentByUse.keys(), ...remainingDesiredByUse.keys()]);
  for (const use of uses) {
    const currentGroup = remainingCurrentByUse.get(use) || [];
    const desiredIndexes = remainingDesiredByUse.get(use) || [];
    const shouldReuseByOrder = currentGroup.length > 1 || desiredIndexes.length > 1;
    if (currentGroup.length > 0 && desiredIndexes.length > 0 && currentGroup.length !== desiredIndexes.length && shouldReuseByOrder) {
      throw new import_errors.FlowSurfaceBadRequestError(
        `flowSurfaces apply cannot safely match duplicate '${use}' nodes under '${parentUse}.${subKey}' without explicit uid or signature`
      );
    }
    if (!shouldReuseByOrder) {
      continue;
    }
    const reuseCount = Math.min(currentGroup.length, desiredIndexes.length);
    for (let index = 0; index < reuseCount; index += 1) {
      const currentChild = currentGroup[index];
      const desiredIndex = desiredIndexes[index];
      matchesByDesiredIndex.set(desiredIndex, currentChild);
      if (currentChild == null ? void 0 : currentChild.uid) {
        matchedCurrentUids.add(currentChild.uid);
      }
    }
  }
  return {
    matchesByDesiredIndex,
    matchedCurrentUids
  };
}
function findExactArrayChildMatch(currentChildren, desiredChild, matchedCurrent) {
  if (desiredChild.uid) {
    return currentChildren.find((item) => (item == null ? void 0 : item.uid) === desiredChild.uid);
  }
  const desiredStrongSignature = getStrongNodeSignature(desiredChild);
  if (desiredStrongSignature) {
    return currentChildren.find(
      (item) => !matchedCurrent.has(item.uid || "") && getStrongNodeSignature(item) === desiredStrongSignature
    );
  }
  const desiredWeakSignature = getWeakNodeSignature(desiredChild);
  if (desiredWeakSignature) {
    return currentChildren.find(
      (item) => !matchedCurrent.has(item.uid || "") && getWeakNodeSignature(item) === desiredWeakSignature
    );
  }
  return void 0;
}
function getStrongNodeSignature(node) {
  if (!(node == null ? void 0 : node.use)) {
    return null;
  }
  const resourceInit = import_lodash.default.get(node, ["stepParams", "resourceSettings", "init"]);
  if ((resourceInit == null ? void 0 : resourceInit.dataSourceKey) || (resourceInit == null ? void 0 : resourceInit.collectionName) || (resourceInit == null ? void 0 : resourceInit.associationName) || (resourceInit == null ? void 0 : resourceInit.associationPathName) || !import_lodash.default.isUndefined(resourceInit == null ? void 0 : resourceInit.sourceId)) {
    return [
      "resource",
      node.use,
      resourceInit.dataSourceKey || "",
      resourceInit.collectionName || "",
      resourceInit.associationName || "",
      resourceInit.associationPathName || "",
      import_lodash.default.isUndefined(resourceInit.sourceId) ? "" : String(resourceInit.sourceId)
    ].join(":");
  }
  const fieldInit = import_lodash.default.get(node, ["stepParams", "fieldSettings", "init"]) || import_lodash.default.get(node, ["subModels", "field", "stepParams", "fieldSettings", "init"]);
  if (fieldInit == null ? void 0 : fieldInit.fieldPath) {
    const innerFieldUse = import_lodash.default.get(node, ["subModels", "field", "use"]) || "";
    return [
      "field",
      node.use,
      innerFieldUse,
      fieldInit.dataSourceKey || "",
      fieldInit.collectionName || "",
      fieldInit.associationPathName || "",
      fieldInit.fieldPath
    ].join(":");
  }
  if (node.use === "TableActionsColumnModel") {
    return "slot:table-actions-column";
  }
  return null;
}
function getWeakNodeSignature(node) {
  if (!(node == null ? void 0 : node.use)) {
    return null;
  }
  const title = import_lodash.default.get(node, ["stepParams", "pageTabSettings", "tab", "title"]) || import_lodash.default.get(node, ["stepParams", "buttonSettings", "general", "title"]) || import_lodash.default.get(node, ["props", "title"]);
  if (typeof title === "string" && title.trim()) {
    return ["title", node.use, title.trim()].join(":");
  }
  return null;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  hasExplicitSubModelKey,
  matchesObjectChild,
  normalizeChildren,
  planArrayChildMatches
});
