# Complete PYOMO implementation - Retry Attempt 4

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

def sports_competition_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided schema and realistic values
    clubs = [1, 2, 3]
    players = [1, 2, 3]
    
    # Club constraints
    club_constraints = {
        1: {'max_players': 25, 'min_players': 18, 'budget': 1500000},
        2: {'max_players': 30, 'min_players': 20, 'budget': 2000000},
        3: {'max_players': 22, 'min_players': 15, 'budget': 1000000}
    }
    
    # Player salaries
    player_salaries = {
        1: 75000,
        2: 100000,
        3: 50000
    }
    
    # Player points
    player_points = {
        (1, 1): 15,
        (2, 2): 20,
        (3, 3): 10
    }
    
    # Validate array lengths
    assert len(player_points) == len(players) * len(clubs), "Player points length mismatch"
    
    # 3. SETS
    model.P = pyo.Set(initialize=players)  # Players
    model.C = pyo.Set(initialize=clubs)    # Clubs
    
    # 4. PARAMETERS
    model.points = pyo.Param(model.P, model.C, initialize=player_points)
    model.salary = pyo.Param(model.P, initialize=player_salaries)
    model.max_players = pyo.Param(model.C, initialize={c: club_constraints[c]['max_players'] for c in clubs})
    model.min_players = pyo.Param(model.C, initialize={c: club_constraints[c]['min_players'] for c in clubs})
    model.budget = pyo.Param(model.C, initialize={c: club_constraints[c]['budget'] for c in clubs})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.P, model.C, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.points[p, c] * model.x[p, c] for p in model.P for c in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Maximum Players per Club
    def max_players_rule(model, c):
        return sum(model.x[p, c] for p in model.P) <= model.max_players[c]
    model.max_players_constraint = pyo.Constraint(model.C, rule=max_players_rule)
    
    # Minimum Players per Club
    def min_players_rule(model, c):
        return sum(model.x[p, c] for p in model.P) >= model.min_players[c]
    model.min_players_constraint = pyo.Constraint(model.C, rule=min_players_rule)
    
    # Budget Limit
    def budget_rule(model, c):
        return sum(model.salary[p] * model.x[p, c] for p in model.P) <= model.budget[c]
    model.budget_constraint = pyo.Constraint(model.C, rule=budget_rule)
    
    # Player Assignment
    def player_assignment_rule(model, p):
        return sum(model.x[p, c] for c in model.C) <= 1
    model.player_assignment_constraint = pyo.Constraint(model.P, rule=player_assignment_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 c in model.C:
                if pyo.value(model.x[p, c]) > 0.5:  # Only print assignments
                    print(f"Player {p} assigned to Club {c}")
        
    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
if __name__ == "__main__":
    sports_competition_optimization()