function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { SUCCESS_CODES, NOT_APPLICABLE_CODES, ERROR_CODES } from "./type";

/**
 * 策略模型 - 核心实现
 *
 * 完全业务无关的通用策略引擎
 * 支持条件评估、动作匹配、结果返回
 */

// ============================================
// 策略引擎实现
// ============================================

/**
 * 策略引擎
 *
 * 核心职责：
 * 1. 递归评估条件组
 * 2. 收集满足条件的 actionIds
 * 3. 根据 actionIds 获取 ActionEffect 对象
 * 4. 按 priority 排序返回
 */
export var StrategyEngine = /*#__PURE__*/function () {
  function StrategyEngine() {
    var _options$debug, _options$enableTrace, _options$operatorHand, _options$errorHandler;
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    _classCallCheck(this, StrategyEngine);
    _defineProperty(this, "options", void 0);
    _defineProperty(this, "operatorHandlers", void 0);
    this.options = {
      debug: (_options$debug = options.debug) !== null && _options$debug !== void 0 ? _options$debug : false,
      enableTrace: (_options$enableTrace = options.enableTrace) !== null && _options$enableTrace !== void 0 ? _options$enableTrace : false,
      operatorHandlers: (_options$operatorHand = options.operatorHandlers) !== null && _options$operatorHand !== void 0 ? _options$operatorHand : {},
      errorHandler: (_options$errorHandler = options.errorHandler) !== null && _options$errorHandler !== void 0 ? _options$errorHandler : function (error) {
        return console.error(error);
      }
    };

    // 初始化内置运算符处理器
    this.operatorHandlers = new Map(Object.entries(this.options.operatorHandlers));
    this.initializeBuiltInOperators();
  }

  /**
   * 评估策略
   */
  _createClass(StrategyEngine, [{
    key: "evaluate",
    value: function evaluate(config, context) {
      var startTime = Date.now();
      var trace = {
        steps: [],
        duration: 0,
        errors: []
      };
      try {
        // 验证配置
        this.validateConfig(config);
        if (this.options.enableTrace) {
          trace.steps.push({
            step: 'validate_config',
            status: 'success',
            duration: Date.now() - startTime
          });
        }

        // 递归评估条件组，收集 actionIds
        var evaluateStart = Date.now();
        var evaluationResult = this.evaluateConditionGroup(config.conditions, context);
        if (this.options.enableTrace) {
          trace.steps.push({
            step: 'evaluate_conditions',
            status: 'success',
            duration: Date.now() - evaluateStart,
            details: {
              satisfied: evaluationResult.satisfied,
              collectedActionIds: evaluationResult.actionIds
            }
          });
        }

        // 根据 actionIds 获取 ActionEffect 对象
        var actionStart = Date.now();
        var matchedActions = this.getActionsByIds(evaluationResult.actionIds, config.actions);
        if (this.options.enableTrace) {
          trace.steps.push({
            step: 'get_actions',
            status: 'success',
            duration: Date.now() - actionStart,
            details: {
              matchedCount: matchedActions.length
            }
          });
        }

        // 按 priority 排序（降序）
        var sortStart = Date.now();
        var sortedActions = this.sortActionsByPriority(matchedActions);
        if (this.options.enableTrace) {
          trace.steps.push({
            step: 'sort_actions',
            status: 'success',
            duration: Date.now() - sortStart
          });
        }

        // 构建结果 - applicable 基于条件是否满足，而不是 actionIds 数量
        var applicable = evaluationResult.satisfied;
        var result = {
          success: true,
          applicable: applicable,
          code: applicable ? SUCCESS_CODES.SUCCESS : NOT_APPLICABLE_CODES.CONDITION_NOT_MET,
          message: applicable ? 'Strategy is applicable' : 'Conditions not met',
          matched: {
            conditions: applicable,
            actionIds: evaluationResult.actionIds,
            details: {}
          },
          matchedActions: sortedActions,
          outputs: {},
          config: config
        };
        trace.duration = Date.now() - startTime;
        if (this.options.enableTrace) {
          result.trace = trace;
        }
        return result;
      } catch (error) {
        var errorMessage = error instanceof Error ? error.message : 'Unknown error';
        if (this.options.enableTrace) {
          var _trace$errors;
          (_trace$errors = trace.errors) === null || _trace$errors === void 0 || _trace$errors.push({
            step: 'evaluation',
            error: errorMessage,
            timestamp: Date.now()
          });
          trace.duration = Date.now() - startTime;
        }
        this.options.errorHandler(error, context);
        return {
          success: false,
          applicable: false,
          code: ERROR_CODES.EVALUATION_ERROR,
          message: errorMessage,
          matched: {
            conditions: false,
            actionIds: [],
            details: {}
          },
          matchedActions: [],
          outputs: {},
          trace: this.options.enableTrace ? trace : undefined,
          config: config
        };
      }
    }

    /**
     * 递归评估条件组
     *
     * @param group 条件组
     * @param context 运行时上下文
     * @returns 评估结果对象，包含条件是否满足和收集到的 actionIds
     */
  }, {
    key: "evaluateConditionGroup",
    value: function evaluateConditionGroup(group, context) {
      var collectedActionIds = [];

      // 评估当前层的 operator 和 rules
      var isCurrentLayerSatisfied = this.evaluateGroupLogic(group, context);

      // 如果当前层条件满足
      if (isCurrentLayerSatisfied) {
        // 收集当前层的 actionIds
        collectedActionIds.push.apply(collectedActionIds, _toConsumableArray(group.actionIds));

        // 递归评估嵌套的 ConditionGroup，收集嵌套层的 actionIds
        var _iterator = _createForOfIteratorHelper(group.rules),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var rule = _step.value;
            if (this.isConditionGroup(rule)) {
              var nestedResult = this.evaluateConditionGroup(rule, context);
              collectedActionIds.push.apply(collectedActionIds, _toConsumableArray(nestedResult.actionIds));
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
      return {
        satisfied: isCurrentLayerSatisfied,
        actionIds: collectedActionIds
      };
    }

    /**
     * 评估条件组的逻辑运算
     */
  }, {
    key: "evaluateGroupLogic",
    value: function evaluateGroupLogic(group, context) {
      var _this = this;
      var operator = group.operator,
        rules = group.rules;
      switch (operator) {
        case 'and':
          // 所有规则都必须满足
          return rules.every(function (rule) {
            return _this.evaluateRule(rule, context);
          });
        case 'or':
          // 任一规则满足即可
          return rules.some(function (rule) {
            return _this.evaluateRule(rule, context);
          });
        case 'not':
          // 对第一个规则取反
          if (rules.length === 0) return false;
          return !this.evaluateRule(rules[0], context);
        default:
          throw new Error("Unknown operator: ".concat(operator));
      }
    }

    /**
     * 评估单个规则
     */
  }, {
    key: "evaluateRule",
    value: function evaluateRule(rule, context) {
      // 如果是嵌套的条件组，递归评估
      if (this.isConditionGroup(rule)) {
        return this.evaluateGroupLogic(rule, context);
      }

      // 原子条件规则
      var conditionRule = rule;

      // Code 模式：使用 eval 执行
      if (conditionRule.type === 'code' && conditionRule.code) {
        return this.evaluateCodeCondition(conditionRule.code, context);
      }

      // Operator 模式：标准运算符判断
      return this.evaluateOperatorCondition(conditionRule, context);
    }

    /**
     * 评估代码模式条件
     */
  }, {
    key: "evaluateCodeCondition",
    value: function evaluateCodeCondition(code, context) {
      try {
        // 将 context 解构到作用域中，方便代码直接使用
        var entities = context.entities,
          attributes = context.attributes,
          metadata = context.metadata;

        // 使用 Function 构造器代替 eval，更安全
        var evalFunc = new Function('entities', 'attributes', 'metadata', "return (".concat(code, ")"));
        var result = evalFunc(entities, attributes, metadata);
        return Boolean(result);
      } catch (error) {
        if (this.options.debug) {
          console.error('Code evaluation error:', error);
        }
        return false;
      }
    }

    /**
     * 评估运算符模式条件
     */
  }, {
    key: "evaluateOperatorCondition",
    value: function evaluateOperatorCondition(rule, context) {
      var field = rule.field,
        operator = rule.operator,
        value = rule.value;
      if (!field || !operator) {
        return false;
      }

      // 从 context.attributes 中获取字段值
      var fieldValue = this.getFieldValue(field, context);

      // 使用运算符处理器
      var handler = this.operatorHandlers.get(operator);
      if (handler) {
        return handler(fieldValue, value, rule);
      }

      // 回退到内置运算符
      return this.evaluateBuiltInOperator(fieldValue, operator, value);
    }

    /**
     * 获取字段值
     */
  }, {
    key: "getFieldValue",
    value: function getFieldValue(field, context) {
      // 支持点号路径，如 "order.total"
      var path = field.split('.');
      var value = context.attributes;
      var _iterator2 = _createForOfIteratorHelper(path),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var key = _step2.value;
          if (value && _typeof(value) === 'object' && key in value) {
            value = value[key];
          } else {
            return undefined;
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      return value;
    }

    /**
     * 评估内置运算符
     */
  }, {
    key: "evaluateBuiltInOperator",
    value: function evaluateBuiltInOperator(fieldValue, operator, compareValue) {
      switch (operator) {
        // 比较运算符
        case '=':
        case '==':
          return fieldValue == compareValue;
        case '!=':
          return fieldValue != compareValue;
        case '>':
          return fieldValue > compareValue;
        case '>=':
          return fieldValue >= compareValue;
        case '<':
          return fieldValue < compareValue;
        case '<=':
          return fieldValue <= compareValue;

        // 集合运算符
        case 'in':
          return Array.isArray(compareValue) && compareValue.includes(fieldValue);
        case 'not_in':
          return Array.isArray(compareValue) && !compareValue.includes(fieldValue);
        case 'contains':
          if (Array.isArray(fieldValue)) {
            return fieldValue.includes(compareValue);
          }
          if (typeof fieldValue === 'string') {
            return fieldValue.includes(compareValue);
          }
          return false;
        case 'not_contains':
          if (Array.isArray(fieldValue)) {
            return !fieldValue.includes(compareValue);
          }
          if (typeof fieldValue === 'string') {
            return !fieldValue.includes(compareValue);
          }
          return true;

        // 字符串运算符
        case 'starts_with':
          return typeof fieldValue === 'string' && fieldValue.startsWith(compareValue);
        case 'ends_with':
          return typeof fieldValue === 'string' && fieldValue.endsWith(compareValue);
        case 'regex':
          return typeof fieldValue === 'string' && new RegExp(compareValue).test(fieldValue);

        // 范围运算符
        case 'between':
          if (!Array.isArray(compareValue) || compareValue.length !== 2) return false;
          return fieldValue >= compareValue[0] && fieldValue <= compareValue[1];

        // 逻辑运算符
        case 'is_null':
          return fieldValue === null || fieldValue === undefined;
        case 'is_not_null':
          return fieldValue !== null && fieldValue !== undefined;
        case 'is_empty':
          if (Array.isArray(fieldValue)) return fieldValue.length === 0;
          if (typeof fieldValue === 'string') return fieldValue.length === 0;
          if (_typeof(fieldValue) === 'object') return Object.keys(fieldValue).length === 0;
          return !fieldValue;
        case 'is_not_empty':
          if (Array.isArray(fieldValue)) return fieldValue.length > 0;
          if (typeof fieldValue === 'string') return fieldValue.length > 0;
          if (_typeof(fieldValue) === 'object') return Object.keys(fieldValue).length > 0;
          return Boolean(fieldValue);

        // 商品匹配运算符
        case 'product_match':
          return this.evaluateProductMatch(fieldValue, compareValue);

        // 对象包含运算符（兼容旧配置）
        case 'object_in':
          return this.evaluateProductMatch(fieldValue, compareValue);
        default:
          throw new Error("Unsupported operator: ".concat(operator));
      }
    }

    /**
     * 根据 actionIds 获取 ActionEffect 对象
     */
  }, {
    key: "getActionsByIds",
    value: function getActionsByIds(actionIds, actions) {
      var matchedActions = [];
      var actionMap = new Map(actions.map(function (action) {
        return [action.id, action];
      }));
      var _iterator3 = _createForOfIteratorHelper(actionIds),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var id = _step3.value;
          var action = actionMap.get(id);
          if (action) {
            matchedActions.push(action);
          } else {
            // 找不到的 ID 记录警告
            if (this.options.debug) {
              console.warn("Action with id \"".concat(id, "\" not found in actions array"));
            }
          }
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
      return matchedActions;
    }

    /**
     * 按 priority 排序（降序）
     */
  }, {
    key: "sortActionsByPriority",
    value: function sortActionsByPriority(actions) {
      return _toConsumableArray(actions).sort(function (a, b) {
        var _a$priority, _b$priority;
        var priorityA = (_a$priority = a.priority) !== null && _a$priority !== void 0 ? _a$priority : 0;
        var priorityB = (_b$priority = b.priority) !== null && _b$priority !== void 0 ? _b$priority : 0;
        return priorityB - priorityA; // 降序
      });
    }

    /**
     * 判断是否为条件组
     */
  }, {
    key: "isConditionGroup",
    value: function isConditionGroup(rule) {
      return 'operator' in rule && 'rules' in rule && Array.isArray(rule.rules);
    }

    /**
     * 验证配置
     */
  }, {
    key: "validateConfig",
    value: function validateConfig(config) {
      if (!config) {
        throw new Error('Strategy config is required');
      }
      if (!config.metadata || !config.metadata.id) {
        throw new Error('Strategy metadata.id is required');
      }
      if (!config.conditions) {
        throw new Error('Strategy conditions is required');
      }
      if (!Array.isArray(config.actions)) {
        throw new Error('Strategy actions must be an array');
      }
    }

    /**
     * 初始化内置运算符处理器
     */
  }, {
    key: "initializeBuiltInOperators",
    value: function initializeBuiltInOperators() {
      // 内置运算符已经在 evaluateBuiltInOperator 中实现
      // 这里可以添加自定义的运算符处理器
    }

    /**
     * 评估商品匹配运算符
     *
     * 匹配规则：
     * - 首先匹配 product_id
     * - 如果配置的 product_variant_id = 0，只需要 product_id 匹配（表示任意变体）
     * - 如果配置的 product_variant_id != 0，还需要 product_variant_id 精确匹配
     *
     * @param fieldValue 实际商品 { product_id: number, product_variant_id: number }
     * @param configValue 配置的商品列表 Array<{ product_id: number, product_variant_id: number }>
     * @returns 是否匹配
     */
  }, {
    key: "evaluateProductMatch",
    value: function evaluateProductMatch(fieldValue, configValue) {
      var _fieldValue$product_v;
      // 确保 configValue 是数组
      if (!Array.isArray(configValue)) {
        return false;
      }

      // 确保 fieldValue 是有效的商品对象
      if (!fieldValue || _typeof(fieldValue) !== 'object' || typeof fieldValue.product_id !== 'number') {
        return false;
      }
      var actualProductId = fieldValue.product_id;
      var actualVariantId = (_fieldValue$product_v = fieldValue.product_variant_id) !== null && _fieldValue$product_v !== void 0 ? _fieldValue$product_v : 0;

      // 遍历配置的商品列表，检查是否有匹配
      return configValue.some(function (item) {
        var _item$product_variant;
        // 验证配置项格式
        if (!item || typeof item.product_id !== 'number') {
          return false;
        }
        var configProductId = item.product_id;
        var configVariantId = (_item$product_variant = item.product_variant_id) !== null && _item$product_variant !== void 0 ? _item$product_variant : 0;

        // 首先检查 product_id 是否匹配
        if (configProductId !== actualProductId) {
          return false;
        }

        // 如果配置的 product_variant_id = 0，只需要 product_id 匹配
        if (configVariantId === 0) {
          return true;
        }

        // 否则需要 product_variant_id 精确匹配
        return configVariantId === actualVariantId;
      });
    }

    /**
     * 注册自定义运算符
     */
  }, {
    key: "registerOperator",
    value: function registerOperator(operator, handler) {
      this.operatorHandlers.set(operator, handler);
    }

    /**
     * 获取调试信息
     */
  }, {
    key: "getDebugInfo",
    value: function getDebugInfo() {
      return {
        debug: this.options.debug,
        enableTrace: this.options.enableTrace,
        registeredOperators: Array.from(this.operatorHandlers.keys())
      };
    }
  }]);
  return StrategyEngine;
}();
export * from "./adapter";

// ============================================
// 导出工具函数
// ============================================

/**
 * 创建策略引擎实例
 */
export function createStrategyEngine(options) {
  return new StrategyEngine(options);
}

/**
 * 快速评估（使用默认引擎配置）
 */
export function evaluate(config, context) {
  var engine = new StrategyEngine();
  return engine.evaluate(config, context);
}