File size: 7,586 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""
Crowd verification orchestrator β€” Phase 10.

Owns:
  - Sending FCM verification prompts to nearby users (via radius query)
  - Storing crowd responses on the crisis Firestore document
  - Evaluating confirmation/denial counts to produce a verdict
  - Calling record_false_report() on the original reporter for denied verdicts
  - Dispatching FCM warning/blacklist notices when those strikes land

Does NOT own:
  - Strike rules (services/cnic.py β€” Phase 9)
  - NGO escalation (Phase 11)
  - Map display of helper locations (mobile Phase 5)
"""

from __future__ import annotations

import logging

from google.cloud.firestore import SERVER_TIMESTAMP

from backend.core.firebase import get_async_db
from backend.services.cnic import record_false_report
from backend.services.fcm import send_blacklist_notice, send_strike_warning, send_verification_prompt
from backend.services.radius_query import DEFAULT_RADIUS_KM, get_users_within_radius

logger = logging.getLogger(__name__)

CONFIRMATION_THRESHOLD: float = 0.6
DENIAL_THRESHOLD: float = 0.3


# ── Pure decision function (no I/O β€” fully unit-testable) ────────────────────


def evaluate_verification(confirmations: int, denials: int) -> str:
    """Return the crowd verification verdict from raw response counts.

    Rules (single source of truth):
      total == 0                          β†’ "inconclusive"
      confirmation_rate >= 0.6            β†’ "confirmed"
      confirmation_rate <= 0.3            β†’ "denied"
      between thresholds                  β†’ "inconclusive"

    Args:
        confirmations: Count of "confirm" + "help" responses received.
        denials:       Count of "deny" responses received.

    Returns:
        One of: "confirmed", "denied", "inconclusive".
    """
    total = confirmations + denials
    if total == 0:
        return "inconclusive"
    rate = confirmations / total
    if rate >= CONFIRMATION_THRESHOLD:
        return "confirmed"
    if rate <= DENIAL_THRESHOLD:
        return "denied"
    return "inconclusive"


# ── Outbound: fan out prompts to nearby users ─────────────────────────────────


async def send_verification_prompts(
    crisis_id: str,
    crisis_type: str,
    location_label: str,
    lat: float,
    lon: float,
    radius_km: float = DEFAULT_RADIUS_KM,
) -> dict:
    """Query users within radius and fire FCM verification prompts to each one.

    Initialises the crisis document's verification counters on Firestore so
    the verify endpoint can do atomic increments against a known baseline.

    Args:
        crisis_id:      Firestore document ID of the crisis.
        crisis_type:    Human-readable crisis label (e.g. "flood").
        location_label: Human-readable area name shown in the notification.
        lat:            Crisis latitude.
        lon:            Crisis longitude.
        radius_km:      Search radius. Defaults to DEFAULT_RADIUS_KM (1 km).

    Returns:
        {"users_found": int, "users_notified": int}
    """
    nearby = await get_users_within_radius(lat, lon, radius_km)
    notified = 0
    for user in nearby:
        ok = await send_verification_prompt(
            token=user.fcm_token,
            crisis_id=crisis_id,
            crisis_type=crisis_type,
            location=location_label,
        )
        if ok:
            notified += 1

    db = get_async_db()
    await db.collection("crises").document(crisis_id).update({
        "verification_status": "pending",
        "users_notified": notified,
        "confirmations": 0,
        "denials": 0,
        "helpers": [],
        "verification_sent_at": SERVER_TIMESTAMP,
    })

    logger.info(
        "Crowd verification: notified %d/%d users near crisis %s",
        notified, len(nearby), crisis_id,
    )
    return {"users_found": len(nearby), "users_notified": notified}


# ── Inbound: handle a user's verification response ────────────────────────────


async def process_verification_response(
    crisis_id: str,
    cnic: str,
    response: str,
) -> dict:
    """Store a crowd verification response and re-evaluate the verdict.

    Args:
        crisis_id: Firestore document ID of the crisis being verified.
        cnic:      Responding user's CNIC (resolved server-side from JWT).
        response:  One of "confirm", "deny", "help".
                   "help" = confirm + volunteer to assist on-ground.

    Returns:
        {"verdict": str, "confirmations": int, "denials": int}

    Side effects:
      - Updates crisis.confirmations / crisis.denials / crisis.helpers
      - Updates crisis.verification_result
      - On "denied" verdict: calls record_false_report() on the original
        reporter and dispatches the appropriate FCM notice (warning or
        blacklist) if a state transition occurs.

    Raises:
        ValueError: If no crisis document exists for `crisis_id`.
    """
    db = get_async_db()
    crisis_ref = db.collection("crises").document(crisis_id)
    doc = await crisis_ref.get()
    if not doc.exists:
        raise ValueError(f"Crisis {crisis_id!r} not found in Firestore")

    data = doc.to_dict()
    confirmations: int = data.get("confirmations", 0)
    denials: int = data.get("denials", 0)
    helpers: list[str] = list(data.get("helpers", []))
    reporter_cnic: str | None = data.get("reporter_cnic")

    if response == "confirm":
        confirmations += 1
        await crisis_ref.update({"confirmations": confirmations})
    elif response == "deny":
        denials += 1
        await crisis_ref.update({"denials": denials})
    elif response == "help":
        confirmations += 1
        if cnic not in helpers:
            helpers.append(cnic)
        await crisis_ref.update({"confirmations": confirmations, "helpers": helpers})

    verdict = evaluate_verification(confirmations, denials)
    await crisis_ref.update({
        "verification_result": verdict,
        "verification_updated_at": SERVER_TIMESTAMP,
    })

    if verdict == "denied" and reporter_cnic:
        await _handle_denied_verdict(reporter_cnic)

    return {"verdict": verdict, "confirmations": confirmations, "denials": denials}


async def _handle_denied_verdict(reporter_cnic: str) -> None:
    """Record a false report strike and dispatch FCM notice if warranted.

    Only sends a notification when the strike causes a state transition
    (warned or blacklisted). Silent strikes (1 and 2) produce no FCM.
    """
    try:
        strike_result = await record_false_report(reporter_cnic)
    except ValueError as exc:
        logger.warning("record_false_report failed for %s: %s", reporter_cnic, exc)
        return

    action = strike_result.get("action")
    logger.info("False report strike for %s: %s (count=%s)", reporter_cnic, action, strike_result.get("strike_count"))

    if action not in ("warned", "blacklisted"):
        return

    db = get_async_db()
    user_doc = await db.collection("users").document(reporter_cnic).get()
    if not user_doc.exists:
        return

    token: str | None = user_doc.to_dict().get("fcm_token")
    if not token:
        return

    if action == "warned":
        # strikes_remaining = how many more before blacklist (always 1 at count=3)
        strikes_remaining = 4 - strike_result["strike_count"]
        await send_strike_warning(token=token, strikes_remaining=strikes_remaining)
    elif action == "blacklisted":
        await send_blacklist_notice(token=token)