#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Shop Membership Optimization Problem
"""

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def shop_membership_optimization():
    """Optimize the allocation of membership benefits across branches to maximize customer satisfaction."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Branch data
    branches = [1, 2, 3]
    membership_amounts = [5000.0, 7500.0, 10000.0]
    branch_capacities = [100, 150, 200]
    
    # Validate array lengths before indexing
    assert len(branches) == len(membership_amounts) == len(branch_capacities), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=branches)  # Set of branches
    
    # 4. PARAMETERS (data containers)
    model.membership_amount = pyo.Param(model.I, initialize={i: membership_amounts[idx] for idx, i in enumerate(branches)})
    model.branch_capacity = pyo.Param(model.I, initialize={i: branch_capacities[idx] for idx, i in enumerate(branches)})
    
    # 5. VARIABLES
    # Continuous variables for total pounds spent by members at each branch
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize the total pounds spent by members across all branches
    def obj_rule(model):
        return sum(model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Branch Capacity Limits: The total pounds spent by members at each branch must not exceed the branch's capacity
    def capacity_rule(model, i):
        return model.x[i] <= model.branch_capacity[i]
    model.capacity_constraint = pyo.Constraint(model.I, rule=capacity_rule)
    
    # Non-Negativity Constraints: The total pounds spent by members at each branch must be non-negative
    def non_negativity_rule(model, i):
        return model.x[i] >= 0
    model.non_negativity_constraint = pyo.Constraint(model.I, rule=non_negativity_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

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