# Complete PYOMO implementation

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

def dorm_assignment_optimization():
    """Optimize dorm assignment to minimize total distance traveled by students."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data from the provided SQL inserts
    students = [1, 2, 3]
    dorms = [1, 2]
    
    distance_matrix = {
        (1, 1): 12.5,
        (1, 2): 18.3,
        (2, 1): 15.0,
        (2, 2): 10.2,
        (3, 1): 20.1,
        (3, 2): 14.7
    }
    
    gender_info = {
        (1, 1): 'Male',
        (2, 2): 'Female',
        (3, 1): 'Male'
    }
    
    dorm_capacity = {
        1: 100,
        2: 150
    }
    
    dorm_gender = {
        1: 'Male',
        2: 'Female'
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(students) == 3, "Student array length mismatch"
    assert len(dorms) == 2, "Dorm array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.Students = pyo.Set(initialize=students)
    model.Dorms = pyo.Set(initialize=dorms)
    
    # 4. PARAMETERS (data containers)
    model.DistanceMatrix = pyo.Param(model.Students, model.Dorms, initialize=distance_matrix)
    model.GenderInfo = pyo.Param(model.Students, model.Dorms, initialize=gender_info)
    model.DormCapacity = pyo.Param(model.Dorms, initialize=dorm_capacity)
    model.DormGender = pyo.Param(model.Dorms, initialize=dorm_gender)
    
    # 5. VARIABLES
    model.Assign = pyo.Var(model.Students, model.Dorms, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.DistanceMatrix[s, d] * model.Assign[s, d] for s in model.Students for d in model.Dorms)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Single Assignment Constraint
    def single_assignment_rule(model, s):
        return sum(model.Assign[s, d] for d in model.Dorms) == 1
    model.single_assignment = pyo.Constraint(model.Students, rule=single_assignment_rule)
    
    # Dorm Capacity Constraint
    def dorm_capacity_rule(model, d):
        return sum(model.Assign[s, d] for s in model.Students) <= model.DormCapacity[d]
    model.dorm_capacity = pyo.Constraint(model.Dorms, rule=dorm_capacity_rule)
    
    # Gender Matching Constraint
    def gender_matching_rule(model, s, d):
        if (s, d) in model.GenderInfo and model.GenderInfo[s, d] != model.DormGender[d]:
            return model.Assign[s, d] == 0
        else:
            return pyo.Constraint.Skip
    model.gender_matching = pyo.Constraint(model.Students, model.Dorms, rule=gender_matching_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("\nAssignment values:")
        for s in model.Students:
            for d in model.Dorms:
                if pyo.value(model.Assign[s, d]) > 0.5:  # Only print assignments
                    print(f"Student {s} assigned to Dorm {d}")
        
    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__":
    dorm_assignment_optimization()