# Complete PYOMO implementation - Retry Attempt 4

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

def school_player_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define sets and parameters based on the provided data
    schools = [1, 2, 3]
    positions = ['Forward', 'Midfielder', 'Defender']
    players = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    # Performance weights
    performance_weight = {
        (1, 'Forward'): 0.9,
        (1, 'Midfielder'): 0.8,
        (1, 'Defender'): 0.7,
        (2, 'Forward'): 0.8,
        (2, 'Midfielder'): 0.9,
        (2, 'Defender'): 0.8,
        (3, 'Forward'): 0.7,
        (3, 'Midfielder'): 0.8,
        (3, 'Defender'): 0.9
    }
    
    # Position constraints
    position_constraints = {
        'Forward': {'min_players': 2, 'max_players': 4},
        'Midfielder': {'min_players': 3, 'max_players': 5},
        'Defender': {'min_players': 3, 'max_players': 5}
    }
    
    # School enrollment limits
    school_enrollment = {
        1: 25,
        2: 20,
        3: 30
    }
    
    # Player positions (assuming each player has a fixed position)
    player_position = {
        1: 'Forward',
        2: 'Midfielder',
        3: 'Defender',
        4: 'Forward',
        5: 'Midfielder',
        6: 'Defender',
        7: 'Forward',
        8: 'Midfielder',
        9: 'Defender',
        10: 'Forward'
    }
    
    # 3. SETS
    model.S = pyo.Set(initialize=schools)
    model.P = pyo.Set(initialize=players)
    model.Pos = pyo.Set(initialize=positions)
    
    # 4. PARAMETERS
    model.performance_weight = pyo.Param(model.S, model.Pos, initialize=performance_weight)
    model.position_constraints_min = pyo.Param(model.Pos, initialize={pos: position_constraints[pos]['min_players'] for pos in positions})
    model.position_constraints_max = pyo.Param(model.Pos, initialize={pos: position_constraints[pos]['max_players'] for pos in positions})
    model.school_enrollment = pyo.Param(model.S, initialize=school_enrollment)
    model.player_position = pyo.Param(model.P, initialize=player_position)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.P, model.S, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.performance_weight[s, model.player_position[p]] * model.x[p, s] for p in model.P for s in model.S)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # School Enrollment Limits
    def enrollment_rule(model, s):
        return sum(model.x[p, s] for p in model.P) <= model.school_enrollment[s]
    model.enrollment_constraint = pyo.Constraint(model.S, rule=enrollment_rule)
    
    # Position Constraints
    def position_min_rule(model, s, pos):
        return sum(model.x[p, s] for p in model.P if model.player_position[p] == pos) >= model.position_constraints_min[pos]
    model.position_min_constraint = pyo.Constraint(model.S, model.Pos, rule=position_min_rule)
    
    def position_max_rule(model, s, pos):
        return sum(model.x[p, s] for p in model.P if model.player_position[p] == pos) <= model.position_constraints_max[pos]
    model.position_max_constraint = pyo.Constraint(model.S, model.Pos, rule=position_max_rule)
    
    # Minimum Team Size
    def team_size_rule(model, s):
        return sum(model.x[p, s] for p in model.P) >= 11
    model.team_size_constraint = pyo.Constraint(model.S, rule=team_size_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("\nPlayer assignments:")
        for p in model.P:
            for s in model.S:
                if pyo.value(model.x[p, s]) > 0.5:
                    print(f"Player {p} assigned to School {s}")
        
    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

# Execute the optimization
school_player_optimization()