# Complete PYOMO implementation

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

def poker_player_optimization():
    """Optimize prize money allocation for poker players to maximize satisfaction."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Player satisfaction coefficients
    satisfaction_coefficients = [1.1, 0.9, 1.3]
    n_players = len(satisfaction_coefficients)
    
    # Budget and maximum prize constraints
    total_budget = 24000
    max_prize_per_player = 10000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(satisfaction_coefficients) == n_players, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_players)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.coefficient = pyo.Param(model.I, initialize={i+1: satisfaction_coefficients[i] for i in range(n_players)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(0, max_prize_per_player))
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.coefficient[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total budget constraint
    def budget_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_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):.3f}")
        
        # Extract variable values
        print("\nPrize Money Allocation:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"Player {i}: Prize Money = {x_val:.2f}")
        
    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
poker_player_optimization()