"""
Core analysis: Compare carrier performance on same routes.
"""
import pandas as pd

def compute_carrier_comparison(df):
    """
    Group flights by route and carrier, compute delay metrics.

    Returns dict: { "LAX-SFO": { "UA": {...}, "WN": {...} } }
    """
    # Filter out cancelled/diverted flights
    df = df[(df['cancelled'] == 0) & (df['diverted'] == 0)].copy()

    # Group by route and carrier
    grouped = df.groupby(['origin', 'dest', 'carrier']).agg({
        'arr_del15': ['count', 'sum', 'mean'],
        'arr_delay': 'mean',
        'carrier_delay': 'mean'
    }).reset_index()

    # Flatten column names
    grouped.columns = ['origin', 'dest', 'carrier',
                       'flight_count', 'delayed_count', 'pct_delayed',
                       'avg_delay', 'avg_carrier_delay']

    # Only keep routes with multiple carriers — need something to compare
    routes_multi = grouped.groupby(['origin', 'dest']).filter(lambda x: len(x) >= 2)

    result = {}
    for _, row in routes_multi.iterrows():
        route_key = f"{row['origin']}-{row['dest']}"
        if route_key not in result:
            result[route_key] = {}
        result[route_key][row['carrier']] = {
            'flight_count': int(row['flight_count']),
            'pct_delayed': float(row['pct_delayed']),
            'avg_delay': float(row['avg_delay']) if pd.notna(row['avg_delay']) else None,
            'avg_carrier_delay': float(row['avg_carrier_delay']) if pd.notna(row['avg_carrier_delay']) else None,
        }

    return result