# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def optimize_student_elections():
    # 1. MODEL & DATA SETUP
    model = gp.Model("student_elections")
    
    # Votes data from the Voting_record table
    votes = [
        [25, 18, 22, 15, 30, 20],  # Student 1
        [30, 25, 20, 18, 28, 22],  # Student 2
        [20, 30, 25, 22, 18, 25]   # Student 3
    ]
    
    n_students = len(votes)
    n_positions = len(votes[0])
    
    # Validate array lengths
    assert all(len(vote) == n_positions for vote in votes), "Array length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables: x[i, j] = 1 if student i is elected to position j
    x = model.addVars(n_students, n_positions, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total number of votes received by the elected representatives
    model.setObjective(
        gp.quicksum(votes[i][j] * x[i, j] for i in range(n_students) for j in range(n_positions)),
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    # Each position must be filled by exactly one student
    model.addConstrs(
        (gp.quicksum(x[i, j] for i in range(n_students)) == 1 for j in range(n_positions)),
        name="position_filled"
    )
    
    # Each student can hold at most one position
    model.addConstrs(
        (gp.quicksum(x[i, j] for j in range(n_positions)) <= 1 for i in range(n_students)),
        name="student_position_limit"
    )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_students):
            for j in range(n_positions):
                if x[i, j].x > 0.5:  # Binary variable, so check if it's 1
                    print(f"Student {i+1} is elected to position {j+1}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_student_elections()