# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_coffee_shop_staff_allocation():
    """Optimize staff allocation across coffee shops during happy hours."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="coffee_shop_staff_allocation")
    
    # Data from the database
    total_amounts = [25.5, 30.0, 15.75]  # happy_hour_member.Total_amount
    membership_levels = [1, 2, 3]        # member.Level_of_membership
    max_staff_per_shop = [10, 12, 15]    # shop_staff_limits.Max_Staff_Per_Shop
    min_staff_per_shop = [2, 3, 4]       # shop_staff_limits.Min_Staff_Per_Shop
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(total_amounts) == len(membership_levels) == len(max_staff_per_shop) == len(min_staff_per_shop), "Array length mismatch"
    safe_range = range(min(len(total_amounts), len(membership_levels), len(max_staff_per_shop), len(min_staff_per_shop)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variable: Number of staff assigned to each shop
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total weighted spending by members during happy hours
    objective = mdl.sum(membership_levels[i] * total_amounts[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Staff Budget Constraint
    total_staff = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_staff <= 150, ctname="total_staff_budget")
    
    # Shop Staffing Limits
    for i in safe_range:
        mdl.add_constraint(x[i] >= min_staff_per_shop[i], ctname=f"min_staff_{i}")
        mdl.add_constraint(x[i] <= max_staff_per_shop[i], ctname=f"max_staff_{i}")
    
    # Maximum Spending Limit per Member
    for i in safe_range:
        mdl.add_constraint(total_amounts[i] <= 50, ctname=f"max_spending_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            print(f"Staff assigned to shop {i}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
optimize_coffee_shop_staff_allocation()