# Complete PYOMO implementation

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

def student_engagement_optimization():
    """Optimize student engagement by allocating hours to games and sports."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    students = [1, 2, 3]
    games = [101, 102, 103]
    sports = ['Basketball', 'Soccer', 'Tennis']
    
    game_engagement_scores = {
        (1, 101): 1.8,
        (2, 102): 2.2,
        (3, 103): 1.5
    }
    
    sport_engagement_scores = {
        (1, 'Basketball'): 1.5,
        (2, 'Soccer'): 1.8,
        (3, 'Tennis'): 2.0
    }
    
    # 3. SETS
    model.Students = pyo.Set(initialize=students)
    model.Games = pyo.Set(initialize=games)
    model.Sports = pyo.Set(initialize=sports)
    
    # 4. PARAMETERS
    model.GameEngagementScore = pyo.Param(model.Students, model.Games, initialize=game_engagement_scores, default=0)
    model.SportEngagementScore = pyo.Param(model.Students, model.Sports, initialize=sport_engagement_scores, default=0)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Students, model.Games, within=pyo.NonNegativeReals)
    model.y = pyo.Var(model.Students, model.Sports, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.GameEngagementScore[s, g] * model.x[s, g] for s in model.Students for g in model.Games) + \
               sum(model.SportEngagementScore[s, sp] * model.y[s, sp] for s in model.Students for sp in model.Sports)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Hours Constraint
    def total_hours_rule(model, s):
        return sum(model.x[s, g] for g in model.Games) + sum(model.y[s, sp] for sp in model.Sports) <= 20
    model.total_hours_constraint = pyo.Constraint(model.Students, rule=total_hours_rule)
    
    # Scholarship Sports Hours Constraint
    def scholarship_sports_rule(model, s):
        # Assuming all students are on scholarship for this example
        return sum(model.y[s, sp] for sp in model.Sports) >= 5
    model.scholarship_sports_constraint = pyo.Constraint(model.Students, rule=scholarship_sports_rule)
    
    # Maximum Gaming Hours Constraint
    def max_gaming_hours_rule(model, s):
        return sum(model.x[s, g] for g in model.Games) <= 15
    model.max_gaming_hours_constraint = pyo.Constraint(model.Students, rule=max_gaming_hours_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):.3f}")
        
        # Extract variable values
        print("\nVariable values:")
        for s in model.Students:
            for g in model.Games:
                x_val = pyo.value(model.x[s, g])
                if x_val > 1e-6:
                    print(f"x[{s}, {g}] = {x_val:.3f}")
            for sp in model.Sports:
                y_val = pyo.value(model.y[s, sp])
                if y_val > 1e-6:
                    print(f"y[{s}, {sp}] = {y_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

# Run the optimization
student_engagement_optimization()