# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_player_allocation():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided schema
    players = [1, 2, 3]
    teams = [1, 2, 3]
    positions = [1, 2, 3]
    
    historical_win_rates = {
        (1, 1): 0.75,
        (2, 2): 0.8,
        (3, 3): 0.85
    }
    
    min_players = {1: 5, 2: 6, 3: 7}
    max_players = {1: 10, 2: 11, 3: 12}
    
    league_capacity = 100
    
    # CRITICAL: Validate array lengths before indexing
    assert len(historical_win_rates) == len(players) * len(positions), "Historical win rates mismatch"
    
    # 3. SETS
    model.Players = pyo.Set(initialize=players)
    model.Teams = pyo.Set(initialize=teams)
    model.Positions = pyo.Set(initialize=positions)
    
    # 4. PARAMETERS
    model.historical_win_rate = pyo.Param(model.Players, model.Positions, initialize=historical_win_rates)
    model.min_players = pyo.Param(model.Teams, initialize=min_players)
    model.max_players = pyo.Param(model.Teams, initialize=max_players)
    model.league_capacity = pyo.Param(initialize=league_capacity)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Players, model.Teams, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.historical_win_rate[p, pos] * model.x[p, t] for p in model.Players for t in model.Teams for pos in model.Positions)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Player Assignment Constraint
    def player_assignment_rule(model, p):
        return sum(model.x[p, t] for t in model.Teams) <= 1
    model.player_assignment_constraint = pyo.Constraint(model.Players, rule=player_assignment_rule)
    
    # Team Size Constraints
    def team_size_min_rule(model, t):
        return sum(model.x[p, t] for p in model.Players) >= model.min_players[t]
    model.team_size_min_constraint = pyo.Constraint(model.Teams, rule=team_size_min_rule)
    
    def team_size_max_rule(model, t):
        return sum(model.x[p, t] for p in model.Players) <= model.max_players[t]
    model.team_size_max_constraint = pyo.Constraint(model.Teams, rule=team_size_max_rule)
    
    # League Capacity Constraint
    def league_capacity_rule(model):
        return sum(model.x[p, t] for p in model.Players for t in model.Teams) <= model.league_capacity
    model.league_capacity_constraint = pyo.Constraint(rule=league_capacity_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("\nVariable values:")
        for p in model.Players:
            for t in model.Teams:
                if pyo.value(model.x[p, t]) > 1e-6:  # Only print non-zero values
                    print(f"Player {p} assigned to Team {t}")
        
    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
optimize_player_allocation()