#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Soccer Team Selection Optimization
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_soccer_selection():
    """Optimize soccer team selection based on skill levels and position constraints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("soccer_selection")
    
    # Example data (replace with actual data from database)
    player_ids = [1, 2, 3, 4, 5]
    skill_levels = [8.5, 7.2, 9.0, 6.8, 7.9]
    positions = ['Forward', 'Midfielder', 'Forward', 'Defender', 'Goalkeeper']
    
    # Position limits
    total_players_limit = 20
    forwards_limit = 5
    midfielders_limit = 7
    defenders_limit = 6
    goalkeepers_limit = 2
    
    # CRITICAL: Validate array lengths before loops
    assert len(player_ids) == len(skill_levels) == len(positions), "Array length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables for each player
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{player_ids[i]}") 
         for i in range(len(player_ids))}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total skill level of selected players
    model.setObjective(gp.quicksum(skill_levels[i] * x[i] for i in range(len(player_ids))), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Players Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(len(player_ids))) <= total_players_limit, name="total_players_limit")
    
    # Forwards Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(len(player_ids)) if positions[i] == 'Forward') <= forwards_limit, name="forwards_limit")
    
    # Midfielders Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(len(player_ids)) if positions[i] == 'Midfielder') <= midfielders_limit, name="midfielders_limit")
    
    # Defenders Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(len(player_ids)) if positions[i] == 'Defender') <= defenders_limit, name="defenders_limit")
    
    # Goalkeepers Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(len(player_ids)) if positions[i] == 'Goalkeeper') <= goalkeepers_limit, name="goalkeepers_limit")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(len(player_ids)):
            if x[i].x > 0.5:
                print(f"Player {player_ids[i]} selected with skill level {skill_levels[i]}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
if __name__ == "__main__":
    optimize_soccer_selection()