# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_transportation():
    """Optimize transportation costs for a logistics company"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="transportation_optimization")
    
    # Data from the problem context
    costs = [5.0, 10.0, 15.0]
    demands = [50, 150, 250]
    capacities = [100, 200, 300]
    total_available_goods = 500
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(costs) == len(demands) == len(capacities), "Array length mismatch"
    safe_range = range(min(len(costs), len(demands), len(capacities)))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(costs[i] * x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    # Total goods shipped must not exceed the total available goods
    total_shipped = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_shipped <= total_available_goods, ctname="total_goods_limit")
    
    # Quantity shipped to each city must not exceed the city's maximum capacity
    for i in safe_range:
        mdl.add_constraint(x[i] <= capacities[i], ctname=f"capacity_limit_{i}")
    
    # Quantity shipped to each city must meet or exceed the city's demand
    for i in safe_range:
        mdl.add_constraint(x[i] >= demands[i], ctname=f"demand_satisfaction_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_transportation()