#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Poker Player Selection Problem
"""

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

def poker_player_optimization():
    """Optimization model for selecting poker players to maximize earnings with constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    earnings = [1200.0, 1500.0, 2000.0, 1000.0, 1800.0]
    money_ranks = [45, 55, 60, 50, 58]
    nationalities = ['USA', 'Canada', 'UK', 'Australia', 'Germany']
    
    # CRITICAL: Validate array lengths before indexing
    assert len(earnings) == len(money_ranks) == len(nationalities) == 5, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, 5)  # 1-based indexing for players
    model.J = pyo.Set(initialize=['USA', 'Canada', 'UK', 'Australia', 'Germany'])  # Nationalities
    
    # 4. PARAMETERS (data containers)
    model.earnings = pyo.Param(model.I, initialize={i+1: earnings[i] for i in range(5)})
    model.money_ranks = pyo.Param(model.I, initialize={i+1: money_ranks[i] for i in range(5)})
    model.nationalities = pyo.Param(model.I, initialize={i+1: nationalities[i] for i in range(5)})
    
    # 5. VARIABLES
    # Binary decision variables for player selection
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # Binary variables for nationality selection
    model.y = pyo.Var(model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.earnings[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Nationality Diversity Constraint
    def nationality_rule(model, j):
        return model.y[j] <= sum(model.x[i] for i in model.I if model.nationalities[i] == j)
    model.nationality_constraint = pyo.Constraint(model.J, rule=nationality_rule)
    
    def diversity_rule(model):
        return sum(model.y[j] for j in model.J) >= 3
    model.diversity_constraint = pyo.Constraint(rule=diversity_rule)
    
    # Money Rank Constraint
    def money_rank_rule(model):
        S = sum(model.x[i] for i in model.I)
        L = sum(model.x[i] for i in model.I if model.money_ranks[i] < 50)
        return L <= 0.2 * S
    model.money_rank_constraint = pyo.Constraint(rule=money_rank_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected Players:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected players
                print(f"Player {i}: Earnings = {model.earnings[i]}, Nationality = {model.nationalities[i]}, Money Rank = {model.money_ranks[i]}")
        
    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__":
    poker_player_optimization()