# Complete PYOMO implementation - Retry Attempt 4

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

def flight_company_optimization():
    """Optimize flight assignments to minimize operational costs."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define the data based on the provided database schema and current stored values
    flight_ids = [1, 2, 3]
    airport_ids = [101, 102, 103]
    
    distances = {
        (1, 101): 550.0,
        (2, 102): 800.0,
        (3, 103): 950.0
    }
    
    fee_rates = {
        101: 12.0,
        102: 18.0,
        103: 22.0
    }
    
    capacities = {
        101: 120,
        102: 180,
        103: 150
    }
    
    # CRITICAL: Validate data consistency
    assert all((i, j) in distances for i in flight_ids for j in airport_ids), "Data length mismatch"
    
    # 3. SETS
    model.F = pyo.Set(initialize=flight_ids)
    model.A = pyo.Set(initialize=airport_ids)
    
    # 4. PARAMETERS
    model.distance = pyo.Param(model.F * model.A, initialize=distances, within=pyo.NonNegativeReals)
    model.fee_rate = pyo.Param(model.A, initialize=fee_rates, within=pyo.NonNegativeReals)
    model.capacity = pyo.Param(model.A, initialize=capacities, within=pyo.NonNegativeIntegers)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.F, model.A, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.distance[i, j] * model.fee_rate[j] * model.x[i, j] for i in model.F for j in model.A)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Each flight must be assigned to exactly one airport
    def flight_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.A) == 1
    model.flight_assignment_constraint = pyo.Constraint(model.F, rule=flight_assignment_rule)
    
    # The total number of flights assigned to an airport must not exceed its capacity
    def airport_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.F) <= model.capacity[j]
    model.airport_capacity_constraint = pyo.Constraint(model.A, rule=airport_capacity_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)}")
        
        # Extract variable values
        print("\nFlight assignments:")
        for i in model.F:
            for j in model.A:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Flight {i} assigned to Airport {j}")
        
    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}")

# Run the optimization
flight_company_optimization()