# Complete PYOMO implementation

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

def gymnast_optimization():
    """Optimization model for selecting gymnasts and events to maximize total points."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Performance scores for each gymnast in each event
    performance_scores = {
        1: {'Floor_Exercise': 9.5, 'Pommel_Horse': 8.7, 'Rings': 9.0, 'Vault': 9.2, 'Parallel_Bars': 8.9, 'Horizontal_Bar': 9.1},
        2: {'Floor_Exercise': 8.8, 'Pommel_Horse': 9.3, 'Rings': 8.7, 'Vault': 8.9, 'Parallel_Bars': 9.0, 'Horizontal_Bar': 8.6},
        3: {'Floor_Exercise': 9.0, 'Pommel_Horse': 8.5, 'Rings': 9.2, 'Vault': 9.1, 'Parallel_Bars': 8.8, 'Horizontal_Bar': 9.3}
    }
    
    # Constraints
    max_events_per_gymnast = 3
    max_gymnasts_on_team = 10
    
    # 3. SETS (Pyomo way to define indices)
    model.Gymnasts = pyo.Set(initialize=[1, 2, 3])
    model.Events = pyo.Set(initialize=['Floor_Exercise', 'Pommel_Horse', 'Rings', 'Vault', 'Parallel_Bars', 'Horizontal_Bar'])
    
    # 4. PARAMETERS (data containers)
    model.performance = pyo.Param(model.Gymnasts, model.Events, initialize=lambda model, i, j: performance_scores[i][j])
    
    # 5. VARIABLES
    # Binary decision variables for event participation
    model.x = pyo.Var(model.Gymnasts, model.Events, within=pyo.Binary)
    
    # Binary decision variables for team selection
    model.y = pyo.Var(model.Gymnasts, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.performance[i, j] * model.x[i, j] for i in model.Gymnasts for j in model.Events)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Event Participation Limit: Each gymnast can participate in a maximum of 3 events
    def event_participation_rule(model, i):
        return sum(model.x[i, j] for j in model.Events) <= max_events_per_gymnast
    model.event_participation_constraint = pyo.Constraint(model.Gymnasts, rule=event_participation_rule)
    
    # Team Size Limit: The total number of gymnasts on the team cannot exceed 10
    def team_size_rule(model):
        return sum(model.y[i] for i in model.Gymnasts) <= max_gymnasts_on_team
    model.team_size_constraint = pyo.Constraint(rule=team_size_rule)
    
    # Linking constraint: If a gymnast participates in any event, they must be on the team
    def linking_rule(model, i):
        return sum(model.x[i, j] for j in model.Events) <= model.y[i] * len(model.Events)
    model.linking_constraint = pyo.Constraint(model.Gymnasts, rule=linking_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("\nVariable values:")
        for i in model.Gymnasts:
            for j in model.Events:
                if pyo.value(model.x[i, j]) > 0:
                    print(f"Gymnast {i} participates in {j}: {pyo.value(model.x[i, j])}")
            if pyo.value(model.y[i]) > 0:
                print(f"Gymnast {i} is on the team: {pyo.value(model.y[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

# Run the optimization
if __name__ == "__main__":
    gymnast_optimization()