# Complete DOCPLEX implementation

from docplex.mp.model import Model

def bike_optimization():
    """Optimization for bike-sharing system to minimize penalty costs"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="bike_optimization")
    
    # Data: Penalty costs, dock counts, expected demands, and total bikes
    shortage_penalty = [5, 4, 6]  # Example penalty costs for shortages
    excess_penalty = [3, 2, 4]    # Example penalty costs for excesses
    dock_counts = [15, 20, 10]
    expected_demands = [12, 18, 8]
    total_bikes = 3  # Total number of bikes in shortage and excess
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(shortage_penalty) == len(excess_penalty) == len(dock_counts) == len(expected_demands), "Array length mismatch"
    safe_range = range(min(len(shortage_penalty), len(excess_penalty), len(dock_counts), len(expected_demands)))  # Safe indexing
    
    # 2. VARIABLES
    s = {i: mdl.continuous_var(name=f"s_{i}", lb=0) for i in safe_range}
    e = {i: mdl.continuous_var(name=f"e_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(shortage_penalty[i] * s[i] + excess_penalty[i] * e[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total Bikes Constraint
    total_bikes_constraint = mdl.sum(s[i] + e[i] for i in safe_range)
    mdl.add_constraint(total_bikes_constraint == total_bikes, ctname="total_bikes_constraint")
    
    # Dock Capacity Constraints
    for i in safe_range:
        mdl.add_constraint(s[i] + expected_demands[i] <= dock_counts[i], ctname=f"dock_capacity_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            shortage_value = solution.get_value(s[i])
            excess_value = solution.get_value(e[i])
            print(f"Station {i}: Shortage = {shortage_value:.3f}, Excess = {excess_value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
bike_optimization()