# Complete PYOMO implementation

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

def optimize_student_assignment():
    """Optimize student assignment to classrooms to minimize the maximum number of students in any classroom."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data (replace with actual data from database)
    students = [101, 102, 103, 104, 105]
    classrooms = [1, 2, 3]
    classroom_capacities = {1: 25, 2: 30, 3: 35}
    max_students_per_classroom = {1: 25, 2: 30, 3: 35}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(classroom_capacities) == len(max_students_per_classroom) == len(classrooms), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.S = pyo.Set(initialize=students)  # Set of students
    model.C = pyo.Set(initialize=classrooms)  # Set of classrooms
    
    # 4. PARAMETERS (data containers)
    model.capacity = pyo.Param(model.C, initialize=classroom_capacities)
    model.max_students = pyo.Param(model.C, initialize=max_students_per_classroom)
    
    # 5. VARIABLES
    # Binary decision variable: x[s,c] = 1 if student s is assigned to classroom c
    model.x = pyo.Var(model.S, model.C, within=pyo.Binary)
    
    # Continuous decision variable: z represents the maximum number of students in any classroom
    model.z = pyo.Var(within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return model.z
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Student Assignment Constraint: Each student must be assigned to exactly one classroom
    def student_assignment_rule(model, s):
        return sum(model.x[s, c] for c in model.C) == 1
    model.student_assignment = pyo.Constraint(model.S, rule=student_assignment_rule)
    
    # Classroom Capacity Constraint: The total number of students assigned to each classroom must not exceed its predefined capacity
    def classroom_capacity_rule(model, c):
        return sum(model.x[s, c] for s in model.S) <= model.capacity[c]
    model.classroom_capacity = pyo.Constraint(model.C, rule=classroom_capacity_rule)
    
    # Maximum Students Constraint: The total number of students assigned to any classroom must be less than or equal to z
    def max_students_rule(model, c):
        return sum(model.x[s, c] for s in model.S) <= model.z
    model.max_students_constraint = pyo.Constraint(model.C, rule=max_students_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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 s in model.S:
            for c in model.C:
                if pyo.value(model.x[s, c]) > 0.5:  # Only print assignments
                    print(f"Student {s} is assigned to Classroom {c}")
        
    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_student_assignment()