# Complete PYOMO implementation - Retry Attempt 4

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

def restaurant_optimization():
    """Optimize student visits to restaurants for maximum satisfaction."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the data based on the provided SQL data
    students = [101, 102, 103]
    restaurants = [1, 2, 3]
    
    ratings = {1: 4.5, 2: 3.8, 3: 5.0}
    budgets = {101: 120, 102: 180, 103: 150}
    costs = {(101, 1): 12.0, (102, 2): 15.0, (103, 3): 20.0}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(costs) == len(students), "Costs length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=students)
    model.J = pyo.Set(initialize=restaurants)
    
    # 4. PARAMETERS
    model.rating = pyo.Param(model.J, initialize=ratings)
    model.budget = pyo.Param(model.I, initialize=budgets)
    model.cost = pyo.Param(model.I, model.J, initialize=costs, default=0)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.rating[j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def budget_constraint_rule(model, i):
        return sum(model.cost[i, j] * model.x[i, j] for j in model.J) <= model.budget[i]
    model.budget_constraint = pyo.Constraint(model.I, rule=budget_constraint_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.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0:  # Only print non-zero values
                    print(f"x[{i},{j}] = {x_val}")
        
    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
restaurant_optimization()