# Complete PYOMO implementation

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

def optimize_participation():
    """Optimize the allocation of students and faculty to extracurricular activities."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data (replace with actual data from database)
    students = [101, 102, 103]
    faculty = [201, 202, 203]
    activities = [1, 2, 3]
    
    # Activity capacities
    activity_capacity = {
        1: 10,
        2: 15,
        3: 20
    }
    
    # Validate array lengths
    assert len(students) > 0, "No students provided"
    assert len(faculty) > 0, "No faculty provided"
    assert len(activities) > 0, "No activities provided"
    assert len(activity_capacity) == len(activities), "Activity capacity mismatch"
    
    # 3. SETS
    model.S = pyo.Set(initialize=students)  # Set of students
    model.F = pyo.Set(initialize=faculty)  # Set of faculty
    model.A = pyo.Set(initialize=activities)  # Set of activities
    
    # 4. PARAMETERS
    model.max_participants = pyo.Param(model.A, initialize=activity_capacity)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.S, model.A, within=pyo.Binary)  # Student participation
    model.y = pyo.Var(model.F, model.A, within=pyo.Binary)  # Faculty participation
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[s, a] for s in model.S for a in model.A) + \
               sum(model.y[f, a] for f in model.F for a in model.A)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Student Participation Limit
    def student_limit_rule(model, s):
        return sum(model.x[s, a] for a in model.A) <= 1
    model.student_limit = pyo.Constraint(model.S, rule=student_limit_rule)
    
    # Faculty Participation Limit
    def faculty_limit_rule(model, f):
        return sum(model.y[f, a] for a in model.A) <= 2
    model.faculty_limit = pyo.Constraint(model.F, rule=faculty_limit_rule)
    
    # Activity Capacity Limit
    def activity_capacity_rule(model, a):
        return sum(model.x[s, a] for s in model.S) + \
               sum(model.y[f, a] for f in model.F) <= model.max_participants[a]
    model.activity_capacity = pyo.Constraint(model.A, rule=activity_capacity_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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nStudent Participation:")
        for s in model.S:
            for a in model.A:
                if pyo.value(model.x[s, a]) > 0:
                    print(f"Student {s} participates in activity {a}")
        
        print("\nFaculty Participation:")
        for f in model.F:
            for a in model.A:
                if pyo.value(model.y[f, a]) > 0:
                    print(f"Faculty {f} participates in activity {a}")
        
    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_participation()