File size: 2,625 Bytes
1ffd0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
Radius-based Firestore user query for crowd verification.

Firestore lacks native geo-radius support; this module fetches all verified,
non-blacklisted users and filters in Python using the Haversine formula.
Acceptable for demo scale (hundreds of users). Production would use
GeoFirestore or server-side geo-hash indexing.

Only users who have BOTH `last_location` and `fcm_token` set are returned —
no token means we cannot notify them; no location means we cannot check their
proximity.
"""

from __future__ import annotations

import math
from typing import NamedTuple

from google.cloud.firestore import FieldFilter

from backend.core.firebase import get_async_db

DEFAULT_RADIUS_KM: float = 1.0


class NearbyUser(NamedTuple):
    cnic: str
    fcm_token: str
    distance_km: float


def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """Return great-circle distance in km between two WGS-84 points."""
    R = 6371.0
    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = (
        math.sin(dlat / 2) ** 2
        + math.cos(math.radians(lat1))
        * math.cos(math.radians(lat2))
        * math.sin(dlon / 2) ** 2
    )
    return R * 2 * math.asin(math.sqrt(a))


async def get_users_within_radius(
    lat: float,
    lon: float,
    radius_km: float = DEFAULT_RADIUS_KM,
) -> list[NearbyUser]:
    """Return verified app users within `radius_km` of (lat, lon).

    Args:
        lat: Crisis latitude in WGS-84 decimal degrees.
        lon: Crisis longitude in WGS-84 decimal degrees.
        radius_km: Search radius. Defaults to DEFAULT_RADIUS_KM (1 km).

    Returns:
        List of NearbyUser tuples sorted by distance ascending. Empty list
        when no eligible users are found or Firestore returns no results.
    """
    db = get_async_db()
    query = (
        db.collection("users")
        .where(filter=FieldFilter("verified", "==", True))
        .where(filter=FieldFilter("blacklisted", "==", False))
    )

    nearby: list[NearbyUser] = []
    async for doc in query.stream():
        data = doc.to_dict()
        token: str | None = data.get("fcm_token")
        loc: dict | None = data.get("last_location")
        if not token or not loc:
            continue
        ulat = loc.get("lat")
        ulon = loc.get("lon")
        if ulat is None or ulon is None:
            continue
        dist = _haversine(lat, lon, float(ulat), float(ulon))
        if dist <= radius_km:
            nearby.append(NearbyUser(cnic=doc.id, fcm_token=token, distance_km=dist))

    nearby.sort(key=lambda u: u.distance_km)
    return nearby