#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Riding Club Optimization Problem
"""

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

def riding_club_optimization():
    """Optimization model for maximizing total points in a riding club."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Players data
    players = {1: 12, 2: 18, 3: 9}  # Player_ID: Votes
    # Coaches data
    coaches = {1: 3, 2: 2, 3: 1}    # Coach_ID: Rank
    
    # CRITICAL: Validate array lengths before indexing
    assert len(players) > 0 and len(coaches) > 0, "Players or coaches data is empty"
    
    # 3. SETS (Pyomo way to define indices)
    model.P = pyo.Set(initialize=players.keys())  # Set of players
    model.C = pyo.Set(initialize=coaches.keys())  # Set of coaches
    
    # 4. PARAMETERS (data containers)
    model.player_votes = pyo.Param(model.P, initialize=players)
    model.coach_rank = pyo.Param(model.C, initialize=coaches)
    
    # 5. VARIABLES
    # Binary decision variable: x[p, c] = 1 if player p is assigned to coach c
    model.x = pyo.Var(model.P, model.C, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.player_votes[p] * model.coach_rank[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
    
    # Single Assignment Constraint: Each player must be assigned to exactly one coach
    def single_assignment_rule(model, p):
        return sum(model.x[p, c] for c in model.C) == 1
    model.single_assignment = pyo.Constraint(model.P, rule=single_assignment_rule)
    
    # Coach Capacity Constraint: Each coach can handle a maximum of four players
    def coach_capacity_rule(model, c):
        return sum(model.x[p, c] for p in model.P) <= 4
    model.coach_capacity = pyo.Constraint(model.C, rule=coach_capacity_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAssignment details:")
        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} is assigned to Coach {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__":
    riding_club_optimization()