package service.generator;

import java.util.Random;

public class PrimaryQuestionGenerator implements QuestionGenerator {
    private final Random rand = new Random();

    @Override
    public String generateQuestion() {
        int numOperands = rand.nextInt(4) + 2; // 随机生成2-5个操作数

        switch (numOperands) {
            case 2:
                return simpleExpression(num(50), op(), num(50));
            case 3:
                return generateThreeOperandExpression();
            case 4:
                return generateFourOperandExpression();
            case 5:
            default:
                return generateFiveOperandExpression();
        }
    }

    private String generateThreeOperandExpression() {
        if (rand.nextBoolean()) {
            // 模板: (a + b) * c
            return String.format("(%d %c %d) %c %d", num(20), opLow(), num(20), opHigh(), num(10));
        } else {
            // 模板: a * (b - c)

            int b = num(29) + 1; // b 的范围是 2 到 30
            int c = num(b - 1);  // c 的范围是 1 到 b-1，确保 c < b
            return String.format("%d %c (%d %c %d)", num(10), opHigh(), b, opLow(), c);
        }
    }

    private String generateFourOperandExpression() {
        if (rand.nextBoolean()) {
            // 模板: ((a + b) * c) - d
            return String.format("((%d %c %d) %c %d) %c %d", num(10), opLow(), num(10), opHigh(), num(5), opLow(), num(20));
        } else {
            // 模板: a * (b - (c + d))
            return String.format("%d %c (%d %c (%d %c %d))", num(5), opHigh(), num(50), opLow(), num(10), opLow(), num(10));
        }
    }

    private String generateFiveOperandExpression() {
        // 模板: (a * b) + (c - d) * e
        int c = num(29) + 1; // c 的范围是 2 到 30
        int d = num(c - 1);  // d 的范围是 1 到 c-1，确保 d < c
        return String.format("(%d %c %d) %c (%d %c %d) %c %d", num(10), opHigh(), num(10), opLow(), c, opLow(), d, opHigh(), num(5));
    }

    // --- 辅助方法 ---
    private int num(int bound) {
        // 健壮性检查，防止外部调用传入无效的bound
        if (bound <= 0) return 1;
        return rand.nextInt(bound) + 1;
    }
    private char op() { return "+-×÷".charAt(rand.nextInt(4)); }
    private char opLow() { return "+-".charAt(rand.nextInt(2)); } // 低优先级
    private char opHigh() { return "×÷".charAt(rand.nextInt(2)); } // 高优先级
    private String simpleExpression(int a, char op, int b) {
        if (op == '÷') a = b * num(10);
        if (op == '-') a = Math.max(a, b + 1);
        return String.format("%d %c %d", a, op, b);
    }
}