""" CNIC verification and fake-report accountability service. Domain ownership ---------------- - CNIC format validation - User lookup by Firebase uid - Atomic strike increment + state transitions (warned → blacklisted) Strike state machine -------------------- 0-2 → strike_recorded (silent) 3 → warned=True (FCM warning sent by Phase 10) 4+ → blacklisted=True (FCM blacklist sent by Phase 10) The transition logic lives here; FCM dispatch lives in Phase 10. This module only updates Firestore state and returns the action taken. """ from __future__ import annotations import re from google.cloud.firestore import FieldFilter, async_transactional from backend.core.firebase import get_async_db CNIC_PATTERN = re.compile(r"^\d{5}-\d{7}-\d$") def validate_cnic_format(cnic: str) -> bool: """Return True iff `cnic` matches the Pakistani XXXXX-XXXXXXX-X format.""" return bool(CNIC_PATTERN.match(cnic)) async def get_user_by_uid(uid: str) -> dict | None: """Fetch the user record whose `uid` field matches the given Firebase uid. The Firestore `users` collection is keyed by CNIC, so this is a query rather than a direct document lookup. Returns: User dict with a `cnic` key added (the document ID), or None if no matching record exists. """ db = get_async_db() query = db.collection("users").where(filter=FieldFilter("uid", "==", uid)) async for doc in query.stream(): return {"cnic": doc.id, **doc.to_dict()} return None # ── Atomic strike increment ──────────────────────────────────────────────── # # Defined at module level so @async_transactional can wrap it correctly. # The decorator handles retry on contention — the function body must be # idempotent with respect to Firestore writes. @async_transactional async def _apply_strike(transaction, user_ref) -> dict: """Transactional inner function — must only be called via record_false_report.""" snap = await user_ref.get(transaction=transaction) if not snap.exists: raise ValueError(f"User document {user_ref.id!r} not found in Firestore") data = snap.to_dict() new_count = (data.get("strike_count") or 0) + 1 updates: dict = {"strike_count": new_count} if new_count == 3: updates["warned"] = True action = "warned" elif new_count >= 4: updates["blacklisted"] = True action = "blacklisted" else: action = "strike_recorded" transaction.update(user_ref, updates) return {"action": action, "strike_count": new_count} async def record_false_report(cnic: str) -> dict: """Atomically increment the strike count for a CNIC and apply state transitions. Uses a Firestore transaction so concurrent calls cannot produce a split-brain where the counter and the flags disagree. Args: cnic: The document ID of the user in the `users` collection. Returns: {"action": "strike_recorded" | "warned" | "blacklisted", "strike_count": } Raises: ValueError: If no user document exists for `cnic`. """ db = get_async_db() user_ref = db.collection("users").document(cnic) transaction = db.transaction() return await _apply_strike(transaction, user_ref)