# Complete DOCPLEX implementation

from docplex.mp.model import Model

def railway_optimization():
    """Optimize train allocation to minimize operational costs."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="railway_optimization")
    
    # Data from the problem statement
    operational_costs = [120.0, 180.0, 140.0]
    capacities = [12, 18, 15]
    minimum_trains_required = [3, 4, 5]
    total_trains_available = 30
    
    # Validate array lengths to prevent IndexError
    assert len(operational_costs) == len(capacities) == len(minimum_trains_required), "Array length mismatch"
    safe_range = range(len(operational_costs))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.integer_var(name=f"x_{i+1}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(operational_costs[i] * x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Total train availability constraint
    total_trains = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_trains <= total_trains_available, ctname="total_trains_available")
    
    # Railway capacity and minimum train requirement constraints
    for i in safe_range:
        mdl.add_constraint(x[i] <= capacities[i], ctname=f"capacity_{i+1}")
        mdl.add_constraint(x[i] >= minimum_trains_required[i], ctname=f"min_trains_{i+1}")
    
    # 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])
            print(f"x[{i+1}] = {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
railway_optimization()