# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_bodybuilder_performance():
    """Optimize the total weight lifted by bodybuilders in Snatch and Clean & Jerk events."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="body_builder_optimization")
    
    # Data from the database
    snatch_impact = [1.2, 1.3, 1.1]
    clean_jerk_impact = [1.5, 1.6, 1.4]
    performance_targets = [300.0, 320.0, 340.0]
    total_limits = [190.0, 210.0, 220.0]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(snatch_impact) == len(clean_jerk_impact) == len(performance_targets) == len(total_limits), "Array length mismatch"
    safe_range = range(min(len(snatch_impact), len(clean_jerk_impact), len(performance_targets), len(total_limits)))  # Safe indexing
    
    # 2. VARIABLES
    x1 = {i: mdl.continuous_var(name=f"x1_{i}", lb=0) for i in safe_range}
    x2 = {i: mdl.continuous_var(name=f"x2_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total weight lifted
    objective = mdl.sum(x1[i] + x2[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Performance Target Constraints
    for i in safe_range:
        mdl.add_constraint(x1[i] + x2[i] <= performance_targets[i], ctname=f"performance_target_{i}")
    
    # Training Impact Constraints
    for i in safe_range:
        mdl.add_constraint(snatch_impact[i] * x1[i] + clean_jerk_impact[i] * x2[i] <= total_limits[i], ctname=f"training_impact_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            x1_value = solution.get_value(x1[i])
            x2_value = solution.get_value(x2[i])
            if x1_value > 1e-6 or x2_value > 1e-6:
                print(f"x1[{i}] = {x1_value:.3f}, x2[{i}] = {x2_value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_bodybuilder_performance()