# Complete PYOMO implementation

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

def wrestler_optimization():
    """Optimization model for selecting wrestlers to maximize total days held."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Wrestler data
    wrestler_data = {
        1: {'Days_held': 150, 'eliminations': 8, 'team': 'Team A'},
        2: {'Days_held': 250, 'eliminations': 12, 'team': 'Team B'},
        3: {'Days_held': 100, 'eliminations': 5, 'team': 'Team A'}
    }
    
    # Business configuration
    max_wrestlers = 6
    max_eliminations = 30
    
    # Validate data consistency
    assert len(wrestler_data) > 0, "No wrestler data provided"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=wrestler_data.keys())  # Wrestler IDs
    
    # 4. PARAMETERS (data containers)
    model.Days_held = pyo.Param(model.I, initialize={i: wrestler_data[i]['Days_held'] for i in model.I})
    model.eliminations = pyo.Param(model.I, initialize={i: wrestler_data[i]['eliminations'] for i in model.I})
    model.team = pyo.Param(model.I, initialize={i: wrestler_data[i]['team'] for i in model.I})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)  # Binary decision variable for selection
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Days_held[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Wrestlers Constraint
    def total_wrestlers_rule(model):
        return sum(model.x[i] for i in model.I) <= max_wrestlers
    model.total_wrestlers_constraint = pyo.Constraint(rule=total_wrestlers_rule)
    
    # Total Eliminations Constraint
    def total_eliminations_rule(model):
        return sum(model.eliminations[i] * model.x[i] for i in model.I) <= max_eliminations
    model.total_eliminations_constraint = pyo.Constraint(rule=total_eliminations_rule)
    
    # Team Balance Constraint
    def team_balance_rule(model):
        return sum(model.x[i] for i in model.I if model.team[i] == 'Team A') == \
               sum(model.x[i] for i in model.I if model.team[i] == 'Team B')
    model.team_balance_constraint = pyo.Constraint(rule=team_balance_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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected Wrestlers:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected wrestlers
                print(f"Wrestler {i}: Days_held={model.Days_held[i]}, Eliminations={model.eliminations[i]}, Team={model.team[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__":
    wrestler_optimization()