# Complete PYOMO implementation

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

def gymnastics_optimization():
    """Optimize gymnast event participation to maximize total points."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Points scored by each gymnast in each event
    points = [
        [12, 10, 14, 15, 11, 9],  # Gymnast 1
        [18, 16, 17, 19, 14, 13], # Gymnast 2
        [14, 12, 15, 17, 13, 11]  # Gymnast 3
    ]
    
    # Constraints from the database
    max_events_per_gymnast = 3
    max_gymnasts_per_event = 5
    
    # Number of gymnasts and events
    n_gymnasts = len(points)
    n_events = len(points[0])
    
    # CRITICAL: Validate array lengths before indexing
    assert all(len(row) == n_events for row in points), "Array length mismatch in points data"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_gymnasts)  # Gymnasts
    model.J = pyo.RangeSet(1, n_events)    # Events
    
    # 4. PARAMETERS
    model.points = pyo.Param(model.I, model.J, initialize={(i+1, j+1): points[i][j] for i in range(n_gymnasts) for j in range(n_events)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.points[i, j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Maximum events per gymnast
    def max_events_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= max_events_per_gymnast
    model.max_events_constraint = pyo.Constraint(model.I, rule=max_events_rule)
    
    # Maximum gymnasts per event
    def max_gymnasts_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= max_gymnasts_per_event
    model.max_gymnasts_constraint = pyo.Constraint(model.J, rule=max_gymnasts_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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nParticipation decisions:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print participation decisions
                    print(f"Gymnast {i} participates in event {j}")
        
    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
gymnastics_optimization()