from flask import Flask, render_template, request, jsonify
from itertools import combinations

app = Flask(__name__)


# 钱币有且只有“花”“衡”“厉”三个种类。
# 盒子里有三个种类的钱币若干枚，由用户输入每种钱币的数量box。
# 通过排列组合原理计算：从盒子中任意取出pick枚钱币时，取出的钱币数量满足requirement的概率。
# 函数输入：
#   box: (1, 2, 3) 分别是盒子中花、衡、厉三种钱的数量。
#   requirement: ((0, 3),(0, 3),(0, 3))，分别时掷出的钱中花、衡、厉三种钱的最少、最多数量。
#   pick: 3，从盒子中取出钱币的数量。

def calculate_probability(box, requirement, pick):
    total_coins = sum(box)
    if pick > total_coins:
        return 0.0

    # 生成所有可能的组合
    coins = ['H'] * box[0] + ['E'] * box[1] + ['L'] * box[2]

    valid_combinations = 0
    all_combinations = list(combinations(coins, pick))

    for combo in all_combinations:
        count_H = combo.count('H')
        count_E = combo.count('E')
        count_L = combo.count('L')

        if (requirement[0][0] <= count_H <= requirement[0][1] and
                requirement[1][0] <= count_E <= requirement[1][1] and
                requirement[2][0] <= count_L <= requirement[2][1]):
            valid_combinations += 1

    probability = valid_combinations / len(all_combinations)
    return probability


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        box = tuple(map(int, request.form['box'].split(',')))
        requirement = tuple(tuple(map(int, req.split(','))) for req in request.form['requirement'].split(';'))
        pick = int(request.form['pick'])

        probability = calculate_probability(box, requirement, pick)
        return jsonify({'probability': probability})

    return render_template('index.html')


if __name__ == '__main__':
    app.run(port=5001)

# Example usage:
# if __name__ == "__main__":
#     box = (1, 4, 2)
#     requirement = ((0, 3), (0, 3), (1, 3))
#     pick = 3
#     print(calculate_probability(box, requirement, pick))
