# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_shop_membership():
    """Optimize budget allocation for maximizing member purchases across branches."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="shop_membership")
    
    # Historical purchase data (Total_pounds) for each branch
    purchase_data = [60000, 90000, 80000]
    
    # Number of branches
    n_branches = len(purchase_data)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(purchase_data) == n_branches, "Array length mismatch"
    safe_range = range(n_branches)  # Safe indexing
    
    # 2. VARIABLES
    # Budget allocation for each branch
    budget_allocation = {i: mdl.continuous_var(name=f"budget_{i}", lb=10000) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total purchases
    objective = mdl.sum(purchase_data[i] * budget_allocation[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Total budget constraint
    total_budget = mdl.sum(budget_allocation[i] for i in safe_range)
    mdl.add_constraint(total_budget <= 45000, ctname="total_budget_constraint")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(budget_allocation[i])
            print(f"Budget allocation for branch {i+1}: {value:.2f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_shop_membership()