package service.generator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public abstract class AbstractQuestionGenerator implements QuestionGenerator {
    protected final Random rand = new Random();
    private static final char[] OPS = {'+', '-', '×', '÷'};

    protected String buildComplexExpression(List<String> operands) {
        int numOperands = operands.size();
        if (numOperands < 2) return operands.get(0); // 如果只有一个操作数，直接返回

        List<Character> operators = new ArrayList<>();
        for (int i = 0; i < numOperands - 1; i++) {
            operators.add(OPS[rand.nextInt(OPS.length)]);
        }

        int parensType = rand.nextInt(5); // 增加不加括号的概率

        switch (parensType) {
            case 1: // 单括号 (a op b) op c ...
                if (numOperands >= 3) {
                    Collections.swap(operands, 0, rand.nextInt(numOperands));
                    Collections.swap(operands, 1, rand.nextInt(numOperands));
                    return String.format("(%s %c %s) %c %s", operands.get(0), operators.get(0), operands.get(1), operators.get(1), buildRest(operands, operators, 2));
                }
                break;
            case 2: // a op (b op c) op d ...
                if (numOperands >= 3) {
                    return String.format("%s %c (%s %c %s)", operands.get(0), operators.get(0), operands.get(1), operators.get(1), buildRest(operands, operators, 2));
                }
                break;
            case 3: // 双重括号 ((a op b) op c) op d ...
                if (numOperands >= 4) {
                    return String.format("((%s %c %s) %c %s) %c %s", operands.get(0), operators.get(0), operands.get(1), operators.get(1), operands.get(2), operators.get(2), buildRest(operands, operators, 3));
                }
                break;
            case 4: // 双重括号 a op (b op (c op d)) ...
                if (numOperands >= 4) {
                    return String.format("%s %c (%s %c (%s %c %s))", operands.get(0), operators.get(0), operands.get(1), operators.get(1), operands.get(2), operators.get(2), buildRest(operands, operators, 3));
                }
                break;
        }

        // 默认情况：无括号或无法应用括号
        return buildRest(operands, operators, 0);
    }

    private String buildRest(List<String> operands, List<Character> operators, int startIndex) {
        StringBuilder sb = new StringBuilder();
        sb.append(operands.get(startIndex));
        for (int i = startIndex; i < operators.size(); i++) {
            sb.append(" ").append(operators.get(i)).append(" ");
            sb.append(operands.get(i + 1));
        }
        return sb.toString();
    }
}