# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_school_teams():
    """Optimize player assignments to school teams to maximize performance score."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="school_player")
    
    # Data from the database schema
    player_ids = [1, 2, 3]
    team_ids = [1, 2, 3]
    
    performance_coefficients = [1.8, 2.3, 2.7]
    player_ages = [16, 17, 18]
    
    max_team_sizes = [15, 18, 20]
    max_age_limits = [100, 110, 120]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(player_ids) == len(performance_coefficients) == len(player_ages), "Player data length mismatch"
    assert len(team_ids) == len(max_team_sizes) == len(max_age_limits), "Team data length mismatch"
    
    safe_player_range = range(len(player_ids))
    safe_team_range = range(len(team_ids))
    
    # 2. VARIABLES
    # Binary decision variables for player assignments
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_player_range for j in safe_team_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total performance score
    objective = mdl.sum(performance_coefficients[i] * x[i, j] for i in safe_player_range for j in safe_team_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Team Size Constraints
    for j in safe_team_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_player_range) <= max_team_sizes[j], ctname=f"team_size_{j}")
    
    # Age Limit Constraints
    for j in safe_team_range:
        mdl.add_constraint(mdl.sum(player_ages[i] * x[i, j] for i in safe_player_range) <= max_age_limits[j], ctname=f"age_limit_{j}")
    
    # Player Assignment Constraints
    for i in safe_player_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_team_range) <= 1, ctname=f"player_assignment_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_player_range:
            for j in safe_team_range:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"Player {player_ids[i]} assigned to Team {team_ids[j]}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_school_teams()