# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_transportation():
    """Optimize transportation costs for a logistics company"""

    # 1. MODEL & DATA SETUP
    model = gp.Model("transportation_optimization")

    # Data from the problem statement
    city_ids = [1, 2, 3]
    costs = [5.0, 10.0, 15.0]
    demands = [50, 150, 250]
    capacities = [100, 200, 300]
    total_available_goods = 500

    # CRITICAL: Validate array lengths before loops
    assert len(city_ids) == len(costs) == len(demands) == len(capacities), "Array length mismatch"

    # 2. VARIABLES
    # Variable dictionaries for quantities shipped to each city
    quantity_shipped = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) for i in city_ids}

    # 3. OBJECTIVE FUNCTION
    # Minimize the total transportation cost
    model.setObjective(gp.quicksum(costs[i-1] * quantity_shipped[i] for i in city_ids), GRB.MINIMIZE)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Total goods shipped must not exceed the total available goods
    model.addConstr(gp.quicksum(quantity_shipped[i] for i in city_ids) <= total_available_goods, name="total_goods_limit")

    # Quantity shipped to each city must not exceed the city's maximum capacity
    for i in city_ids:
        model.addConstr(quantity_shipped[i] <= capacities[i-1], name=f"capacity_limit_{i}")

    # Quantity shipped to each city must meet or exceed the city's demand
    for i in city_ids:
        model.addConstr(quantity_shipped[i] >= demands[i-1], name=f"demand_satisfaction_{i}")

    # 5. SOLVING & RESULTS
    model.optimize()

    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in city_ids:
            if quantity_shipped[i].x > 1e-6:
                print(f"Quantity shipped to city {i}: {quantity_shipped[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")

    return model

# Run the optimization
optimize_transportation()