package com.sino.mci.inbound.engine;

import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.MapAccessor;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;

/**
 * SpEL 条件表达式求值器。
 */
public final class SpelConditionEvaluator {

    private static final SpelExpressionParser PARSER = new SpelExpressionParser();

    private SpelConditionEvaluator() {
    }

    /**
     * 对给定表达式进行求值。
     *
     * @param expression SpEL 表达式；为空或空白时返回 {@code true}
     * @param context    流程执行上下文
     * @return 表达式求值结果
     */
    public static boolean evaluate(String expression, FlowContext context) {
        if (!StringUtils.hasText(expression)) {
            return true;
        }
        try {
            StandardEvaluationContext evaluationContext = new StandardEvaluationContext(context.toEvaluationMap());
            evaluationContext.addPropertyAccessor(new MapAccessor());
            Boolean result = PARSER.parseExpression(expression).getValue(evaluationContext, Boolean.class);
            return Boolean.TRUE.equals(result);
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to evaluate condition expression: " + expression, e);
        }
    }
}
