#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Flight Optimization Problem
"""

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

def flight_optimization():
    """Optimize flight operations to minimize costs while ensuring efficient use of airport resources."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    routes = ['NYC-LAX', 'CHI-MIA', 'SEA-DEN']
    costs = {'NYC-LAX': 4500, 'CHI-MIA': 3500, 'SEA-DEN': 3000}
    airport_capacities = {'JFK': 150, 'ORD': 120, 'SEA': 80}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(routes) == len(costs), "Route and cost array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.R = pyo.Set(initialize=routes)  # Set of routes
    
    # 4. PARAMETERS (data containers)
    model.cost = pyo.Param(model.R, initialize=costs)
    model.departure_capacity = pyo.Param(initialize=airport_capacities)
    model.arrival_capacity = pyo.Param(initialize=airport_capacities)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.R, within=pyo.NonNegativeIntegers)  # Number of flights per route
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[r] * model.x[r] for r in model.R)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Route Coverage: Each route must be covered by at least one flight
    def route_coverage_rule(model, r):
        return model.x[r] >= 1
    model.route_coverage = pyo.Constraint(model.R, rule=route_coverage_rule)
    
    # Airport Departure Capacity: Total flights departing from any airport must not exceed its capacity
    def departure_capacity_rule(model, a):
        return sum(model.x[r] for r in model.R if a in r) <= model.departure_capacity[a]
    model.departure_capacity_constraint = pyo.Constraint(airport_capacities.keys(), rule=departure_capacity_rule)
    
    # Airport Arrival Capacity: Total flights arriving at any airport must not exceed its capacity
    def arrival_capacity_rule(model, a):
        return sum(model.x[r] for r in model.R if a in r) <= model.arrival_capacity[a]
    model.arrival_capacity_constraint = pyo.Constraint(airport_capacities.keys(), rule=arrival_capacity_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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)  # tee=True shows solver output
    
    # 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("\nVariable values:")
        for r in model.R:
            x_val = pyo.value(model.x[r])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{r}] = {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

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