# Complete PYOMO implementation

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

def optimize_course_teach():
    """Optimize the assignment of teachers to courses to maximize teaching quality."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided schema and realistic values
    teachers = ['T1', 'T2', 'T3']
    courses = ['C1', 'C2', 'C3', 'C4', 'C5']
    
    # Teaching quality grades for each teacher-course pair
    grades = {
        ('T1', 'C1'): 4.5,
        ('T1', 'C2'): 3.7,
        ('T1', 'C3'): 4.0,
        ('T1', 'C4'): 3.5,
        ('T1', 'C5'): 4.2,
        ('T2', 'C1'): 3.8,
        ('T2', 'C2'): 4.1,
        ('T2', 'C3'): 3.9,
        ('T2', 'C4'): 4.3,
        ('T2', 'C5'): 3.6,
        ('T3', 'C1'): 4.0,
        ('T3', 'C2'): 3.5,
        ('T3', 'C3'): 4.2,
        ('T3', 'C4'): 3.8,
        ('T3', 'C5'): 4.1,
    }
    
    # Maximum number of courses each teacher can handle
    max_courses = {
        'T1': 4,
        'T2': 3,
        'T3': 5,
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(teachers) == len(max_courses), "Teacher and max_courses length mismatch"
    assert len(grades) == len(teachers) * len(courses), "Grades length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.T = pyo.Set(initialize=teachers)  # Set of teachers
    model.C = pyo.Set(initialize=courses)   # Set of courses
    
    # 4. PARAMETERS (data containers)
    model.grade = pyo.Param(model.T, model.C, initialize=grades)
    model.max_courses = pyo.Param(model.T, initialize=max_courses)
    
    # 5. VARIABLES
    # Binary decision variables indicating whether a teacher is assigned to a course
    model.x = pyo.Var(model.T, model.C, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize the total teaching quality
    def obj_rule(model):
        return sum(model.grade[t, c] * model.x[t, c] for t in model.T for c in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Course Assignment Constraint: Each course must be assigned exactly one teacher
    def course_assignment_rule(model, c):
        return sum(model.x[t, c] for t in model.T) == 1
    model.course_assignment = pyo.Constraint(model.C, rule=course_assignment_rule)
    
    # Teacher Capacity Constraint: Each teacher can be assigned no more than their maximum allowable number of courses
    def teacher_capacity_rule(model, t):
        return sum(model.x[t, c] for c in model.C) <= model.max_courses[t]
    model.teacher_capacity = pyo.Constraint(model.T, rule=teacher_capacity_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 details:")
        for t in model.T:
            for c in model.C:
                if pyo.value(model.x[t, c]) > 0.5:  # Only print assigned pairs
                    print(f"Teacher {t} is assigned to course {c}")
        
    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
if __name__ == "__main__":
    optimize_course_teach()