"""
Statistical helpers for carrier analysis.
"""

def find_carrier_gap(carriers_data):
    """
    Find best and worst carriers, calculate percentage point gap.

    Returns: { 'best_carrier': 'DL', 'worst_carrier': 'NK', 'gap_pp': 23.7 }
    """
    if len(carriers_data) < 2:
        return None

    sorted_carriers = sorted(
        carriers_data.items(),
        key=lambda x: x[1]['pct_delayed']
    )

    best_carrier, best_data = sorted_carriers[0]
    worst_carrier, worst_data = sorted_carriers[-1]
    gap = (worst_data['pct_delayed'] - best_data['pct_delayed']) * 100

    return {
        'best_carrier': best_carrier,
        'best_pct': best_data['pct_delayed'],
        'worst_carrier': worst_carrier,
        'worst_pct': worst_data['pct_delayed'],
        'gap_pp': round(gap, 1)
    }

def classify_gap(gap_pp):
    """Traffic light classification for carrier gap."""
    if gap_pp < 5:
        return 'low'       # carriers are similar
    elif gap_pp < 15:
        return 'moderate'  # noticeable difference
    else:
        return 'high'      # major gap