# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def logistics_optimization():
    """Logistics optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_cities = 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 indexing
    assert len(costs) == len(demands) == len(capacities) == n_cities, "Array length mismatch"
    
    # 3. SETS
    model.C = pyo.RangeSet(1, n_cities)  # 1-based indexing for cities
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.C, initialize={i+1: costs[i] for i in range(n_cities)})
    model.demand = pyo.Param(model.C, initialize={i+1: demands[i] for i in range(n_cities)})
    model.capacity = pyo.Param(model.C, initialize={i+1: capacities[i] for i in range(n_cities)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.C)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Total goods shipped must not exceed the total available goods
    def total_goods_rule(model):
        return sum(model.x[i] for i in model.C) <= total_available_goods
    model.total_goods_constraint = pyo.Constraint(rule=total_goods_rule)
    
    # Quantity shipped to each city must not exceed the city's maximum capacity
    def capacity_rule(model, i):
        return model.x[i] <= model.capacity[i]
    model.capacity_constraint = pyo.Constraint(model.C, rule=capacity_rule)
    
    # Quantity shipped to each city must meet or exceed the city's demand
    def demand_rule(model, i):
        return model.x[i] >= model.demand[i]
    model.demand_constraint = pyo.Constraint(model.C, rule=demand_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective):.2f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.C:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.2f}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
logistics_optimization()