# Complete PYOMO implementation

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

def optimize_shop_membership():
    """Optimize budget allocation for maximizing member purchases"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    branches = [1, 2, 3]
    total_purchases = {1: 60000, 2: 90000, 3: 80000}
    total_budget = 45000
    min_budget = 10000
    
    # CRITICAL: Validate data lengths before indexing
    assert len(branches) == len(total_purchases), "Data length mismatch"
    
    # 3. SETS
    model.B = pyo.Set(initialize=branches)
    
    # 4. PARAMETERS
    model.purchase = pyo.Param(model.B, initialize=total_purchases)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.B, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.purchase[b] * model.x[b] for b in model.B)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def total_budget_rule(model):
        return sum(model.x[b] for b in model.B) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # Minimum budget allocation for each branch
    def min_budget_rule(model, b):
        return model.x[b] >= min_budget
    model.min_budget_constraint = pyo.Constraint(model.B, rule=min_budget_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective):.2f}")
        
        # Extract variable values
        print("\nBudget Allocation:")
        for b in model.B:
            x_val = pyo.value(model.x[b])
            print(f"Branch {b}: {x_val:.2f}")
        
    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

# Run the optimization
optimize_shop_membership()