# Complete PYOMO implementation

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

def flight_optimization():
    """Optimize flight allocation to maximize passenger transport"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Passenger capacities for each route
    passenger_capacities = [150, 200, 250]
    n_routes = len(passenger_capacities)
    
    # CRITICAL: Validate array lengths before indexing
    assert n_routes == 3, "Expected 3 routes based on problem statement"
    
    # 3. SETS
    model.R = pyo.RangeSet(1, n_routes)  # 1-based indexing for routes
    
    # 4. PARAMETERS
    model.passenger_capacity = pyo.Param(model.R, initialize={i+1: passenger_capacities[i] for i in range(n_routes)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.R, within=pyo.NonNegativeIntegers, bounds=(1, 5))  # At least 1 flight, at most 5 flights per route
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.passenger_capacity[i] * model.x[i] for i in model.R)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total number of flights constraint
    def total_flights_rule(model):
        return sum(model.x[i] for i in model.R) <= 12
    model.total_flights_constraint = pyo.Constraint(rule=total_flights_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    # Check solver status
    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 allocations:")
        for i in model.R:
            x_val = pyo.value(model.x[i])
            print(f"Route {i}: {x_val} flights")
        
    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
flight_optimization()