#!/usr/bin/env python3
"""
DOCPLEX implementation for shop_membership optimization problem
"""

from docplex.mp.model import Model

def optimize_shop_membership():
    """Optimize the allocation of membership benefits across branches"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="shop_membership")
    
    # Data from the problem
    total_budget = 500000
    branch_ids = [1, 2, 3]
    membership_amounts = [5000.0, 7500.0, 10000.0]
    branch_capacities = [100, 150, 200]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(branch_ids) == len(membership_amounts) == len(branch_capacities), "Array length mismatch"
    safe_range = range(min(len(branch_ids), len(membership_amounts), len(branch_capacities)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: total pounds spent by members at each branch
    x = {i: mdl.continuous_var(name=f"x_{branch_ids[i]}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total pounds spent by members across all branches
    objective = mdl.sum(x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Total Membership Benefits Budget
    # The sum of the membership amounts allocated to all branches must not exceed the total budget
    total_membership = mdl.sum(membership_amounts[i] for i in safe_range)
    mdl.add_constraint(total_membership <= total_budget, ctname="total_budget")
    
    # Constraint 2: Branch Capacity Limits
    # The total pounds spent by members at each branch must not exceed the branch's capacity
    for i in safe_range:
        mdl.add_constraint(x[i] <= branch_capacities[i], ctname=f"capacity_{branch_ids[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"x[{branch_ids[i]}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    optimize_shop_membership()