import math

_EARTH_RADIUS_KM = 6371.0


def haversine_km(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
    """Great-circle distance between two lat/long points, in kilometers.

    Used for app.services.pricing's delivery fee (branch to delivery
    address) — deliberately plain Python, not a PostGIS query, since
    it's a distance between exactly two known points rather than a
    sort over many candidate rows. That also means it works
    identically on SQLite and Postgres, unlike the ST_Distance-based
    nearest-branch/nearest-courier queries in
    app.api.v1.endpoints.merchants and app.services.dispatch, which
    need PostGIS specifically because they're ordering a whole table
    by distance.
    """
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi = math.radians(lat2 - lat1)
    dlambda = math.radians(lng2 - lng1)
    a = (
        math.sin(dphi / 2) ** 2
        + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
    )
    return 2 * _EARTH_RADIUS_KM * math.asin(math.sqrt(a))
