# Complete PYOMO implementation - Retry Attempt 4

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

def school_bus_optimization():
    """Optimize school bus driver assignments to minimize experience mismatch."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    drivers = [1, 2, 3]
    schools = [101, 102, 103]
    is_full_time = {1: True, 2: True, 3: True}
    required_drivers = {101: 3, 102: 4, 103: 5}
    years_mismatch = {
        (1, 101): 2, (1, 102): 3, (1, 103): 4,
        (2, 101): 5, (2, 102): 1, (2, 103): 2,
        (3, 101): 3, (3, 102): 4, (3, 103): 0
    }
    
    # CRITICAL: Validate data lengths
    assert len(drivers) == len(is_full_time), "Driver data length mismatch"
    assert len(schools) == len(required_drivers), "School data length mismatch"
    
    # 3. SETS
    model.D = pyo.Set(initialize=drivers)
    model.S = pyo.Set(initialize=schools)
    
    # 4. PARAMETERS
    model.is_full_time = pyo.Param(model.D, initialize=is_full_time)
    model.required_drivers = pyo.Param(model.S, initialize=required_drivers)
    model.years_mismatch = pyo.Param(model.D * model.S, initialize=years_mismatch)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.D, model.S, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.years_mismatch[i, j] * model.x[i, j] for i in model.D for j in model.S)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Each driver can be assigned to at most one school
    def driver_assignment_rule(model, i):
        if model.is_full_time[i]:
            return sum(model.x[i, j] for j in model.S) <= 1
        else:
            return pyo.Constraint.Skip
    model.driver_assignment_constraint = pyo.Constraint(model.D, rule=driver_assignment_rule)
    
    # Each school must receive the exact number of drivers it requires
    def school_requirement_rule(model, j):
        return sum(model.x[i, j] for i in model.D) == model.required_drivers[j]
    model.school_requirement_constraint = pyo.Constraint(model.S, rule=school_requirement_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
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nDriver assignments:")
        for i in model.D:
            for j in model.S:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable check
                    print(f"Driver {i} assigned to School {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

# Execute the optimization
school_bus_optimization()