#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Bodybuilder Team Selection Problem
"""

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

def bodybuilder_optimization():
    """Optimization model for selecting bodybuilders to maximize performance score."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Performance scores (Snatch + Clean & Jerk)
    performance_scores = [350.5, 370.5, 390.5]
    
    # Physical attributes
    heights = [175.0, 180.0, 185.0]
    weights = [90.0, 95.0, 100.0]
    
    # Number of bodybuilders
    n_bodybuilders = len(performance_scores)
    
    # CRITICAL: Validate array lengths before indexing
    assert len(performance_scores) == len(heights) == len(weights) == n_bodybuilders, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_bodybuilders)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.performance = pyo.Param(model.I, initialize={i+1: performance_scores[i] for i in range(n_bodybuilders)})
    model.height = pyo.Param(model.I, initialize={i+1: heights[i] for i in range(n_bodybuilders)})
    model.weight = pyo.Param(model.I, initialize={i+1: weights[i] for i in range(n_bodybuilders)})
    
    # 5. VARIABLES
    # Binary decision variables
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.performance[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Team Size Limit
    def team_size_rule(model):
        return sum(model.x[i] for i in model.I) <= 5
    model.team_size_constraint = pyo.Constraint(rule=team_size_rule)
    
    # Minimum Average Height
    def min_height_rule(model):
        return sum(model.height[i] * model.x[i] for i in model.I) >= 170 * sum(model.x[i] for i in model.I)
    model.min_height_constraint = pyo.Constraint(rule=min_height_rule)
    
    # Maximum Average Weight
    def max_weight_rule(model):
        return sum(model.weight[i] * model.x[i] for i in model.I) <= 100 * sum(model.x[i] for i in model.I)
    model.max_weight_constraint = pyo.Constraint(rule=max_weight_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("\nSelected bodybuilders:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected bodybuilders
                print(f"Bodybuilder {i} is selected.")
        
    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__":
    bodybuilder_optimization()