# Complete PYOMO implementation

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

def optimize_advisor_workload():
    """Optimize the allocation of student advisors to minimize maximum workload."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem description
    students = [1, 2, 3]
    advisors = [201, 202, 203]
    max_students = {201: 5, 202: 6, 203: 7}
    max_weights = {201: 100.0, 202: 120.0, 203: 150.0}
    initial_weights = {201: 50.0, 202: 60.0, 203: 70.0}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(students) == 3, "Student data length mismatch"
    assert len(advisors) == 3, "Advisor data length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=students)
    model.J = pyo.Set(initialize=advisors)
    
    # 4. PARAMETERS
    model.MaxStudents = pyo.Param(model.J, initialize=max_students)
    model.MaxWeight = pyo.Param(model.J, initialize=max_weights)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    model.w = pyo.Var(model.J, within=pyo.NonNegativeReals)
    model.M = pyo.Var(within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return model.M
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Maximum workload constraint
    def max_workload_rule(model, j):
        return model.M >= sum(model.x[i, j] for i in model.I) + model.w[j]
    model.max_workload_constraint = pyo.Constraint(model.J, rule=max_workload_rule)
    
    # Student assignment constraint
    def student_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) == 1
    model.student_assignment_constraint = pyo.Constraint(model.I, rule=student_assignment_rule)
    
    # Advisor capacity constraints
    def max_students_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.MaxStudents[j]
    model.max_students_constraint = pyo.Constraint(model.J, rule=max_students_rule)
    
    def max_weight_rule(model, j):
        return model.w[j] <= model.MaxWeight[j]
    model.max_weight_constraint = pyo.Constraint(model.J, rule=max_weight_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("\nVariable values:")
        for j in model.J:
            workload = sum(pyo.value(model.x[i, j]) for i in model.I) + pyo.value(model.w[j])
            print(f"Advisor {j}: Workload = {workload:.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
optimize_advisor_workload()