# Complete PYOMO implementation

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

def classroom_assignment_optimization():
    """Optimize student assignments to classrooms to minimize the maximum number of students in any classroom."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided database schema and realistic data
    students = [1, 2, 3, 4, 5]
    classrooms = [101, 102, 103]
    max_students = {101: 25, 102: 30, 103: 35}
    
    # CRITICAL: Validate data lengths before indexing
    assert len(students) > 0, "No students available"
    assert len(classrooms) > 0, "No classrooms available"
    
    # 3. SETS
    model.I = pyo.Set(initialize=students)
    model.J = pyo.Set(initialize=classrooms)
    
    # 4. PARAMETERS
    model.max_students = pyo.Param(model.J, initialize=max_students)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    model.M = pyo.Var(within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return model.M
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Classroom Capacity Constraints
    def capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.max_students[j]
    model.capacity_constraint = pyo.Constraint(model.J, rule=capacity_rule)
    
    # Student Assignment Constraints
    def assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) == 1
    model.assignment_constraint = pyo.Constraint(model.I, rule=assignment_rule)
    
    # Maximum Students Constraint
    def max_students_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.M
    model.max_students_constraint = pyo.Constraint(model.J, rule=max_students_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)
    
    # 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("\nAssignment of students to classrooms:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable check
                    print(f"Student {i} assigned to Classroom {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

# Run the optimization
classroom_assignment_optimization()