#!/usr/bin/env python3
"""
DOCPLEX Implementation for Flight Optimization Problem
"""

from docplex.mp.model import Model

def flight_optimization():
    """Optimize flight operations to minimize costs while respecting airport capacities."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="flight_optimization")
    
    # Define routes, costs, and capacities
    routes = ['NYC-LAX', 'CHI-MIA', 'SEA-DEN']
    costs = [4500, 3500, 3000]
    departure_capacities = [150, 120, 80]
    arrival_capacities = [150, 120, 80]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(routes) == len(costs) == len(departure_capacities) == len(arrival_capacities), "Array length mismatch"
    safe_range = range(min(len(routes), len(costs), len(departure_capacities), len(arrival_capacities)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: number of flights on each route
    x = {i: mdl.integer_var(name=f"x_{routes[i]}", lb=1) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total cost of operating all flights
    objective = mdl.sum(costs[i] * x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Route Coverage: Each route must be covered by at least one flight
    for i in safe_range:
        mdl.add_constraint(x[i] >= 1, ctname=f"route_coverage_{routes[i]}")
    
    # Airport Departure Capacity: Total flights departing from any airport must not exceed its capacity
    for i in safe_range:
        mdl.add_constraint(x[i] <= departure_capacities[i], ctname=f"departure_capacity_{routes[i]}")
    
    # Airport Arrival Capacity: Total flights arriving at any airport must not exceed its capacity
    for i in safe_range:
        mdl.add_constraint(x[i] <= arrival_capacities[i], ctname=f"arrival_capacity_{routes[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])
            print(f"Flights on route {routes[i]}: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    flight_optimization()