# Complete PYOMO implementation

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

def riding_club_optimization():
    """Optimization model for the riding club player-coach assignment problem."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Compatibility scores and coach constraints data
    compatibility_scores = {
        (1, 1): 0.85,
        (1, 2): 0.65,
        (2, 1): 0.75,
        (2, 3): 0.6,
        (3, 2): 0.9,
        (3, 3): 0.7
    }
    coach_constraints = {
        1: 5,
        2: 4,
        3: 6
    }
    min_compatibility_score = 0.6  # Example threshold
    
    # 3. SETS
    model.Players = pyo.Set(initialize=set(i for i, j in compatibility_scores))
    model.Coaches = pyo.Set(initialize=set(j for i, j in compatibility_scores))
    
    # 4. PARAMETERS
    model.compatibility_score = pyo.Param(model.Players, model.Coaches, initialize=compatibility_scores, default=0)
    model.max_players = pyo.Param(model.Coaches, initialize=coach_constraints)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Players, model.Coaches, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.compatibility_score[i, j] * model.x[i, j] for i in model.Players for j in model.Coaches)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Coach capacity constraints
    def coach_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.Players) <= model.max_players[j]
    model.coach_capacity_constraint = pyo.Constraint(model.Coaches, rule=coach_capacity_rule)
    
    # Player assignment constraints
    def player_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Coaches) <= 1
    model.player_assignment_constraint = pyo.Constraint(model.Players, rule=player_assignment_rule)
    
    # Compatibility threshold constraints
    def compatibility_threshold_rule(model, i, j):
        if model.compatibility_score[i, j] < min_compatibility_score:
            return model.x[i, j] == 0
        return pyo.Constraint.Skip
    model.compatibility_threshold_constraint = pyo.Constraint(model.Players, model.Coaches, rule=compatibility_threshold_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 decisions:")
        for i in model.Players:
            for j in model.Coaches:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments that are made
                    print(f"Player {i} assigned to Coach {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
riding_club_optimization()