# Complete PYOMO implementation

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

def aircraft_optimization():
    """Optimize aircraft allocation to maximize passenger transport"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    aircraft_ids = [1, 2, 3]
    airport_ids = [1, 2, 3]
    capacities = {1: 150, 2: 180, 3: 200}
    number_of_aircraft = {1: 3, 2: 5, 3: 7}
    movement_limits = {1: 10, 2: 15, 3: 20}

    # CRITICAL: Validate array lengths before indexing
    assert len(capacities) == len(aircraft_ids), "Capacity data length mismatch"
    assert len(number_of_aircraft) == len(airport_ids), "Aircraft data length mismatch"
    assert len(movement_limits) == len(airport_ids), "Movement limit data length mismatch"

    # 3. SETS
    model.I = pyo.Set(initialize=aircraft_ids)
    model.J = pyo.Set(initialize=airport_ids)

    # 4. PARAMETERS
    model.capacity = pyo.Param(model.I, initialize=capacities)
    model.number_of_aircraft = pyo.Param(model.J, initialize=number_of_aircraft)
    model.movement_limit = pyo.Param(model.J, initialize=movement_limits)

    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.NonNegativeIntegers)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.capacity[i] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS

    # Aircraft Capacity Constraint
    def aircraft_capacity_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.number_of_aircraft[i]
    model.aircraft_capacity_constraint = pyo.Constraint(model.I, rule=aircraft_capacity_rule)

    # Airport Movement Constraint
    def airport_movement_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.movement_limit[j]
    model.airport_movement_constraint = pyo.Constraint(model.J, rule=airport_movement_rule)

    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')

    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap

    # 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("\nVariable values:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i},{j}] = {x_val:.3f}")

    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
aircraft_optimization()