# Complete PYOMO implementation

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

def optimize_restaurant_allocation():
    """Optimize student allocation to restaurants to maximize satisfaction within budget."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data from the problem context
    students = [1, 2, 3]
    restaurants = [1, 2, 3]
    
    # Satisfaction scores (StuID, ResID, score)
    satisfaction_scores = {
        (1, 1): 4.5,
        (1, 2): 3.0,
        (2, 1): 3.8,
        (2, 2): 2.5,
        (3, 3): 5.0
    }
    
    # Restaurant capacities (ResID, capacity)
    restaurant_capacities = {
        1: 50,
        2: 75,
        3: 100
    }
    
    # Total budget
    total_budget = 15000
    
    # 3. SETS
    model.Students = pyo.Set(initialize=students)
    model.Restaurants = pyo.Set(initialize=restaurants)
    
    # 4. PARAMETERS
    model.satisfaction_scores = pyo.Param(model.Students, model.Restaurants, initialize=satisfaction_scores, default=0.0)
    model.restaurant_capacities = pyo.Param(model.Restaurants, initialize=restaurant_capacities)
    model.total_budget = pyo.Param(initialize=total_budget)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Students, model.Restaurants, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.satisfaction_scores[i, j] * model.x[i, j] for i in model.Students for j in model.Restaurants)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total Spending Constraint
    def spending_rule(model):
        return sum(model.satisfaction_scores[i, j] * model.x[i, j] for i in model.Students for j in model.Restaurants) <= model.total_budget
    model.spending_constraint = pyo.Constraint(rule=spending_rule)
    
    # Restaurant Capacity Constraint
    def capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.Students) <= model.restaurant_capacities[j]
    model.capacity_constraint = pyo.Constraint(model.Restaurants, rule=capacity_rule)
    
    # Student Assignment Constraint
    def assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Restaurants) == 1
    model.assignment_constraint = pyo.Constraint(model.Students, rule=assignment_rule)
    
    # 8. SOLVING WITH GUROBI
    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.Students:
            for j in model.Restaurants:
                if pyo.value(model.x[i, j]) > 0:
                    print(f"Student {i} assigned to Restaurant {j}")
        
    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__":
    optimize_restaurant_allocation()