# Complete PYOMO implementation

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

def course_teach_optimization():
    """Optimize teacher-course assignments to maximize expected grade improvement"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    courses = [101, 102, 103]
    teachers = [201, 202, 203]
    expected_improvements = {
        (101, 201): 0.8,
        (102, 202): 0.6,
        (103, 203): 0.7,
        (101, 202): 0.5,
        (102, 203): 0.4
    }
    
    # CRITICAL: Validate data consistency
    assert all((i, j) in expected_improvements for i in courses for j in teachers if (i, j) in expected_improvements), "Data inconsistency detected"
    
    # 3. SETS
    model.C = pyo.Set(initialize=courses)
    model.T = pyo.Set(initialize=teachers)
    
    # 4. PARAMETERS
    model.expected_improvement = pyo.Param(model.C * model.T, initialize=expected_improvements, default=0)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, model.T, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.expected_improvement[i, j] * model.x[i, j] for i in model.C for j in model.T)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Each course can have at most one teacher assigned
    def course_constraint_rule(model, i):
        return sum(model.x[i, j] for j in model.T) <= 1
    model.course_constraint = pyo.Constraint(model.C, rule=course_constraint_rule)
    
    # Each teacher can only be assigned to one course
    def teacher_constraint_rule(model, j):
        return sum(model.x[i, j] for i in model.C) <= 1
    model.teacher_constraint = pyo.Constraint(model.T, rule=teacher_constraint_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):.3f}")
        
        # Extract variable values
        print("\nAssignment values:")
        for i in model.C:
            for j in model.T:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i},{j}] = {int(x_val)}")
        
    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
course_teach_optimization()