"""Route statistics and risk classification."""
import os

# thresholds
MIN_ROUTE_FLIGHTS   = int(os.getenv("MIN_ROUTE_FLIGHTS",  "500"))                                                                                                                                                                             
MIN_CARRIER_FLIGHTS = int(os.getenv("MIN_CARRIER_FLIGHTS", "100"))
MIN_CHAIN_OBS       = int(os.getenv("MIN_CHAIN_OBS",      "30"))   
MAX_UPSTREAM = 5
MAX_DOWNSTREAM = 5

def est_pax(flight_count, distance):
    """Estimate passenger impact using typical seat counts * 85% load factor."""
    if distance and distance < 500:
        seats = 76    # regional jet
    elif distance and distance > 1500:
        seats = 280   # wide body
    else:
        seats = 160   # narrow body (most domestic)
    return int(flight_count * seats * 0.85)


def classify_risk(pct):
    """Traffic light classification for a time window's pct_delayed."""
    if pct < 0.20:
        return "low"
    elif pct < 0.30:
        return "moderate"
    return "high"


def generate_reason(tw, risk, upstream_links):
    """Short explanation for why a time window has its risk level."""
    if not upstream_links:
        if tw == "morning":
            return "Aircraft overnights here, fresh start"
        return "No upstream chain data"

    worst = max(upstream_links, key=lambda x: x["avg_delay_inherited"])

    if risk == "low":
        if tw == "morning":
            return "Fresh aircraft, minimal upstream delays"
        return "Short rotation chains, low inherited delays"
    elif risk == "moderate":
        return f"Mid-day rotations, some delays from {worst['origin']}"
    else:
        return f"Long chains, {worst['avg_delay_inherited']:.0f}min inherited from {worst['origin']}"


def compute_verdict(time_data):
    """Figure out best/worst time window."""
    windows = {}
    for tw in ["morning", "afternoon", "evening"]:
        if tw in time_data:
            windows[tw] = time_data[tw].get("pct_delayed", 0.5)

    if not windows:
        return None

    best = min(windows, key=windows.get)
    worst = max(windows, key=windows.get)

    return {
        "best_time": best,
        "worst_time": worst,
    }
