""" FCM Notification Service — single source of truth for all push notifications. All notification types (verification prompts, area alerts, strike warnings, blacklist notices) are dispatched through this module. No other module should call firebase_admin.messaging directly. Failure policy: a failed FCM send is logged and returns False — it must never crash the pipeline. FCM is best-effort for the demo. """ from __future__ import annotations import asyncio import logging from firebase_admin import messaging logger = logging.getLogger(__name__) async def send_notification( token: str, title: str, body: str, data: dict[str, str] | None = None, ) -> bool: """Send a push notification to a single device token. Args: token: FCM device registration token. title: Notification title shown on the device. body: Notification body text. data: Optional key-value payload delivered alongside the visual notification. All values must be strings (FCM requirement). Returns: True on success, False on any failure (token invalid, quota, etc.). """ if not token: logger.warning("send_notification called with empty token — skipped") return False message = messaging.Message( notification=messaging.Notification(title=title, body=body), data={k: str(v) for k, v in (data or {}).items()}, token=token, ) try: # messaging.send() is synchronous — run in thread to stay non-blocking. await asyncio.to_thread(messaging.send, message) return True except messaging.UnregisteredError: logger.warning("FCM token unregistered — device removed app: %.20s…", token) return False except Exception as exc: # noqa: BLE001 logger.warning("FCM send failed: %s", exc) return False async def send_verification_prompt( token: str, crisis_id: str, crisis_type: str, location: str, ) -> bool: """Ask a nearby user to confirm or deny a reported crisis. Payload delivered to the mobile app: type = "verification_prompt" crisis_id = crisis_type = e.g. "flood" """ return await send_notification( token=token, title="Crisis reported near you", body=f"A {crisis_type} has been reported near {location}. Can you confirm?", data={ "type": "verification_prompt", "crisis_id": crisis_id, "crisis_type": crisis_type, }, ) async def send_area_alert( token: str, crisis_type: str, location: str, action: str, ) -> bool: """Notify a user that a crisis is active in their area.""" return await send_notification( token=token, title=f"Crisis alert: {crisis_type} in {location}", body=action, data={"type": "area_alert", "crisis_type": crisis_type}, ) async def send_strike_warning(token: str, strikes_remaining: int) -> bool: """Warn a user that they are close to being blacklisted.""" return await send_notification( token=token, title="False report warning", body=( f"Warning: you have received {3 - strikes_remaining + 1} false report " "strikes. One more false report will permanently block your account." ), data={"type": "strike_warning"}, ) async def send_blacklist_notice(token: str) -> bool: """Notify a user that their account has been permanently blocked.""" return await send_notification( token=token, title="Account blocked", body="Your account has been permanently blocked due to repeated false reports.", data={"type": "blacklist_notice"}, ) async def send_ngo_alert( token: str, crisis_id: str, crisis_type: str, location: str, severity: int, response_plan_summary: str, ) -> bool: """Dispatch a real-time escalation alert to an NGO device. This is a real notification to a real device — it is NOT simulated. The NGO representative's device receives the push; tapping it opens the crisis detail screen (handled by the mobile FCM handler). Payload delivered to the app: type = "ngo_escalation" crisis_id = crisis_type = e.g. "flood" location = human-readable area name severity = stringified int (FCM data values must be strings) response_plan_summary = short summary of the planned response """ return await send_notification( token=token, title="\U0001f6a8 Crisis Alert — Response Required", body=( f"Confirmed {crisis_type} in {location}. " f"Severity: {severity}/5. {response_plan_summary}" ), data={ "type": "ngo_escalation", "crisis_id": crisis_id, "crisis_type": crisis_type, "location": location, "severity": str(severity), "response_plan_summary": response_plan_summary, }, )