# Complete PYOMO implementation

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

def optimize_scholarship_allocation():
    """Optimize scholarship allocation based on academic performance, sports participation, and gaming habits."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Academic Performance
    gpa_data = {1: 3.8, 2: 3.5, 3: 3.2}
    
    # Sports Information
    sports_data = {
        1: {'HoursPerWeek': 10.0, 'Min_Hours_Sports': 2.0, 'Max_Hours_Sports': 15.0},
        2: {'HoursPerWeek': 7.5, 'Min_Hours_Sports': 2.5, 'Max_Hours_Sports': 18.0},
        3: {'HoursPerWeek': 5.0, 'Min_Hours_Sports': 3.0, 'Max_Hours_Sports': 20.0}
    }
    
    # Gaming Information
    gaming_data = {
        1: {'Hours_Played': 12.5, 'Min_Hours_Gaming': 5.0, 'Max_Hours_Gaming': 20.0},
        2: {'Hours_Played': 15.0, 'Min_Hours_Gaming': 6.0, 'Max_Hours_Gaming': 25.0},
        3: {'Hours_Played': 10.0, 'Min_Hours_Gaming': 5.5, 'Max_Hours_Gaming': 22.0}
    }
    
    # Objective Weights
    weights = {'w1': 0.6, 'w2': 0.25, 'w3': 0.15}
    
    # Total Budget
    total_budget = 150000
    
    # 3. SETS
    model.I = pyo.Set(initialize=[1, 2, 3])  # Students
    
    # 4. PARAMETERS
    model.gpa = pyo.Param(model.I, initialize=gpa_data)
    model.hours_sports = pyo.Param(model.I, initialize={i: sports_data[i]['HoursPerWeek'] for i in model.I})
    model.hours_gaming = pyo.Param(model.I, initialize={i: gaming_data[i]['Hours_Played'] for i in model.I})
    model.min_hours_sports = pyo.Param(model.I, initialize={i: sports_data[i]['Min_Hours_Sports'] for i in model.I})
    model.max_hours_sports = pyo.Param(model.I, initialize={i: sports_data[i]['Max_Hours_Sports'] for i in model.I})
    model.min_hours_gaming = pyo.Param(model.I, initialize={i: gaming_data[i]['Min_Hours_Gaming'] for i in model.I})
    model.max_hours_gaming = pyo.Param(model.I, initialize={i: gaming_data[i]['Max_Hours_Gaming'] for i in model.I})
    model.w1 = pyo.Param(initialize=weights['w1'])
    model.w2 = pyo.Param(initialize=weights['w2'])
    model.w3 = pyo.Param(initialize=weights['w3'])
    model.total_budget = pyo.Param(initialize=total_budget)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)  # Scholarship amount
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.w1 * model.gpa[i] + model.w2 * model.hours_sports[i] + model.w3 * model.hours_gaming[i]) * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total Budget Constraint
    def budget_constraint_rule(model):
        return sum(model.x[i] for i in model.I) <= model.total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Scholarship Fairness Constraint
    def fairness_constraint_rule(model, i):
        return model.x[i] >= 1000 * model.gpa[i]
    model.fairness_constraint = pyo.Constraint(model.I, rule=fairness_constraint_rule)
    
    # Sports Participation Constraints
    def sports_constraint_rule(model, i):
        return (model.min_hours_sports[i], model.hours_sports[i], model.max_hours_sports[i])
    model.sports_constraint = pyo.Constraint(model.I, rule=sports_constraint_rule)
    
    # Gaming Habits Constraints
    def gaming_constraint_rule(model, i):
        return (model.min_hours_gaming[i], model.hours_gaming[i], model.max_hours_gaming[i])
    model.gaming_constraint = pyo.Constraint(model.I, rule=gaming_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("\nScholarship Allocation:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"Student {i}: ${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

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