package com.usky.rule.engine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 规则 detail JSON 条件评估（简化版）：支持 threshold 比较。
 * 与 leo-rule-engine 中按 identifier + 表达式匹配的思路一致。
 */
public final class RuleConditionEvaluator {

    private RuleConditionEvaluator() {
    }

    /**
     * @param detailJson rule_engine.detail
     * @param value      当前属性值
     */
    public static boolean evaluate(String detailJson, Object value) {
        if (detailJson == null || detailJson.isEmpty()) {
            return false;
        }
        try {
            JSONObject root = JSON.parseObject(detailJson);
            if (root.containsKey("threshold")) {
                double v = toDouble(value);
                double th = root.getDoubleValue("threshold");
                String op = root.getString("op");
                if (op == null) {
                    op = ">=";
                }
                switch (op) {
                    case ">":
                        return v > th;
                    case ">=":
                        return v >= th;
                    case "<":
                        return v < th;
                    case "<=":
                        return v <= th;
                    case "==":
                        return Double.compare(v, th) == 0;
                    default:
                        return v >= th;
                }
            }
            return root.getBooleanValue("match");
        } catch (Exception e) {
            return false;
        }
    }

    private static double toDouble(Object value) {
        if (value == null) {
            return Double.NaN;
        }
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        return Double.parseDouble(String.valueOf(value));
    }
}
