# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_flight_schedule():
    """Optimize flight schedule to minimize operational costs."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="flight_optimization")
    
    # Data: Costs and mandatory flights
    flight_costs = {'FL123': 1200.0, 'FL456': 2500.0, 'FL789': 1800.0}
    mandatory_flights = {'FL789', 'FL101', 'FL202'}
    
    # Parameters
    max_flights = 5  # Example parameter for maximum flights
    max_departures = {'AirportA': 3, 'AirportB': 2}  # Example airport departure limits
    max_arrivals = {'AirportA': 3, 'AirportB': 2}  # Example airport arrival limits
    
    # CRITICAL: Validate array lengths to prevent IndexError
    flight_numbers = list(flight_costs.keys())
    assert len(flight_numbers) == len(flight_costs), "Array length mismatch"
    safe_range = range(len(flight_numbers))  # Safe indexing
    
    # 2. VARIABLES
    x = {flight: mdl.binary_var(name=f"x_{flight}") for flight in flight_numbers}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(flight_costs[flight] * x[flight] for flight in flight_numbers)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Maximum number of flights operated
    mdl.add_constraint(mdl.sum(x[flight] for flight in flight_numbers) <= max_flights, ctname="max_flights")
    
    # Mandatory flights
    for flight in mandatory_flights:
        if flight in x:
            mdl.add_constraint(x[flight] == 1, ctname=f"mandatory_{flight}")
    
    # Maximum departures from each airport
    for airport, max_dep in max_departures.items():
        # Example: flights departing from airport
        departures_from_airport = [flight for flight in flight_numbers if flight.startswith('FL')]
        mdl.add_constraint(mdl.sum(x[flight] for flight in departures_from_airport) <= max_dep, ctname=f"max_departures_{airport}")
    
    # Maximum arrivals at each airport
    for airport, max_arr in max_arrivals.items():
        # Example: flights arriving at airport
        arrivals_at_airport = [flight for flight in flight_numbers if flight.startswith('FL')]
        mdl.add_constraint(mdl.sum(x[flight] for flight in arrivals_at_airport) <= max_arr, ctname=f"max_arrivals_{airport}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for flight in flight_numbers:
            value = solution.get_value(x[flight])
            if value > 1e-6:
                print(f"x[{flight}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_flight_schedule()