# Complete PYOMO implementation

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

def swimming_optimization():
    """Optimization model for assigning swimmers to events to maximize total performance score."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Swimmer performance data
    swimmer_performance_data = {
        (1, 1): 85.5,
        (2, 1): 78.3,
        (3, 1): 90.0
    }
    
    # Stadium capacity data
    stadium_capacity_data = {
        1: 100,
        2: 150,
        3: 200
    }
    
    # Validate data consistency
    assert len(swimmer_performance_data) > 0, "Swimmer performance data is empty"
    assert len(stadium_capacity_data) > 0, "Stadium capacity data is empty"
    
    # 3. SETS
    # Swimmers and events
    swimmers = set(s for (s, e) in swimmer_performance_data.keys())
    events = set(e for (s, e) in swimmer_performance_data.keys())
    
    model.swimmers = pyo.Set(initialize=swimmers)
    model.events = pyo.Set(initialize=events)
    
    # 4. PARAMETERS
    # Performance scores
    model.performance_score = pyo.Param(model.swimmers, model.events, initialize=swimmer_performance_data)
    
    # Stadium capacities
    model.stadium_capacity = pyo.Param(model.events, initialize=stadium_capacity_data)
    
    # 5. VARIABLES
    # Binary decision variable: 1 if swimmer s is assigned to event e, 0 otherwise
    model.x = pyo.Var(model.swimmers, model.events, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total performance score
    def obj_rule(model):
        return sum(model.performance_score[s, e] * model.x[s, e] for s in model.swimmers for e in model.events)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Swimmer Assignment Limit: Each swimmer can be assigned to at most one event
    def swimmer_assignment_rule(model, s):
        return sum(model.x[s, e] for e in model.events) <= 1
    model.swimmer_assignment = pyo.Constraint(model.swimmers, rule=swimmer_assignment_rule)
    
    # Event Capacity Constraint: Number of swimmers assigned to each event must not exceed stadium capacity
    def event_capacity_rule(model, e):
        return sum(model.x[s, e] for s in model.swimmers) <= model.stadium_capacity[e]
    model.event_capacity = pyo.Constraint(model.events, rule=event_capacity_rule)
    
    # Performance Score Threshold: Only swimmers with a performance score of at least 80 can be assigned
    def performance_threshold_rule(model, s, e):
        if model.performance_score[s, e] < 80:
            return model.x[s, e] == 0
        else:
            return pyo.Constraint.Skip
    model.performance_threshold = pyo.Constraint(model.swimmers, model.events, rule=performance_threshold_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("\nVariable values:")
        for s in model.swimmers:
            for e in model.events:
                if pyo.value(model.x[s, e]) > 0:
                    print(f"Swimmer {s} assigned to Event {e} with score {model.performance_score[s, e]}")
        
    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__":
    swimming_optimization()