#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Soccer Team Selection Optimization
"""

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

def soccer_team_selection():
    """Optimization model for selecting soccer players for tryouts"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data for player skills and positions
    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']
    
    # Validate array lengths before indexing
    assert len(player_ids) == len(skill_levels) == len(positions), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=player_ids)  # Set of players
    
    # 4. PARAMETERS (data containers)
    model.skill_level = pyo.Param(model.I, initialize={i: skill_levels[idx] for idx, i in enumerate(player_ids)})
    model.position = pyo.Param(model.I, initialize={i: positions[idx] for idx, i in enumerate(player_ids)})
    
    # 5. VARIABLES
    # Binary decision variable for player selection
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize the total skill level of selected players
    def obj_rule(model):
        return sum(model.skill_level[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Players Constraint
    def total_players_rule(model):
        return sum(model.x[i] for i in model.I) <= 20
    model.total_players_constraint = pyo.Constraint(rule=total_players_rule)
    
    # Forwards Constraint
    def forwards_rule(model):
        return sum(model.x[i] for i in model.I if model.position[i] == 'Forward') <= 5
    model.forwards_constraint = pyo.Constraint(rule=forwards_rule)
    
    # Midfielders Constraint
    def midfielders_rule(model):
        return sum(model.x[i] for i in model.I if model.position[i] == 'Midfielder') <= 7
    model.midfielders_constraint = pyo.Constraint(rule=midfielders_rule)
    
    # Defenders Constraint
    def defenders_rule(model):
        return sum(model.x[i] for i in model.I if model.position[i] == 'Defender') <= 6
    model.defenders_constraint = pyo.Constraint(rule=defenders_rule)
    
    # Goalkeepers Constraint
    def goalkeepers_rule(model):
        return sum(model.x[i] for i in model.I if model.position[i] == 'Goalkeeper') <= 2
    model.goalkeepers_constraint = pyo.Constraint(rule=goalkeepers_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected Players:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected players
                print(f"Player {i} (Position: {model.position[i]}, Skill Level: {model.skill_level[i]})")
        
    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
if __name__ == "__main__":
    soccer_team_selection()