# Complete PYOMO implementation - Retry Attempt 4

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

def voter_2_optimization():
    """Pyomo model for optimizing student representative elections"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_students = 3
    positions = ['President', 'Vice President', 'Secretary', 'Treasurer', 'Class President', 'Class Senator']
    
    # Votes received by each student for each position
    votes = {
        (1, 'President'): 25, (1, 'Vice President'): 18, (1, 'Secretary'): 22, (1, 'Treasurer'): 15, (1, 'Class President'): 30, (1, 'Class Senator'): 20,
        (2, 'President'): 30, (2, 'Vice President'): 25, (2, 'Secretary'): 20, (2, 'Treasurer'): 18, (2, 'Class President'): 28, (2, 'Class Senator'): 22,
        (3, 'President'): 20, (3, 'Vice President'): 30, (3, 'Secretary'): 25, (3, 'Treasurer'): 22, (3, 'Class President'): 18, (3, 'Class Senator'): 25
    }
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_students)  # Students
    model.J = pyo.Set(initialize=positions)  # Positions
    
    # 4. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 5. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(votes[i, j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 6. CONSTRAINTS
    
    # Each position must be filled by exactly one student
    def position_filled_rule(model, j):
        return sum(model.x[i, j] for i in model.I) == 1
    model.position_filled_constraint = pyo.Constraint(model.J, rule=position_filled_rule)
    
    # Each student can hold at most one position
    def student_limit_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= 1
    model.student_limit_constraint = pyo.Constraint(model.I, rule=student_limit_rule)
    
    # 7. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 8. 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("\nElection results:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if elected
                    print(f"Student {i} is elected as {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
voter_2_optimization()