"""A deterministic, real-signal-only estimate of how many days a FAR B2B
truck order takes to arrive after payment is confirmed — used to give the
customer a reasonable delivery-date window instead of always offering
"starting tomorrow" regardless of how far the route actually is.

Every input here is a real, already-computed signal (routed distance, the
Overpass-derived road-surface check, real truck-type capacity tiers) —
deliberately not a live weather forecast, since (see
market/views.py::_quick_delivery_weather_note) no forecast API exists in
this app and HERE's weather call only returns current conditions, useless
for a delivery days away."""

import math

# Matches the low end of the existing 24-48hr assignment-SLA language
# already shown to admins/pickers elsewhere (see market/fleet.py::
# get_assignment_sla_badge) -- not a new number, just reused here.
_PROCESSING_DAYS = 1


def estimate_b2b_delivery_window(distance_km, total_weight_kg=None, route_picker_ok=None):
    """(min_days, max_days) from order confirmation. `route_picker_ok` is
    the `picker_ok` flag from market/geo.py::get_route_surface_summary
    (None if the check was never run or came back inconclusive) -- reusing
    that exact signal rather than re-deriving a second paved-road threshold
    that could drift out of sync with it."""
    from .site_settings import get_b2b_km_per_day

    travel_days = math.ceil(distance_km / get_b2b_km_per_day()) if distance_km else 0
    min_days = _PROCESSING_DAYS + travel_days

    extra_days = 0
    if route_picker_ok is False:
        # Rough-road buffer -- stands in for the combined unload/separate/
        # verify handling that a difficult route also tends to slow down.
        # There's no real per-order signal (crew size, cargo type) to split
        # that into three separate numbers, so one grounded buffer tied to
        # the real Overpass-derived road check is more honest than three
        # invented ones.
        extra_days += 1
    if total_weight_kg is not None and _requires_largest_truck_tier(total_weight_kg):
        extra_days += 1

    return min_days, min_days + extra_days


def _requires_largest_truck_tier(total_weight_kg):
    """True when the order is heavy enough that only the single largest
    active truck type could carry it -- a genuinely heavy load takes
    longer to load, unload, and separate."""
    from .truck_types import get_active_truck_types

    types = sorted(get_active_truck_types(segment='b2b'), key=lambda t: float(t['max_weight_kg']))
    if len(types) < 2:
        return False
    second_largest_cap = float(types[-2]['max_weight_kg'])
    return float(total_weight_kg) > second_largest_cap
