# Complete PYOMO implementation

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

def sports_competition_optimization():
    """Optimization for sports competition player assignment to clubs"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    players = [1, 2, 3]
    clubs = [1, 2, 3]
    points = {1: 15, 2: 25, 3: 10}
    max_apps = {1: 3, 2: 4, 3: 2}
    capacities = {1: 5, 2: 10, 3: 8}
    
    # CRITICAL: Validate data lengths before indexing
    assert len(points) == len(max_apps) == len(players), "Player data length mismatch"
    assert len(capacities) == len(clubs), "Club data length mismatch"
    
    # 3. SETS
    model.Players = pyo.Set(initialize=players)
    model.Clubs = pyo.Set(initialize=clubs)
    
    # 4. PARAMETERS
    model.Points = pyo.Param(model.Players, initialize=points)
    model.MaxApps = pyo.Param(model.Players, initialize=max_apps)
    model.Capacity = pyo.Param(model.Clubs, initialize=capacities)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Players, model.Clubs, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Points[i] * model.x[i, j] for i in model.Players for j in model.Clubs)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Player Application Limit
    def player_app_limit_rule(model, i):
        return sum(model.x[i, j] for j in model.Clubs) <= model.MaxApps[i]
    model.player_app_limit = pyo.Constraint(model.Players, rule=player_app_limit_rule)
    
    # Club Capacity Limit
    def club_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.Players) <= model.Capacity[j]
    model.club_capacity = pyo.Constraint(model.Clubs, rule=club_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("\nAssignment of players to clubs:")
        for i in model.Players:
            for j in model.Clubs:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments
                    print(f"Player {i} assigned to Club {j}")
        
    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
sports_competition_optimization()