# Complete PYOMO implementation

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

def optimize_school_bus_assignment():
    """Optimize the assignment of drivers to schools to minimize total travel distance."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    drivers = [1, 2, 3]
    schools = [1, 2, 3]
    
    # Distance matrix: driver_id -> school_id -> distance
    distance_matrix = {
        (1, 1): 10.5,
        (1, 2): 15.3,
        (1, 3): 20.1,
        (2, 1): 18.2,
        (2, 2): 8.7,
        (2, 3): 22.4,
        (3, 1): 19.8,
        (3, 2): 21.3,
        (3, 3): 7.5
    }
    
    # Validate data consistency
    assert len(drivers) == 3, "Expected 3 drivers"
    assert len(schools) == 3, "Expected 3 schools"
    assert len(distance_matrix) == 9, "Expected 9 distance entries"
    
    # 3. SETS
    model.DRIVERS = pyo.Set(initialize=drivers)
    model.SCHOOLS = pyo.Set(initialize=schools)
    
    # 4. PARAMETERS
    model.distance = pyo.Param(model.DRIVERS, model.SCHOOLS, initialize=distance_matrix)
    
    # 5. VARIABLES
    model.assign = pyo.Var(model.DRIVERS, model.SCHOOLS, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.distance[i, j] * model.assign[i, j] for i in model.DRIVERS for j in model.SCHOOLS)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Each school must be assigned exactly one driver
    def school_assignment_rule(model, j):
        return sum(model.assign[i, j] for i in model.DRIVERS) == 1
    model.school_assignment = pyo.Constraint(model.SCHOOLS, rule=school_assignment_rule)
    
    # Each driver can be assigned to at most one school
    def driver_assignment_rule(model, i):
        return sum(model.assign[i, j] for j in model.SCHOOLS) <= 1
    model.driver_assignment = pyo.Constraint(model.DRIVERS, rule=driver_assignment_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("\nAssignment details:")
        for i in model.DRIVERS:
            for j in model.SCHOOLS:
                if pyo.value(model.assign[i, j]) > 0.5:  # Only print assignments
                    print(f"Driver {i} assigned to School {j} with distance {model.distance[i, 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
if __name__ == "__main__":
    optimize_school_bus_assignment()