#!/usr/bin/env python3
"""
DOCplex 2.29.245 Implementation for Flight Scheduling Optimization
"""

from docplex.mp.model import Model

def flight_scheduling_optimization():
    """Optimize flight assignments to minimize total fuel consumption."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="flight_scheduling")
    
    # Example data (replace with actual data loading from database)
    flights = [1, 2, 3]
    airports = [1, 2, 3]
    companies = [1, 2, 3]
    
    fuel_coefficients = {1: 0.5, 2: 0.6, 3: 0.7}
    airport_capacities = {1: 10, 2: 15, 3: 20}
    company_capacities = {1: 5, 2: 10, 3: 15}
    
    # Validate array lengths
    assert len(flights) == len(fuel_coefficients), "Flight data mismatch"
    assert len(airports) == len(airport_capacities), "Airport data mismatch"
    assert len(companies) == len(company_capacities), "Company data mismatch"
    
    # 2. VARIABLES
    # Binary decision variable: x[f, a, c] = 1 if flight f is assigned to airport a and company c
    x = mdl.binary_var_cube(flights, airports, companies, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total fuel consumption
    objective = mdl.sum(fuel_coefficients[f] * x[f, a, c] for f in flights for a in airports for c in companies)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Flight Assignment Constraint: Each flight must be assigned to exactly one airport and one company
    for f in flights:
        mdl.add_constraint(mdl.sum(x[f, a, c] for a in airports for c in companies) == 1, ctname=f"flight_assignment_{f}")
    
    # Airport Capacity Constraint: Total flights assigned to an airport cannot exceed its capacity
    for a in airports:
        mdl.add_constraint(mdl.sum(x[f, a, c] for f in flights for c in companies) <= airport_capacities[a], ctname=f"airport_capacity_{a}")
    
    # Company Capacity Constraint: Total flights assigned to a company cannot exceed its capacity
    for c in companies:
        mdl.add_constraint(mdl.sum(x[f, a, c] for f in flights for a in airports) <= company_capacities[c], ctname=f"company_capacity_{c}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for f in flights:
            for a in airports:
                for c in companies:
                    if solution.get_value(x[f, a, c]) > 0.5:  # Check if assigned
                        print(f"Flight {f} assigned to Airport {a} and Company {c}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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