#!/usr/bin/env python3
"""
DOCPLEX implementation for soccer team selection optimization problem.
"""

from docplex.mp.model import Model

def soccer_team_selection():
    """Optimize soccer team selection to maximize total skill level."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="soccer_team_selection")
    
    # Player data
    player_ids = [1, 2, 3, 4, 5]
    skill_levels = [8.5, 7.2, 9.0, 6.8, 7.9]
    positions = ['Forward', 'Midfielder', 'Defender', 'Goalkeeper', 'Midfielder']  # Example positions
    
    # Position limits
    total_players_limit = 20
    forwards_limit = 5
    midfielders_limit = 7
    defenders_limit = 6
    goalkeepers_limit = 2
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(player_ids) == len(skill_levels) == len(positions), "Array length mismatch"
    safe_range = range(min(len(player_ids), len(skill_levels), len(positions)))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for player selection
    x = {i: mdl.binary_var(name=f"x_{player_ids[i]}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total skill level of selected players
    objective = mdl.sum(skill_levels[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Players Constraint
    total_players = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_players <= total_players_limit, ctname="total_players_limit")
    
    # Position Constraints
    forwards = mdl.sum(x[i] for i in safe_range if positions[i] == 'Forward')
    mdl.add_constraint(forwards <= forwards_limit, ctname="forwards_limit")
    
    midfielders = mdl.sum(x[i] for i in safe_range if positions[i] == 'Midfielder')
    mdl.add_constraint(midfielders <= midfielders_limit, ctname="midfielders_limit")
    
    defenders = mdl.sum(x[i] for i in safe_range if positions[i] == 'Defender')
    mdl.add_constraint(defenders <= defenders_limit, ctname="defenders_limit")
    
    goalkeepers = mdl.sum(x[i] for i in safe_range if positions[i] == 'Goalkeeper')
    mdl.add_constraint(goalkeepers <= goalkeepers_limit, ctname="goalkeepers_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            if solution.get_value(x[i]) > 0.5:  # Selected players
                print(f"Player {player_ids[i]} (Position: {positions[i]}, Skill: {skill_levels[i]}) selected")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    soccer_team_selection()