# Complete PYOMO implementation

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

def faculty_activity_optimization():
    """Optimize faculty assignments to activities to maximize participation score."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    faculty_ids = [1, 2, 3]
    activity_ids = [101, 102, 103]
    participation_scores = {
        (1, 101): 12.0,
        (2, 102): 18.5,
        (3, 103): 14.0,
        (1, 102): 10.0,
        (2, 103): 16.0
    }
    max_activities = {1: 2, 2: 2, 3: 1}  # Example maximum activities per faculty
    min_faculty = {101: 1, 102: 1, 103: 1}  # Example minimum faculty per activity
    
    # Validate data lengths
    assert len(faculty_ids) > 0 and len(activity_ids) > 0, "Faculty or activity list is empty"
    
    # 3. SETS
    model.F = pyo.Set(initialize=faculty_ids)
    model.A = pyo.Set(initialize=activity_ids)
    
    # 4. PARAMETERS
    model.participation_score = pyo.Param(model.F, model.A, initialize=participation_scores, default=0)
    model.max_activities = pyo.Param(model.F, initialize=max_activities)
    model.min_faculty = pyo.Param(model.A, initialize=min_faculty)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.F, model.A, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.participation_score[i, j] * model.x[i, j] for i in model.F for j in model.A)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Faculty availability constraint
    def faculty_availability_rule(model, i):
        return sum(model.x[i, j] for j in model.A) <= model.max_activities[i]
    model.faculty_availability_constraint = pyo.Constraint(model.F, rule=faculty_availability_rule)
    
    # Activity staffing constraint
    def activity_staffing_rule(model, j):
        return sum(model.x[i, j] for i in model.F) >= model.min_faculty[j]
    model.activity_staffing_constraint = pyo.Constraint(model.A, rule=activity_staffing_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("\nAssignment of faculty to activities:")
        for i in model.F:
            for j in model.A:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Faculty {i} assigned to Activity {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

# Run the optimization
faculty_activity_optimization()