package com.hotent.util;
import java.util.Stack;
import java.util.regex.Pattern;

/**
 * 检查四则运算表达式是否正确
 */
public class CustomExpressionValidator {

    private static final Pattern VARIABLE_PATTERN = Pattern.compile("[a-zA-Z_.][a-zA-Z0-9_.]*");
    private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+(\\.\\d+)?");

    public static boolean isValidExpression(String expr) {
        if (expr == null || expr.trim().isEmpty()) {
            return false;
        }

        // 检查括号匹配
        if (!checkParentheses(expr)) {
            return false;
        }

        // 检查运算符使用
        if (!checkOperators(expr)) {
            return false;
        }

        // 检查变量命名
        return checkVariables(expr);
    }

    private static boolean checkParentheses(String expr) {
        Stack<Character> stack = new Stack<>();

        for (char c : expr.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else if (c == ')') {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }
            }
        }

        return stack.isEmpty();
    }

    private static boolean checkOperators(String expr) {
        String cleaned = expr.replaceAll("\\s+", "");

        // 检查开头和结尾不能是运算符（除负号外）
        if (isOperator(cleaned.charAt(0)) && cleaned.charAt(0) != '-') {
            return false;
        }
        if (isOperator(cleaned.charAt(cleaned.length() - 1))) {
            return false;
        }

        // 检查连续的运算符
        for (int i = 0; i < cleaned.length() - 1; i++) {
            char current = cleaned.charAt(i);
            char next = cleaned.charAt(i + 1);

            if (isOperator(current) && isOperator(next) && next != '-') {
                return false;
            }
        }

        return true;
    }

    private static boolean checkVariables(String expr) {
        String[] tokens = expr.split("[+\\-*/()\\s]+");

        for (String token : tokens) {
            if (!token.isEmpty() && !NUMBER_PATTERN.matcher(token).matches() &&
                    !VARIABLE_PATTERN.matcher(token).matches()) {
                return false;
            }
        }

        return true;
    }

    private static boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }

    public static void main(String[] args) {
        String[] testExpressions = {
                "(taiyuan.c1+taiyuan.c2)*(c1/c2)+c1",
                "c1++c2",           // 错误：连续运算符
                "c1+",              // 错误：运算符在结尾
                "(c1+c2",           // 错误：括号不匹配
                "123c4 + 5"         // 错误：无效变量名
        };

        for (String expr : testExpressions) {
            System.out.println(expr + " : " + isValidExpression(expr));
        }
    }
}