diff --git "a/app/hadith.py" "b/app/hadith.py" new file mode 100644 --- /dev/null +++ "b/app/hadith.py" @@ -0,0 +1,4825 @@ +# ========================================================= + +# 1. IMPORTS & DEPENDENCIES + +# ========================================================= + +import os + +import sys + + + +if sys.platform == "win32": + + class _SafeStream: + + def __init__(self, target): + + self._target = target + + def write(self, s): + + try: + + self._target.write(s) + + except UnicodeEncodeError: + + self._target.write(s.encode("ascii", errors="replace").decode("ascii")) + + def flush(self): + + if hasattr(self._target, "flush"): + + self._target.flush() + + def __getattr__(self, name): + + return getattr(self._target, name) + + + + if not isinstance(sys.stdout, _SafeStream): + + sys.stdout = _SafeStream(sys.stdout) + + if not isinstance(sys.stderr, _SafeStream): + + sys.stderr = _SafeStream(sys.stderr) + + + +import re + +import json + +import time + +import pickle + +import asyncio + +import logging + +import datetime + +import httpx + +import numpy as np + +import warnings + + + +from anyio import to_thread + +from contextlib import asynccontextmanager + +import uuid + +import inspect + +from fastapi import APIRouter, Request, Response, BackgroundTasks, Depends, HTTPException + +from fastapi.responses import StreamingResponse, JSONResponse + +from pydantic import BaseModel, Field, field_validator + +from typing import List, Optional, Dict, Any, Union, Tuple + + + +# Database & Auth + +from app.database import hadith_collection, chats_collection, vector_memory_collection, quran_collection + + +from app.hijri import gregorian_to_hijri + +from app.limiter import limiter + +from app.core.config import settings + +from app.auth_deps import get_current_user, get_optional_user, require_superadmin + +from app.redis_client import redis_manager + +from app.rag.cache import ( + + get_cached_canonical_documents, + + get_cached_canonical_pool, + + set_cached_canonical_documents, + + get_cached_llm_answer, + + set_cached_llm_answer, + + make_canonical_docs_key, + + get_corpus_revision, + + refresh_corpus_revision, + + register_cache_clear_hook, + + MAX_CANONICAL_CACHE_DOCS, + +) + +from app.rag.single_flight import single_flight_manager + +from app.rag.translations import ( + + select_hadith_translation, + + format_hadith_search_response, + + format_grade_string, + + extract_doc_narrator, + + extract_doc_sanad, + + extract_sanad_and_matn_from_text, + + get_language_display_name, + + is_quran_record, + + render_hadith_doc_block, + + _clean_non_empty, + + normalize_language_code, + +) + +from app.rag.analytics import record_search_metric + +import hashlib + + + +# ========================================================= + +# 2. SYSTEM CONFIGURATION & API ROUTING + +# ========================================================= + +SEARCH_CONFIG = { + + # 🔎 RECALL PROVISIONING (Atlas $vectorSearch / HNSW). + + # numCandidates is how many approximate neighbours the HNSW search + + # explores before returning the top `limit`. Atlas recommends it be + + # ~10–20x the limit; too low and the ANN search silently MISSES true + + # near-matches (this caused "how to perform wudu" to return only the + + # nearby ghusl hadith while the real wudu hadith — a slightly weaker + + # cosine match — never entered the pool the reranker sees). + + "vector_search_scope": 500, # numCandidates (HNSW search width) + + "max_vector_results": 50, # limit -> docs handed to the reranker + + "max_items_to_rerank": 10, + + + + # 🚀 RELEVANCE TUNING DIALS + + # We use the BI-ENCODER vector similarity as the relevance gate (it is + + # normalized 0..1 and stable across queries), and the CROSS-ENCODER + + # only to ORDER the survivors. This returns many results when many are + + # relevant (up to top_k) and none when the query is off-topic — unlike + + # a raw cross-encoder logit threshold, which is uncalibrated and drops + + # correct-but-paraphrased matches. + + # + + # minimum_vector_similarity is the Atlas $vectorSearch cosine score + + # (≈ (1 + cosine)/2): ~0.5 = unrelated, ~0.65+ = on-topic. Lower it for + + # more recall, raise it for more precision. + + "minimum_vector_similarity": 0.58, + + # 🎯 CROSS-ENCODER GATE. The reranker reads the full (query, doc) pair and + + # outputs a relevance LOGIT used both to ORDER and to gate. On this model + + # the logits run cold: a 250-question audit showed ~88% of "no result" + + # failures actually had a relevant hadith in the pool that a 0.0 gate was + + # cutting. Moving the gate to -1.75 lifted recall from ~39% to ~72% while + + # still rejecting clearly off-topic docs (which score well below -2). + + # Lower for more recall, raise toward 0 for stricter precision. + + # Cross-encoder reranking is disabled by default across all tiers (toggleable via tier config). + "cross_encoder_enabled": False, + + "minimum_rerank_logit": -1.75, + + "quran_context_similarity_threshold": 0.3, # How closely surrounding verses must match the topic to be included + +} + + + +# --- LLM API CREDENTIALS --- + +DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") + +XAI_API_KEY = os.getenv("XAI_API_KEY") + + + +# --- MANUAL LLM OVERRIDE SWITCHES --- + +FORCE_DEEPSEEK = 1 + +FORCE_XAI = 0 + + + +warnings.filterwarnings("ignore", category=UserWarning, module="huggingface_hub") + +warnings.filterwarnings("ignore", category=FutureWarning) + + + +logger = logging.getLogger("sahihislam.hadith") + +logger.setLevel(logging.INFO) + +router = APIRouter() + + + +# 🚀 SCALE & RESILIENCE: Measured, conservative HTTP Client Connection Pool (Loop-Aware) + +# Prevents connection exhaustion across multiple workers and cloud providers without cross-loop Future errors + +_hadith_http_clients: dict = {} + + + +def get_http_client() -> httpx.AsyncClient: + + try: + + loop = asyncio.get_running_loop() + + key = id(loop) + + except RuntimeError: + + key = 0 + + client = _hadith_http_clients.get(key) + + if client is None or client.is_closed: + + client = httpx.AsyncClient( + + limits=httpx.Limits(max_keepalive_connections=50, max_connections=100, keepalive_expiry=30.0) + + ) + + _hadith_http_clients[key] = client + + return client + + + +class _HttpClientProxy: + + def __getattr__(self, name): + + return getattr(get_http_client(), name) + + + +http_client = _HttpClientProxy() + + + +# Granular timeouts for each distinct pipeline stage + +TIMEOUT_EMBEDDING = httpx.Timeout(10.0, connect=3.0, read=8.0, write=4.0) + +TIMEOUT_RERANK = httpx.Timeout(12.0, connect=3.0, read=10.0, write=4.0) + +TIMEOUT_LLM_STREAM = httpx.Timeout(35.0, connect=5.0, read=20.0, write=5.0) + +TIMEOUT_LLM_FAST = httpx.Timeout(15.0, connect=4.0, read=12.0, write=4.0) + + + +# 🛡️ BOUNDED CONCURRENCY & QUEUE TIMEOUT CONTROLS (Weakness #2 Fix) + +# Enforces strict concurrency ceilings and wait timeouts around expensive downstream stages + +STAGE_CONCURRENCY_LIMITS = { + + "query_rewrite": 20, # Max 20 concurrent LLM query rewrites + + "embedding": 40, # Max 40 concurrent embedding calls + + "atlas_vector": 25, # Max 25 concurrent MongoDB Atlas vector searches + + "reranking": 20, # Max 20 concurrent cross-encoder rerank calls + + "llm_generation": 35, # Max 35 concurrent LLM streaming generation tasks + +} + +_stage_semaphores = {} + + + +def get_stage_semaphore(stage_name: str) -> Optional[asyncio.Semaphore]: + + limit = STAGE_CONCURRENCY_LIMITS.get(stage_name) + + if limit is None: + + return None + + try: + + loop = asyncio.get_running_loop() + + except RuntimeError: + + try: + + loop = asyncio.get_event_loop() + + except RuntimeError: + + loop = asyncio.new_event_loop() + + asyncio.set_event_loop(loop) + + key = (id(loop) if loop else 0, stage_name) + + if key not in _stage_semaphores: + + _stage_semaphores[key] = asyncio.Semaphore(limit) + + return _stage_semaphores[key] + + + +class _LazyStageConcurrency(dict): + + def __contains__(self, key): + + return key in STAGE_CONCURRENCY_LIMITS + + def __iter__(self): + + return iter(STAGE_CONCURRENCY_LIMITS) + + def __len__(self): + + return len(STAGE_CONCURRENCY_LIMITS) + + def keys(self): + + return STAGE_CONCURRENCY_LIMITS.keys() + + def values(self): + + return [get_stage_semaphore(k) for k in STAGE_CONCURRENCY_LIMITS] + + def items(self): + + return [(k, get_stage_semaphore(k)) for k in STAGE_CONCURRENCY_LIMITS] + + def get(self, key, default=None): + + sem = get_stage_semaphore(key) + + return sem if sem is not None else default + + def __getitem__(self, key): + + sem = get_stage_semaphore(key) + + if sem is None: + + raise KeyError(key) + + return sem + + + +STAGE_CONCURRENCY = _LazyStageConcurrency() + + + +STAGE_QUEUE_TIMEOUT_SEC = { + + "query_rewrite": 4.0, + + "embedding": 5.0, + + "atlas_vector": 6.0, + + "reranking": 6.0, + + "llm_generation": 8.0, + +} + + + +@asynccontextmanager + +async def bounded_stage(stage_name: str, timeout: Optional[float] = None): + + """Async context manager enforcing bounded concurrency and queue timeouts around expensive stages.""" + + sem = get_stage_semaphore(stage_name) + + if sem is None: + + yield + + return + + q_timeout = timeout or STAGE_QUEUE_TIMEOUT_SEC.get(stage_name, 5.0) + + acquired = False + + try: + + await asyncio.wait_for(sem.acquire(), timeout=q_timeout) + + acquired = True + + yield + + except asyncio.TimeoutError: + + logger.warning(f"[BACKPRESSURE] Queue timeout ({q_timeout}s) waiting for '{stage_name}' semaphore") + + raise HTTPException( + + status_code=503, + + detail=f"The AI search engine is currently handling high traffic. Please retry in a few moments. (Stage: {stage_name})" + + ) + + finally: + + if acquired: + + sem.release() + + + + + + + +# ========================================================= + +# 3. EMBEDDED INTENT EXAMPLES (NO CONVERSATION CATEGORY) + +# ========================================================= + +INTENT_EXAMPLES = { + + "hadith_search": [ + + "give me hadith about fasting", + + "what did prophet say about charity", + + "hadith on intention and rewards", + + "show me hadiths regarding prayer", + + "is there any hadith about smiling" + + ], + + "hadith_by_number": [ + + "sahih bukhari hadith 1", + + "muslim 456", + + "hadith no 500", + + "tirmidhi hadith number 20", + + "give me bukhari 2" + + ], + + "quran_search": [ + + "surah baqarah ayat 2", + + "what does quran say about patience", + + "quran verse about fasting", + + "chapter 2 verse 255", + + "show me surah yaseen" + + ], + + "greeting": [ + + "salam", + + "assalamualaikum", + + "hello", + + "hi", + + "kya haal hai" + + ] + +} + + + +# ========================================================= + +# 4. ENTERPRISE NEURAL INFERENCE (CLOUD FIRST / DECOUPLED) + +# ========================================================= + +print("[INFERENCE] Initializing neural inference bridge...") + +from app.inference_client import ( + + get_embedding as async_get_embedding, + + get_rerank_scores as async_get_rerank_scores, + + INFERENCE_SERVICE_URL, + +) + + + +if INFERENCE_SERVICE_URL: + + print(f"[INFERENCE] Microservice mode engaged: Routing tensor jobs to {INFERENCE_SERVICE_URL}") + +else: + + print("[INFERENCE] Pure Cloud mode active: High-performance cloud neural APIs (Zero local RAM/CPU overhead)") + + + +# --------------------------------------------------------------------- + +# 🚀 MULTI-TIER USER SEARCH RAG RUNTIME CONFIGURATION + +# --------------------------------------------------------------------- + +from app.rag_config import ( + + resolve_user_tier, + + get_tier_rag_config, + + get_all_tier_configs, + + invalidate_tier_rag_cache, + + resolve_effective_limit, + + is_cross_encoder_allowed, + + parse_bool, + + DEFAULT_TIER_CONFIGS, + +) + +from app.rag.hybrid_biencoder import ( + + build_retrieval_queries, + + finalize_bi_encoder_candidates, + +) + + + +async def get_active_neural_config(tier: str = "free") -> dict: + + """Backward-compatible helper: returns active tier RAG configuration.""" + + return await get_tier_rag_config(tier) + + + +def invalidate_neural_config_cache(): + + """Invalidates the in-memory tier RAG cache so updates apply immediately.""" + + invalidate_tier_rag_cache() + + + +# --------------------------------------------------------------------- + +# 🚀 Quran Audio URL Generator (Dynamic Playlists) + +# --------------------------------------------------------------------- + +def get_quran_audio_urls(surah_no: int, ayah_numbers: List[int], language: str) -> List[str]: + + """Generates direct MP3 URLs for the frontend audio player based on user language.""" + + urls = [] + + # Map user language to available translated audio datasets + + audio_folders = { + + "English": "English/Sahih_Intnl_Ibrahim_Walk_192kbps", + + "Urdu": "translations/urdu_shamshad_ali_khan_46kbps", + + "Arabic": "Alafasy_128kbps" # Native Arabic recitation + + } + + # Fallback to Arabic if the language doesn't have a direct MP3 translation mapped yet + + folder = audio_folders.get(language, "Alafasy_128kbps") + + + + for ayah in ayah_numbers: + + surah_str = str(surah_no).zfill(3) + + ayah_str = str(ayah).zfill(3) + + urls.append(f"https://everyayah.com/data/{folder}/{surah_str}{ayah_str}.mp3") + + return urls + + + +# --------------------------------------------------------------------- + +# 🏷️ Grade normalizer (handles BOTH grade shapes) + +# --------------------------------------------------------------------- + +def _format_grade(grade) -> str: + + """Return a clean display string for a hadith grade. + + + + Bukhari/Muslim store `grade` as a plain STRING ("Sahih Authentic"). + + Tirmidhi (and the other Sunan) store a NESTED dict of every scholar's + + verdict: {"Al-Albani": "Sahih", "Zubair Ali Zai": "Daif"}. The response + + and memory paths join grades with " | ", and `" | ".join([...])` raises + + TypeError the moment a dict is in the list — which 500'd the /ask stream + + and surfaced as "Pipeline Error: Connection aborted" whenever a Tirmidhi + + doc was returned. Coercing every shape to a string here prevents that. + + """ + + if grade is None: + + return "Unspecified" + + if isinstance(grade, str): + + return grade.strip() or "Unspecified" + + if isinstance(grade, dict): + + parts = [f"{k}: {v}" for k, v in grade.items() + + if k and v and str(k).lower() != "xyz" + + and "not available" not in str(v).lower()] + + return "; ".join(parts) if parts else "Unspecified" + + if isinstance(grade, (list, tuple)): + + return "; ".join(str(x) for x in grade if x) or "Unspecified" + + return str(grade) + + + + + +# Legacy intent_router.pkl (which contained follow_up/conversation classes) has been removed; +# greetings and exact citations are routed deterministically without embedding calls. + + + +# ========================================================= + +# 5. DATA SCHEMAS (Tightened with Bounds & Non-Mutable Defaults - Weakness #6 Fix) + +# ========================================================= + +_PROMPT_INJECTION_PATTERNS = [ + + re.compile(r"(?i)\b(ignore|disregard|forget|override)\s+(all\s+)?(previous|prior|above|system)\s+(instructions|directives|rules|prompts|commands)"), + + re.compile(r"(?i)\b(you are now|pretend to be|act as|switch to)\s+(dan|jailbreak|unrestricted|evil|anarchist|godmode|developer mode)"), + + re.compile(r"(?i)\[system\s*(command|override|prompt|directive)\]"), + + re.compile(r"(?i)\b(system\s*prompt|system\s*override|system\s*instruction)\b"), + + re.compile(r"(?i)\b(developer mode enabled|jailbreak active)\b"), + +] + +_BOUNDARY_TAG_RE = re.compile( + r"(?i)<\s*/?\s*(retrieved_context|user_query|system|instructions?|assistant|developer)\s*>" +) + + +def sanitize_rag_untrusted_text(value: Any) -> str: + """Neutralizes prompt-injection directives and boundary-escape tags in untrusted DB or user text.""" + text = str(value or "") + text = _BOUNDARY_TAG_RE.sub("[BOUNDARY_TAG_REMOVED]", text) + for pattern in _PROMPT_INJECTION_PATTERNS: + text = pattern.sub("[DIRECTIVE_FILTERED]", text) + return text + + + +class AskRequest(BaseModel): + + query: str = Field(..., min_length=2, max_length=500) + + history: List[Dict[str, Any]] = Field(default_factory=list) + + user_id: Optional[str] = None + + session_id: Optional[str] = Field(default=None, max_length=128) + + language: str = Field(default="English", max_length=32) + + books: List[str] = Field(default_factory=list) + + top_k: int = Field(default=6, ge=1, le=15) + + strict_mode: bool = Field(default=False) + + include_sanad: bool = Field(default=False) + + pipeline: str = Field(default="rag_generation") + + + + @field_validator("history") + + @classmethod + + def validate_history_bounds(cls, v): + + if not v: + + return [] + + cleaned = [] + + total_chars = 0 + + # Restrict to last 20 messages and enforce character bounds to prevent prompt bloat + + for msg in v[-20:]: + + if not isinstance(msg, dict): + + continue + + role = str(msg.get("role", "")).strip().lower() + + content = str(msg.get("content", "")).strip() + + if role in ("user", "assistant") and content: + + # NEW-011: Strip prompt injection attempts in untrusted assistant turns + + if role == "assistant": + + if any(p.search(content) for p in _PROMPT_INJECTION_PATTERNS): + + logger.warning("[HADITH] Stripped prompt injection attempt from client-supplied assistant history.") + + continue + + trimmed = content[:1000] + + total_chars += len(trimmed) + + if total_chars > 8000: + + break + + cleaned.append({"role": role, "content": trimmed}) + + return cleaned + + + + @field_validator("books") + + @classmethod + + def validate_books_bounds(cls, v): + + if not v: + + return [] + + return [str(b).strip() for b in v[:30] if str(b).strip()] + + + + + +# ========================================================= + +# 6. 🚀 BOUNDED WORKER QUEUE FOR NON-ESSENTIAL MEMORY INDEXING + +# Prevents downstream overload & secondary request bursts (Weakness #3 Fix) + +# ========================================================= + +_memory_indexing_queue: asyncio.Queue = asyncio.Queue(maxsize=1000) + +_memory_worker_task: Optional[asyncio.Task] = None + + + +def _get_memory_queue() -> asyncio.Queue: + + global _memory_indexing_queue + + if _memory_indexing_queue is None: + + _memory_indexing_queue = asyncio.Queue(maxsize=1000) + + return _memory_indexing_queue + + + +def enqueue_memory_indexing(item: dict): + + """Enqueues an item for nonessential vector memory indexing with graceful queue drop on saturation.""" + + global _memory_indexing_queue + + try: + + q = _get_memory_queue() + + q.put_nowait(item) + + except asyncio.QueueFull: + + logger.warning("[MEMORY WORKER] Bounded queue full (1000 tasks). Dropping non-essential background indexing to preserve system health.") + + except Exception as e: + + logger.warning(f"[MEMORY WORKER] Failed to enqueue memory indexing: {e}") + + + +async def _process_single_memory_item(item: dict): + + user_id = item["user_id"] + + session_id = item["session_id"] + + query = item["query"] + + response = item["response"] + + source = item["source"] + + grade = item["grade"] + + narrator = item["narrator"] + + is_strict = item["is_strict"] + + intent = item["intent"] + + language = item["language"] + + top_k = item["top_k"] + + precomputed_vec = item.get("query_vector") + + books = item.get("books", []) + + collection_scope = sorted([b.lower() for b in books]) if books else [] + + stream_status = item.get("stream_status", "COMPLETED") + + is_interrupted = item.get("is_interrupted", False) or (stream_status != "COMPLETED") + + + + # 1. Private Interaction Memory: DECOMMISSIONED + + # (Previously used exclusively for the decommissioned chat follow-up explanation feature) + + + + # 2. Global Semantic Cache Indexing (Guarded against scope pollution, interruption, and errors) + + has_history = item.get("has_history", False) or bool(item.get("history")) + is_personalized = item.get("is_personalized", False) + if ( + + not is_interrupted + and not has_history + and not is_personalized + + and "⚠️" not in response + + and not is_strict + + and len(response) > 50 + + and intent in ["hadith_search", "quran_search", "SEARCH_DB"] + + ): + + try: + + if precomputed_vec is not None: + + cache_vec = precomputed_vec + + else: + + async with bounded_stage("embedding", timeout=6.0): + + cache_vec = (await async_get_embedding(query)).tolist() + + + + await vector_memory_collection.insert_one({ + + "memory_type": "GLOBAL", + + "user_id": "SYSTEM", + + "session_id": "GLOBAL_CACHE", + + "query": query, + + "response": response, + + "source": source, + + "grade": grade, + + "narrator": narrator, + + "collection_scope": collection_scope, + + "strict_mode": False, + + "intent": intent, + + "language": language, + + "top_k": top_k, + + "embedding_1024": cache_vec, + "context_class": "public_canonical", + "corpus_version": "v3", + "provenance": {"has_history": False, "is_personalized": False, "classification": "context_free_public"}, + + "timestamp": datetime.datetime.utcnow() + + }) + + except Exception as ce: + + logger.warning(f"[MEMORY WORKER] Failed to index global semantic cache: {ce}") + + + +async def _memory_worker_loop(): + + logger.info("[MEMORY WORKER] Background memory indexing worker started.") + + while True: + + try: + + q = _get_memory_queue() + + item = await q.get() + + try: + + # Retry with backoff for transient DB/network issues + + for attempt in range(2): + + try: + + await _process_single_memory_item(item) + + break + + except Exception as err: + + if attempt == 0: + + await asyncio.sleep(0.5) + + else: + + logger.error(f"[MEMORY WORKER] Final attempt failed for query: {err}") + + finally: + + q.task_done() + + except asyncio.CancelledError: + + break + + except Exception as e: + + logger.error(f"[MEMORY WORKER] Unexpected worker error: {e}") + + await asyncio.sleep(1.0) + + + +async def start_memory_indexing_worker(): + + """Initializes queue and starts background memory worker on the active application event loop.""" + + global _memory_indexing_queue, _memory_worker_task + + try: + + loop = asyncio.get_running_loop() + + except RuntimeError: + + logger.warning("[MEMORY WORKER] Cannot start worker: no running event loop.") + + return + + if _memory_indexing_queue is None or getattr(_memory_indexing_queue, "_loop", None) is not loop: + + _memory_indexing_queue = asyncio.Queue(maxsize=1000) + + if _memory_worker_task is None or _memory_worker_task.done(): + + _memory_worker_task = loop.create_task(_memory_worker_loop()) + + logger.info("[MEMORY WORKER] Background memory indexing worker started on active event loop.") + + + +async def stop_memory_indexing_worker(): + + """Cleanly cancels and awaits background memory worker on application shutdown.""" + + global _memory_worker_task + + if _memory_worker_task and not _memory_worker_task.done(): + + logger.info("[MEMORY WORKER] Cancelling background memory worker task...") + + _memory_worker_task.cancel() + + try: + + await _memory_worker_task + + except asyncio.CancelledError: + + pass + + except Exception as e: + + logger.warning(f"[MEMORY WORKER] Error stopping worker: {e}") + + _memory_worker_task = None + + logger.info("[MEMORY WORKER] Background memory worker cleanly stopped.") + + + +def ensure_memory_worker(): + + global _memory_worker_task, _memory_indexing_queue + + if _memory_worker_task is None or _memory_worker_task.done(): + + try: + + loop = asyncio.get_running_loop() + + if _memory_indexing_queue is None or getattr(_memory_indexing_queue, "_loop", None) is not loop: + + _memory_indexing_queue = asyncio.Queue(maxsize=1000) + + _memory_worker_task = loop.create_task(_memory_worker_loop()) + + except RuntimeError: + + pass + + + +async def handle_post_response_persistence( + + user_id: str, + + session_id: str, + + query: str, + + response: str, + + source: str, + + grade: str, + + narrator: str, + + is_strict: bool, + + intent: str, + + language: str, + + top_k: int, + + query_vector: Optional[list] = None, + + books: Optional[List[str]] = None, + + stream_status: str = "COMPLETED", + + is_interrupted: bool = False + +): + + """ + + Chat history writes (chats_collection) and vector-memory indexing are permanently + + disabled for the pure DB-search utility; searches never persist chat turns or + + trigger background embeddings. + + """ + + return None + + + +# Maintain backward compatibility + +vectorize_and_save_memory = handle_post_response_persistence + + + + + +# ========================================================= + +# 7. ASYNC STREAMERS & CIRCUIT BREAKERS + +# ========================================================= + +async def stream_direct_message( + + message_text: str, user_id: str, session_id: str, query: str, + + bg_tasks: BackgroundTasks, intent: str, language: str, top_k: int, + + source: str = "N/A", grade: str = "N/A", narrator: str = "N/A", + + should_cache: bool = True, audio_urls: list = [], precomputed_query_vec: Optional[list] = None, + + books: Optional[List[str]] = None, req_id: Optional[str] = None, t_start: Optional[float] = None, + + include_sanad: bool = False, doc_count: Optional[int] = None, + + tier_cfg: Optional[Dict[str, Any]] = None, strict_mode: bool = False, + +): + + async def generator(): + + words = message_text.split(" ") + + chunk_size = 8 + + for i in range(0, len(words), chunk_size): + + chunk = " ".join(words[i:i + chunk_size]) + " " + + yield json.dumps({ + + "chunk": chunk, + + "source": source, + + "grade": grade, + + "narrator": narrator, + + "original_text": "N/A", + + "audio_urls": audio_urls + + }) + "\n" + + await asyncio.sleep(0) + + if t_start is not None: + + t_tot = (time.perf_counter() - t_start) * 1000.0 + + logger.info(f"[{req_id or 'DIRECT'}] ⏱️ [TIMING][DIRECT_STREAM_DONE] total={t_tot:.1f}ms words={len(words)}") + + if should_cache: + + if message_text and len(message_text) > 20: + + try: + + await set_cached_llm_answer( + + query, + + language, + + top_k, + + { + + "response": message_text, + + "source": source, + + "grade": grade, + + "narrator": narrator, + + "audio_urls": audio_urls, + + "doc_count": doc_count if doc_count is not None else top_k, + + }, + + books, + + strict_mode, + + include_sanad=include_sanad, + + tier_cfg=tier_cfg, + + ) + + except Exception as ce: + + logger.warning(f"[{req_id or 'DIRECT'}] Failed to cache direct answer: {ce}") + + return StreamingResponse(generator(), media_type="application/x-ndjson") + + + +# LLM chatbot synthesis (stream_ai_output) removed: search returns direct database records only. + + + +async def _agent_llm_call(sys_prompt: str, user_prompt: str, max_tokens: int) -> str: + + primary_provider = "xai" if FORCE_XAI == 1 else "deepseek" + + fallback_provider = None if (FORCE_XAI == 1 or FORCE_DEEPSEEK == 1) else "xai" + + + + configs = { + + "deepseek": ("https://api.deepseek.com/chat/completions", {"Authorization": f"Bearer {DEEPSEEK_API_KEY}"}, {"model": "deepseek-chat", "messages": [{"role": "system", "content": sys_prompt}, {"role": "user", "content": user_prompt}], "temperature": 0.0, "max_tokens": max_tokens}), + + "xai": ("https://api.x.ai/v1/chat/completions", {"Authorization": f"Bearer {XAI_API_KEY}"}, {"model": "grok-2-latest", "messages": [{"role": "system", "content": sys_prompt}, {"role": "user", "content": user_prompt}], "temperature": 0.0, "max_tokens": max_tokens}) + + } + + + + async def _make_call(provider): + + url, headers, payload = configs[provider] + + async with bounded_stage("query_rewrite"): + + res = await http_client.post(url, headers=headers, json=payload, timeout=TIMEOUT_LLM_FAST) + + res.raise_for_status() + + return res.json()['choices'][0]['message']['content'].strip() + + + + try: + + return await _make_call(primary_provider) + + except Exception as e: + + if fallback_provider: + + try: + + return await _make_call(fallback_provider) + + except Exception: pass + + raise e + + +def _parse_llm_translation_payload(raw_out: str) -> Dict[str, str]: + """Parses JSON `{"text": ..., "sanad": ...}` output from LLM translation calls cleanly.""" + cleaned = (raw_out or "").strip() + if not cleaned: + return {} + if cleaned.startswith("```"): + cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.IGNORECASE | re.DOTALL).strip() + try: + parsed = json.loads(cleaned) + if isinstance(parsed, dict): + return { + "text": str(parsed.get("text") or parsed.get("translated_text") or "").strip(), + "sanad": str(parsed.get("sanad") or parsed.get("translated_sanad") or "").strip(), + } + except Exception: + pass + # Fallback: plain-text response when model omitted JSON braces + if not cleaned.startswith("{"): + return {"text": cleaned} + return {} + + +async def _translate_single_doc_with_llm( + doc: Dict[str, Any], + code: str, + display_lang: str, + include_sanad: bool, + need_text: bool, + need_sanad: bool, + fallback_sanad: str, +) -> Dict[str, str]: + """ + Uses `_agent_llm_call` (called ONLY when strict_mode=False) to generate a faithful + translation/transliteration into `display_lang` without any 'unavailable' notice. + """ + is_q = is_quran_record(doc) + raw_ur = _clean_non_empty(doc.get("text_urdu") or doc.get("text_ur")) + raw_en = _clean_non_empty(doc.get("text_english") or doc.get("text_en")) + raw_ar = _clean_non_empty(doc.get("text_arabic") or doc.get("text_ar")) + sanad_en_hint, _ = extract_doc_sanad(doc, "English") if not is_q else ("", False) + + if not is_q: + if raw_ur: + _, raw_ur = extract_sanad_and_matn_from_text(raw_ur, lang_code="ur") + if raw_ar: + _, raw_ar = extract_sanad_and_matn_from_text(raw_ar, lang_code="ar") + if raw_en: + _, raw_en = extract_sanad_and_matn_from_text(raw_en, lang_code="en", sanad_hint=sanad_en_hint) + + sanad_src = fallback_sanad if (include_sanad and not is_q and need_sanad) else "" + if include_sanad and not is_q and need_sanad and code == "hinglish": + # Prefer Urdu sanad when generating Roman Urdu transliteration + ur_sanad, _ = extract_doc_sanad(doc, "Urdu") + if ur_sanad: + sanad_src = ur_sanad + + if need_text: + if code == "hinglish" and raw_ur: + src_kind = "Urdu" + text_src = raw_ur + elif raw_ar and code != "hinglish": + src_kind = "Arabic" + text_src = raw_ar + elif raw_en: + src_kind = "English" + text_src = raw_en + elif raw_ur: + src_kind = "Urdu" + text_src = raw_ur + else: + src_kind = "Arabic" + text_src = raw_ar + else: + src_kind = "Source" + text_src = "" + + if need_text and not text_src and not sanad_src: + return {} + if not need_text and not sanad_src: + return {} + + sanad_rule = ( + "Omit all chains of narrators (Sanad) and keep ONLY the Matn." + if (not is_q and not include_sanad) + else "Preserve exact meanings faithfully." + ) + if code == "hinglish": + sys_prompt = ( + "You are an expert Islamic scholar and Urdu-to-Roman-Urdu (Hinglish) transliterator.\n" + "Rules:\n" + "1. If Urdu source text is given, transliterate it word-for-word into clean Roman Urdu using the Latin script.\n" + "2. If only Arabic/English source text is given, translate and write it faithfully in natural Roman Urdu (Hinglish) using Latin script.\n" + f"3. {sanad_rule}\n" + "4. NEVER include disclaimers, commentary, or 'translation not available' notes.\n" + "5. Output ONLY valid JSON with requested keys." + ) + else: + sys_prompt = ( + f"You are an expert Islamic scripture translator translating accurately into {display_lang}.\n" + "Rules:\n" + f"1. Translate directly and faithfully into {display_lang}.\n" + f"2. {sanad_rule}\n" + "3. NEVER add commentary, footnotes, or 'translation not available' disclaimers.\n" + "4. Output ONLY valid JSON with requested keys." + ) + + parts = [f"Target Language: {display_lang}"] + if need_text and text_src: + parts.append(f"{src_kind} Hadith Text:\n{text_src}") + if sanad_src: + parts.append(f"Chain of Narrators (Sanad):\n{sanad_src}") + + if need_text and sanad_src: + parts.append('Return ONLY valid JSON: {"sanad": "", "text": ""}') + elif need_text: + parts.append('Return ONLY valid JSON: {"text": ""}') + else: + parts.append('Return ONLY valid JSON: {"sanad": ""}') + + src_len = len(text_src) + len(sanad_src) + max_tokens = max(500, min(4096, src_len + 256)) + raw_out = await _agent_llm_call(sys_prompt, "\n\n".join(parts), max_tokens=max_tokens) + return _parse_llm_translation_payload(raw_out) + + +async def _format_hadith_search_response_for_mode( + docs: List[Dict[str, Any]], + language: Optional[str] = "English", + include_sanad: bool = False, + strict_mode: bool = False, +) -> Tuple[str, str, str, str, List[str], bool]: + """ + Formats search results respecting strict_mode and include_sanad: + - strict_mode=True: 100% deterministic DB text only (zero LLM calls); prints unavailable notice + English fallback when missing. + - strict_mode=False: Generates missing translations/transliterations via LLM cleanly without 'translation not available' notices. + Returns `(response_text, combined_refs, combined_grades, combined_narrators, combined_audio_urls, had_llm_failure)`. + """ + if strict_mode or not docs: + res = format_hadith_search_response(docs, language=language, include_sanad=include_sanad) + return (*res, False) + + code = normalize_language_code(language) + display_lang = get_language_display_name(language) + + raw_refs: List[str] = [] + raw_grades: List[str] = [] + raw_narrators: List[str] = [] + combined_audio_urls: List[str] = [] + prepared: List[Dict[str, Any]] = [] + llm_jobs: List[Tuple[int, Any]] = [] + + for i, doc in enumerate(docs): + ref = str(doc.get("reference") or f"Hadith #{doc.get('hadith_id', i+1)}") + grade = format_grade_string(doc.get("grade")) + narrator = extract_doc_narrator(doc, language) + is_q = is_quran_record(doc) + sanad, sanad_needs_loc = ("", False) if (not include_sanad or is_q) else extract_doc_sanad(doc, language) + + raw_refs.append(ref) + raw_grades.append(grade) + raw_narrators.append(narrator) + if doc.get("audio_urls"): + combined_audio_urls.extend(doc["audio_urls"]) + + text, is_fallback, _ = select_hadith_translation(doc, language, include_sanad=include_sanad) + if include_sanad and not is_q and not is_fallback: + extracted_inline, clean_matn = extract_sanad_and_matn_from_text( + text, lang_code=code, sanad_hint=sanad + ) + if extracted_inline and clean_matn: + text = clean_matn + if not sanad: + sanad = extracted_inline + + need_text = bool(is_fallback) + need_sanad = bool(include_sanad and not is_q and sanad_needs_loc and sanad) + prepared.append({ + "doc": doc, + "text": text, + "sanad": sanad, + "need_text": need_text, + "need_sanad": need_sanad, + }) + if need_text or need_sanad: + llm_jobs.append(( + i, + _translate_single_doc_with_llm( + doc=doc, + code=code, + display_lang=display_lang, + include_sanad=include_sanad, + need_text=need_text, + need_sanad=need_sanad, + fallback_sanad=sanad, + ), + )) + + had_llm_failure = False + if llm_jobs: + results = await asyncio.gather(*(coro for _, coro in llm_jobs), return_exceptions=True) + for (idx, _), res in zip(llm_jobs, results): + item = prepared[idx] + if isinstance(res, Exception) or not isinstance(res, dict): + logger.warning(f"[NON_STRICT_TRANSLATE] Failed doc translation/transliteration: {res}") + had_llm_failure = True + continue + gen_text = (res.get("text") or "").strip() + gen_sanad = (res.get("sanad") or "").strip() + if item["need_text"]: + if gen_text: + item["text"] = gen_text + else: + had_llm_failure = True + if item["need_sanad"] and gen_sanad: + item["sanad"] = gen_sanad + + blocks = [ + render_hadith_doc_block( + i, + item["doc"], + item["text"], + sanad=item["sanad"], + include_sanad=include_sanad, + ) + for i, item in enumerate(prepared) + ] + + response_text = "\n\n".join(blocks) + combined_refs = " | ".join(raw_refs) if raw_refs else "N/A" + combined_grades = " | ".join(raw_grades) if raw_grades else "N/A" + combined_narrators = " | ".join(raw_narrators) if raw_narrators else "N/A" + return response_text, combined_refs, combined_grades, combined_narrators, combined_audio_urls, had_llm_failure + + + +_EXACT_GREETING_PHRASES = { + + "hi", "hii", "hiii", "hello", "hey", "heyy", "hola", + + "salam", "salaam", "assalam", "assalamualaikum", "assalamu alaikum", + + "as salamu alaykum", "as-salamu alaykum", "assalamu alaykum", "salam alaikum", + + "wa alaikum assalam", "kya haal hai", "kya hal hai", "kaise ho", + + "how are you", "good morning", "good afternoon", "good evening", "peace be upon you", + +} + +_GREETING_STEMS = {"hi", "hii", "hiii", "hello", "hey", "heyy", "hola", "salam", "salaam", "assalam", "assalamualaikum"} + +_GREETING_FILLER_TOKENS = {"there", "bot", "ai", "sahih", "sahihislam", "friend", "brother", "sister", "everyone", "all", "sir", "madam", "ji"} + +_ROMAN_TRANSLIT_HINT_RE = re.compile( + + r"\b(" + + r"ki|ka|ke|ko|pe|mein|hain|hai|ho|toh|bhi|nahi|nahin|yeh|woh|jab|tab|agar|lekin|magar|" + + r"kyunki|isliye|kuch|koi|kaun|kaisa|kaisi|kaise|kahan|kab|kyun|kyon|kya|" + + r"baare|bare|batao|bataiye|bataye|batayein|dikhao|samjhao|" + + r"karo|karna|karni|karne|kare|karein|kiya|hota|hoti|hote|hua|hui|hue|raha|rahi|rahe|" + + r"chahiye|sakta|sakti|sakte|padhe|padhna|parhe|parhna|padho|parhne|rakhne|bachne|milne|milta|milti|" + + r"wala|wali|wale|unke|unki|unka|iske|iski|iska|apna|apni|apne|mera|meri|mere|tera|teri|tere|" + + r"humara|hamara|humari|aapka|aapki|haal|hal|aur|maa|baap|behen|bhai|" + + r"rehmat|rahemat|fazilat|fazeelat|fazail|hukm|masla|masail|masnoon|qunoot|gunah|gunaah|sawab|sawaab|barkat|" + + r"maghfirat|hidayat|ibadat|namaz|nimaz|namaaz|nimaaz|roza|rozah|roze|sehri|iftar|iftari|" + + r"wuzu|wazu|wudhu|gusl|ghusl|taharat|pakeezgi|paak|napak|shabe|farz|hadees|sharif|todne|toot|cheez|cheezein|" + + r"waqt|walidain|aulad|shohar|biwi|duniya|akhirat|aakhirat|qabar|qabr|qayamat|qiyamat|dajjal|barzakh|" + + r"jannat|jahannam|dozakh|tauba|tawba|astaghfar|istighfar|shafaat|shukar|rizq|niyat|huqooq|haqooq|huquq|" + + r"tarika|tareeqa|subah|shaam|raat|zyada|ghussa|nikah|nikaah|talaq|talaaq|iddat|zakaat|sadqa|sadqah|fitra|fitrah|" + + r"qurbani|janaza|janazah|mayyat|kafan|dafan|jumma|jummah|azaan|taraweeh|tahajjud|sunnat|haraam|halaal|" + + r"makrooh|bidat|biddat|bidah|duaa|darood|durood|tasbeeh|tilawat|parda|pardah|gheebat|geebat|takabbur|tawakkul|" + + r"imaan|bimaar|bimari|marz|ilaj|dawa|yateem|miskeen|faqeer|padosi|humsaya|rishtedar|zulm|insaf|insaaf|amanat|" + + r"khayanat|jhoot|jhooth|sach|mohabbat|nafrat|maut|zindagi|" + + r"kafir|kaafir|kufr|momin|mumin|munafiq|mushrik|jahil|zalim|taqdeer|azab|azaab|" + + r"bagaimana|tentang|hukum|puasa|sholat|shalat|quels|verset|priere|como|sobre|versiculo|nedir|hakkinda|oruc" + + r")\b", + + re.IGNORECASE, + +) + +_IZAFAT_TRANSLIT_RE = re.compile( + + r"\b(?:[a-z]{2,}-e-[a-z]{2,}|(?:shab|dua|fazail|ayat|masail|kitab|subah|namaz|roza|ramazan|eid|juma|ilm|zikr|rahmat|rehmat|barkat|zindagi|hukm|qiyam|tilawat|sunnat|farz|ghusl|noor|baab|bayan|tariqa|masla|ahkam|shaan|azmat|haqeeqat|ahl|ahle)\s+e\s+[a-z]{2,})\b", + + re.IGNORECASE, + +) + +_EXACT_QURAN_CITATION_RE = re.compile( + + r"(?:surah|quran|chapter|سورة)\s*(\d+)(?:\s*(?:ayat|ayah|verse|:|آية)\s*(\d+))?" + + r"|^(?:\s*)(\d{1,3})\s*:\s*(\d{1,3})(?:\s*)$" + + r"|(?:surah|quran|chapter|ayat|ayah|verse|سورة|آية).*\b(\d{1,3})\s*:\s*(\d{1,3})\b" + +) + +_EXACT_HADITH_CITATION_RE = re.compile( + + r"(?:hadith\s*(?:no\.?|number|#)?|(?:bukhari|muslim|tirmidhi|tirmizi|majah|dawud|dawood|nasai|ahmad|muwatta|darimi|daraqutni|حديث)(?:\s+hadith)?(?:\s*(?:no\.?|number|#))?|#)\s*[:\-]?\s*(\d+)" + +) + + +def is_greeting_query(query: str) -> bool: + + """Recognizes standalone greetings consistently without capturing search queries by prefix.""" + + raw = (query or "").strip().lower() + + if not raw or any(ch.isdigit() for ch in raw): + + return False + + clean = re.sub(r"[^\w\s]", "", raw) + + clean = re.sub(r"\s+", " ", clean).strip() + + if not clean: + + return False + + if clean in _EXACT_GREETING_PHRASES: + + return True + + tokens = clean.split() + + if len(tokens) <= 4 and tokens[0] in _GREETING_STEMS and all(t in _GREETING_FILLER_TOKENS for t in tokens[1:]): + + return True + + return False + + +_CHAIN_STUB_EN_RE = re.compile( + r"(?:this|a|another|the\s+same|similar)\s+hadith(?:\s+like\s+this|\s+of\s+the\s+same\s+meaning)?" + r"(?:\s+is|\s+has\s+been|\s+was)?\s*(?:narrated|reported|transmitted)\b" + r"|\b(?:this|a|another)\s+hadith\s+like\s+this\b" + r"|(?:reported|narrated|transmitted)\s+(?:a\s+hadith\s+)?(?:like|similar\s+to)\s+(?:this|it)" + r"|(?:with\s+this\s+chain|with\s+the\s+same\s+chain)(?:\s+of\s+narration)?\s+(?:like|similar\s+to|to\s+the\s+same\s+effect)" + r"|\b(?:by|through)\s+another\s+chain\s+of\s+(?:narrators|transmitters)\b" + r"|\bwith\s+(?:a\s+slight|some)\s+variation\s+of\s+words\b", + re.IGNORECASE, +) + +_CHAIN_STUB_TAIL_RE = re.compile( + r"(?:isi\s+sanad\s+ke\s+saath(?:\s+isi\s+ke\s+misl)?|isi\s+ke\s+misl(?:\s+riwayat\s+kiya|\s+khabar\s+di|\s+hadees\s+bayan\s+ki)?|" + r"اسی\s+سند\s+کے\s+ساتھ(?:\s+اسی\s+کے\s+مانند)?|اسی\s+کے\s+مانند|" + r"بِهَذَا\s+الإِسْنَادِ(?:\s+مِثْلَهُ|\s+نَحْوَهُ)?|نَحْوَهُ|مِثْلَهُ)\s*[.\u200f۔]?\s*$", + re.IGNORECASE, +) + +_SEARCH_BOILERPLATE_RE = re.compile( + r"^(?:please\s+|can\s+you\s+|could\s+you\s+)?(?:show|tell|give|find|search|fetch|bring|get)\s+(?:me\s+)?" + r"(?:some\s+|any\s+|authentic\s+|verified\s+|the\s+|a\s+|an\s+)?" + r"(?:hadiths?|hadees|ahadees|ahadith|verses?|ayahs?|ayat)\s+(?:about|on|regarding|for|of|related\s+to)\s+" + r"|^(?:hadiths?|hadees|ahadees|ahadith)\s+(?:about|on|regarding|for|related\s+to)\s+", + re.IGNORECASE, +) + + +def _strip_search_boilerplate(term: str) -> str: + """ + Removes conversational wrapper phrasing (e.g. 'Show me hadith about kafir' -> 'kafir') + before vector embedding so the word 'hadith' does not attract chain-pointer stubs. + """ + raw = re.sub(r"\s+", " ", (term or "").strip()) + if not raw: + return "" + stripped = _SEARCH_BOILERPLATE_RE.sub("", raw).strip(" :?.-") + return stripped if len(stripped) >= 3 else raw + + +def _is_chain_reference_stub(doc: Dict[str, Any]) -> bool: + """ + Identifies zero-content mutaba'at cross-reference stub Hadiths (e.g. + 'This hadith is narrated on the authority of Ayyub', 'isi sanad ke saath isi ke misl', + or partial chain-variation pointers like 'through another chain of transmitters but with...') + that lack a standalone prophetic teaching, so topic searches rank substantive narrations first. + """ + if is_quran_record(doc): + return False + en = str(doc.get("text_english") or "").strip() + if en and re.match( + r"^(?:this|a|another|the\s+same)\s+hadith\b.*?\b(?:through\s+another\s+chain|another\s+chain\s+of\s+(?:narrators|transmitters)|with\s+this\s+chain|with\s+(?:a\s+slight|some)\s+variation)\b", + en, + re.IGNORECASE, + ) and len(en) <= 260: + if not re.search(r'(?:the\s+(?:prophet|messenger\s+of\s+allah)\s*(?:\([^)]*\))?\s+said\s*[:,"])', en, re.IGNORECASE): + return True + if len(en) > 180 or '"' in en: + return False + if en and _CHAIN_STUB_EN_RE.search(en): + if not re.search(r'(?:said\s*:?\s*"|the prophet[^"]*said\s*["\':])', en, re.IGNORECASE): + return True + for field in ("text_hinglish", "text_urdu", "text_arabic"): + val = str(doc.get(field) or "").strip() + if val and len(val) <= 320 and '"' not in val and "«" not in val: + if _CHAIN_STUB_TAIL_RE.search(val): + return True + return False + + +def _needs_english_translation(query: str) -> bool: + + """Returns True when query contains non-ASCII script or Roman-Urdu/Hinglish/non-English terms needing translation.""" + + if not query: + + return False + + if any(ord(ch) > 127 for ch in query): + + return True + + if _ROMAN_TRANSLIT_HINT_RE.search(query): + + return True + + if _IZAFAT_TRANSLIT_RE.search(query): + + return True + + return False + + +def _canonical_record_identity(doc: Dict[str, Any]) -> tuple: + + """Builds a stable database record identity (collection + record ID) so distinct records with similar text are retained.""" + + surah_no = doc.get("surah_no") + + ayah_no = doc.get("ayah_no") + + is_quran_doc = ( + + bool(doc.get("is_quran")) + + or "quran" in str(doc.get("collection", "")).lower() + + or (surah_no is not None and ayah_no is not None) + + ) + + if is_quran_doc and surah_no is not None and ayah_no is not None: + + return ("quran", f"{int(surah_no)}:{int(ayah_no)}") + + col = str(doc.get("collection") or "").strip().lower() + + rec_id = doc.get("hadith_id") + + if rec_id is None or str(rec_id).strip() == "": + + rec_id = doc.get("_id") + + if rec_id is None or str(rec_id).strip() == "": + + rec_id = doc.get("reference") or "" + + return ("hadith", col, str(rec_id).strip().lower()) + + +async def classify_query_intent(query: str, history: Optional[List[Dict[str, str]]] = None) -> str: + + """Deterministic zero-embedding router: greetings, exact citations, or general DB semantic search.""" + + if is_greeting_query(query): + + return "greeting" + + q_low = (query or "").lower() + + if _EXACT_HADITH_CITATION_RE.search(q_low): + + return "hadith_by_number" + + if _EXACT_QURAN_CITATION_RE.search(q_low): + + return "quran_search" + + return "SEARCH_DB" + + + +async def rewrite_query_for_search( + query: str, + history: Optional[List[Dict[str, str]]] = None, + strict_mode: bool = False, +) -> str: + + """ + + Translation-only normalization step: converts non-English queries into literal English for + + bi-encoder search while preserving all constraints (identifiers, collection names, negation, + + quoted phrases, and details). Never uses conversation history, summarizes, or expands terms. + + In strict_mode=True, skips LLM translation completely so zero LLM calls occur. + + """ + + normalized_input = re.sub(r"\s+", " ", (query or "").strip()) + + if not normalized_input: + + return "" + + if strict_mode: + + return normalized_input + + if not _needs_english_translation(normalized_input): + + return normalized_input + + sys_prompt = """You are a literal search-query translator for an Islamic Quran & Hadith database search engine. + +Translate the user's query into faithful, literal English for database search. + +STRICT RULES: + +1. TRANSLATE ONLY: Do NOT summarize, paraphrase, expand definitions, or add explanations. + +2. PRESERVE ALL CONSTRAINTS: Keep all numbers, Hadith/Surah/Ayah identifiers (e.g., 2:255, #1, hadith 45), collection names (Sahih Bukhari, Muslim, Abu Dawud, Tirmidhi, etc.), negations (not, never, without, forbidden, except), and quoted terms ("...") intact. + +3. NO CHAT HISTORY / NO PRONOUN RESOLUTION: Treat the query completely independently. + +4. Convert any Roman-Urdu / Hinglish / South-Asian Islamic transliterations inside the query into clean English database terms (e.g., nimaz/namaz -> prayer, roza -> fasting, wuzu -> ablution, gunah -> sin, nikah -> marriage, sabr -> patience). If already pure English with no non-English words, return unchanged. + +5. Output ONLY the translated English query text, nothing else.""" + + prompt = f"QUERY: {normalized_input}\n\nLITERAL ENGLISH QUERY:" + + try: + + result = await _agent_llm_call(sys_prompt, prompt, max_tokens=150) + + cleaned = re.sub(r"\s+", " ", (result or "").strip()) + + return cleaned if cleaned else normalized_input + + except Exception: + + return normalized_input + + + + + +_surah_memory_cache: Dict[int, dict] = {} +_surah_memory_cache_revision: Optional[str] = None +_MAX_SURAH_MEMORY_CACHE = 120 + + +def _clear_surah_memory_cache() -> None: + global _surah_memory_cache_revision + _surah_memory_cache.clear() + _surah_memory_cache_revision = get_corpus_revision() + + +register_cache_clear_hook(_clear_surah_memory_cache) + + +def _sync_surah_memory_cache_revision() -> None: + global _surah_memory_cache_revision + active_rev = get_corpus_revision() + if _surah_memory_cache_revision != active_rev: + _surah_memory_cache.clear() + _surah_memory_cache_revision = active_rev + + +def _cache_surah_doc(s_num: int, doc: dict) -> None: + _sync_surah_memory_cache_revision() + if len(_surah_memory_cache) >= _MAX_SURAH_MEMORY_CACHE and s_num not in _surah_memory_cache: + _surah_memory_cache.pop(next(iter(_surah_memory_cache)), None) + _surah_memory_cache[s_num] = doc + + + +class SurahLookupError(RuntimeError): + + """Raised when both primary (MongoDB) and fallback (R2) Quran data sources fail.""" + + +async def _get_surah_doc_from_r2(surah_no: int, raise_on_error: bool = False): + + """Retrieve complete Surah document. MongoDB first, with revision-aware in-memory caching and R2 fallback. + + Distinguishes data-source failures from a genuine nonexistent Surah when raise_on_error=True. + """ + + try: + + s_num = int(surah_no) + + except (ValueError, TypeError): + + return None + + + + await refresh_corpus_revision() + + _sync_surah_memory_cache_revision() + + if s_num in _surah_memory_cache: + + return _surah_memory_cache[s_num] + + + + mongo_failed = False + + r2_failed = False + + + + # 1. Primary: Direct high-speed MongoDB Atlas query (10x faster) + + try: + + doc = await quran_collection.find_one({"surah_no": s_num}, {"_id": 0}) + + if doc and doc.get("ayahs"): + + _cache_surah_doc(s_num, doc) + + return doc + + except Exception as e: + + mongo_failed = True + + logger.warning(f"[QURAN_CACHE] Mongo read failed for surah {s_num}: {e}") + + + + # 2. Resilient Fallback: Cloudflare R2 CDN + + try: + + from app.r2_config import fetch_translation_data + + call_kwargs: Dict[str, Any] = {} + + try: + + params = inspect.signature(fetch_translation_data).parameters + + if "raise_on_error" in params or any( + + p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values() + + ): + + call_kwargs["raise_on_error"] = raise_on_error + + except (TypeError, ValueError): + + pass + + data = await fetch_translation_data(s_num, **call_kwargs) + + if data: + + _cache_surah_doc(s_num, data) + + return data + + except Exception as e: + + r2_failed = True + + logger.warning(f"[QURAN_CACHE] R2 fallback failed for surah {s_num}: {e}") + + + + if raise_on_error and (mongo_failed or r2_failed): + + raise SurahLookupError( + + f"Failed to retrieve Surah {s_num} cleanly (mongo_failed={mongo_failed}, r2_failed={r2_failed})." + + ) + + + + return None + + + + + +async def _execute_cold_retrieval( + + query: str, + + books: Optional[List[str]] = None, + + history: Optional[List[Dict[str, str]]] = None, + + language: str = "english", + + top_k: int = 5, + + include_sanad: Optional[bool] = None, + + strict_mode: bool = False, + + user_tier: str = "free", + + tier_cfg: Optional[Dict[str, Any]] = None, + + req_id: str = "sf", + +) -> Dict[str, Any]: + + """ + + Sole leader execution for cold Hadith + Quran vector retrieval pipeline. + + Executes translation-only English normalization, exact normalized-English canonical + + cache check, BGE-M3 bi-encoder embedding, Atlas Vector Search, stable-ID dedup, + + and configurable similarity gating. Cross-encoder reranking remains disabled by default. + + Caches up to 6 full canonical records (with all stored translations) keyed by + + normalized English query, corpus scope, and version metadata. + + """ + + cfg = tier_cfg or {} + + effective_limit = resolve_effective_limit(top_k, cfg, hard_cap=MAX_CANONICAL_CACHE_DOCS) + + normalized_books = [b.lower() for b in books] if books else [] + + is_quran_only_mode = bool(normalized_books and len(normalized_books) == 1 and "quran" in normalized_books[0]) + + quran_selected = is_quran_only_mode or any("quran" in b for b in normalized_books) + + hadith_books_selected = [b for b in (books or []) if "quran" not in b.lower()] + + has_specific_hadith = bool(hadith_books_selected) + + + + search_quran = quran_selected + + search_hadith = has_specific_hadith or (not quran_selected) + + + + t_rew_0 = time.perf_counter() + + # Translation-only normalization (history is ignored; constraints preserved; skipped in strict_mode) + + search_term = await rewrite_query_for_search(query, None, strict_mode=strict_mode) + + search_term = (search_term or query or "")[:300].strip() + + t_rew_ms = (time.perf_counter() - t_rew_0) * 1000.0 + + + + # Ensure cache keys reflect current corpus revision across multi-worker instances + + await refresh_corpus_revision() + + # Exact normalized-English canonical cache check (isolated by tier retrieval policy; never truncates 6-record pool) + + canonical_pool = await get_cached_canonical_pool(query=search_term, books=books, tier_cfg=cfg) + + if canonical_pool: + + if search_term.strip().lower() != query.strip().lower(): + + await set_cached_canonical_documents(query, canonical_pool, books, tier_cfg=cfg) + + print(f"🎯 [{req_id}] [NORMALIZED-ENGLISH CANONICAL CACHE HIT] {len(canonical_pool)} canonical docs loaded for '{search_term}'") + + return { + + "candidates": canonical_pool, + + "query_vec": None, + + "search_term": search_term, + + "used_bi_encoder": False, + + "used_cross_encoder": False, + + "cache_hit": True, + + "cache_type": "CANONICAL_TRANSLATED", + + "search_status": "OK", + + "partial_failures": [], + + "timings": {"rew_ms": t_rew_ms, "embed_ms": 0.0, "atlas_ms": 0.0, "rerank_ms": 0.0}, + + } + + + + # Bi-encoder query enrichment & embedding (BGE-M3 1024-d normalized) + # Strips conversational boilerplate and adds deterministic DB English synonyms for Hinglish/Arabic terms + + t_emb_0 = time.perf_counter() + + retrieval_queries = build_retrieval_queries(search_term, boilerplate_stripper=_strip_search_boilerplate) + + embed_term = retrieval_queries["embed_query"] + + try: + + async with bounded_stage("embedding"): + + query_vec = (await async_get_embedding(embed_term)).tolist() + + except Exception as emb_err: + + t_embed_ms = (time.perf_counter() - t_emb_0) * 1000.0 + + logger.error(f"[{req_id}] Embedding failure for search_term='{search_term}': {emb_err}") + + return { + + "candidates": [], + + "query_vec": None, + + "search_term": search_term, + + "used_bi_encoder": False, + + "used_cross_encoder": False, + + "cache_hit": False, + + "cache_type": "FAILURE", + + "search_status": "FAILED", + + "partial_failures": ["embedding"], + + "error": str(emb_err), + + "timings": {"rew_ms": t_rew_ms, "embed_ms": t_embed_ms, "atlas_ms": 0.0, "rerank_ms": 0.0}, + + } + + t_embed_ms = (time.perf_counter() - t_emb_0) * 1000.0 + + + + # Atlas Vector Search & Tier Retrieval Provisioning: + # - free: Atlas 200 -> bi-encoder top 6 directly to user + # - tiers below pro (ad_free / plus): Atlas 300 -> bi-encoder top 40 -> amazon/rerank-v1 -> final 6 + # - pro / vip: Atlas 500 -> bi-encoder top 80 -> amazon/rerank-v1 -> final 6 + tier_low = str(user_tier or "free").strip().lower() + default_bi_k = 6 if tier_low == "free" else (40 if tier_low in ("ad_free", "plus") else 80) + try: + bi_encoder_limit = max(effective_limit, min(200, int(cfg.get("bi_encoder_top_k", default_bi_k)))) + except (TypeError, ValueError): + bi_encoder_limit = max(effective_limit, default_bi_k) + + cross_enabled = bool(cfg.get("cross_encoder_enabled", False)) and is_cross_encoder_allowed() + + configured_scope = int(cfg.get("num_candidates", SEARCH_CONFIG["vector_search_scope"])) + + scope = max(30, min(configured_scope, 10000)) + + limit_docs = min(scope, max(90, bi_encoder_limit * 2)) + + + + search_tasks = [] + + active_collections = [] + + if search_hadith: + + hadith_stage = { + + "$vectorSearch": { + + "index": "vector_index", + + "path": "embedding_1024", + + "queryVector": query_vec, + + "numCandidates": scope, + + "limit": limit_docs, + + } + + } + + if has_specific_hadith: + + hadith_stage["$vectorSearch"]["filter"] = {"collection": {"$in": hadith_books_selected}} + + + + search_tasks.append( + + hadith_collection.aggregate([ + + hadith_stage, + + {"$addFields": {"_vscore": {"$meta": "vectorSearchScore"}}}, + + {"$project": {"embedding_1024": 0, "embedding": 0}}, + + ]).to_list(length=limit_docs) + + ) + + active_collections.append("hadith") + + else: + + search_tasks.append(asyncio.sleep(0, result=[])) + + + + if search_quran: + + quran_stage = { + + "$vectorSearch": { + + "index": "quran1024_index", + + "path": "embedding_1024", + + "queryVector": query_vec, + + "numCandidates": scope, + + "limit": limit_docs, + + } + + } + + search_tasks.append( + + quran_collection.database["quran_verses"].aggregate([ + + quran_stage, + + {"$addFields": {"_vscore": {"$meta": "vectorSearchScore"}}}, + + ]).to_list(length=limit_docs) + + ) + + active_collections.append("quran") + + else: + + search_tasks.append(asyncio.sleep(0, result=[])) + + # Parallel non-fatal MongoDB $text BM25 lexical search for hybrid bi-encoder fusion (task index 2) + lex_query_str = retrieval_queries.get("lex_query", "") + async def _fetch_lexical_hadiths() -> List[Dict[str, Any]]: + if not search_hadith or not lex_query_str or not hasattr(hadith_collection, "find"): + return [] + try: + lex_filter: Dict[str, Any] = {"$text": {"$search": lex_query_str}} + if has_specific_hadith: + lex_filter["collection"] = {"$in": hadith_books_selected} + cur = hadith_collection.find(lex_filter, {"embedding": 0, "_tscore": {"$meta": "textScore"}}) + if hasattr(cur, "sort"): + cur = cur.sort([("score", {"$meta": "textScore"})]) + if hasattr(cur, "limit"): + cur = cur.limit(35) + rows = await cur.to_list(length=35) + if isinstance(rows, list) and all(isinstance(r, dict) for r in rows): + for r in rows: + if "_tscore" not in r and "score" in r: + try: + r["_tscore"] = float(r.get("score") or 0.0) + except (TypeError, ValueError): + r["_tscore"] = 0.0 + return rows + except Exception as lex_err: + logger.debug(f"[{req_id}] Non-fatal lexical $text search skipped: {lex_err}") + return [] + + search_tasks.append(_fetch_lexical_hadiths()) + + + + t_atlas_0 = time.perf_counter() + + raw_hadiths = [] + + raw_quran = [] + + raw_lexical_hadiths: List[Dict[str, Any]] = [] + + partial_failures = [] + + try: + + async with bounded_stage("atlas_vector"): + + results = await asyncio.gather(*search_tasks, return_exceptions=True) + + if search_hadith: + + if isinstance(results[0], Exception): + + logger.error(f"[{req_id}] Hadith vector search error: {results[0]}") + + partial_failures.append("hadith") + + elif isinstance(results[0], list): + + raw_hadiths = results[0] + + if search_quran: + + if isinstance(results[1], Exception): + + logger.error(f"[{req_id}] Quran vector search error: {results[1]}") + + partial_failures.append("quran") + + elif isinstance(results[1], list): + + raw_quran = results[1] + + if len(results) > 2 and isinstance(results[2], list): + + raw_lexical_hadiths = results[2] + + except Exception as e: + + logger.error(f"[{req_id}] Atlas vector stage error: {e}") + + partial_failures = list(active_collections) or ["atlas_vector"] + + t_atlas_ms = (time.perf_counter() - t_atlas_0) * 1000.0 + + + + if active_collections and len(partial_failures) >= len(active_collections): + + return { + + "candidates": [], + + "query_vec": query_vec, + + "search_term": search_term, + + "used_bi_encoder": True, + + "used_cross_encoder": False, + + "cache_hit": False, + + "cache_type": "FAILURE", + + "search_status": "FAILED", + + "partial_failures": partial_failures, + + "error": f"All active collection searches failed: {', '.join(partial_failures)}", + + "timings": { + + "rew_ms": t_rew_ms, + + "embed_ms": t_embed_ms, + + "atlas_ms": t_atlas_ms, + + "rerank_ms": 0.0, + + }, + + } + + + + cached_candidates = [] + + bi_encoder_final_docs: List[Dict[str, Any]] = [] + + bi_encoder_metrics: Dict[str, Any] = {} + + used_cross_encoder = False + + t_rerank_ms = 0.0 + + min_sim = float(cfg.get("minimum_vector_similarity", SEARCH_CONFIG["minimum_vector_similarity"])) + + min_rerank = float(cfg.get("minimum_rerank_logit", SEARCH_CONFIG["minimum_rerank_logit"])) + + MAX_CACHE_DEPTH = MAX_CANONICAL_CACHE_DOCS + + + + if raw_quran or raw_hadiths or raw_lexical_hadiths: + + # ========================================================= + # STEP 4A: BI-ENCODER-FIRST FINAL OUTPUT STAGE + # Hybrid dense BGE-M3 + $text BM25 RRF + IDF concept coverage + noise gating + # Final output is computed here cleanly BEFORE any optional cross-encoder step. + # ========================================================= + def _is_quran_candidate(d: Dict[str, Any]) -> bool: + ref_id = d.get("reference", "N/A") + return ( + bool(d.get("is_quran")) + or "Quran" in str(ref_id) + or "quran" in str(d.get("collection", "")).lower() + or d.get("surah_no") is not None + ) + + bi_res = finalize_bi_encoder_candidates( + vector_hadiths=raw_hadiths, + vector_quran=raw_quran, + lexical_hadiths=raw_lexical_hadiths, + query_vec=query_vec, + retrieval_queries=retrieval_queries, + min_sim=min_sim, + max_results=bi_encoder_limit, + identity_fn=_canonical_record_identity, + is_stub_fn=_is_chain_reference_stub, + is_quran_fn=_is_quran_candidate, + prune_cliff=not cross_enabled, + ) + bi_encoder_final_docs = bi_res["candidates"] + bi_encoder_metrics = bi_res["metrics"] + print( + f"[{req_id}] ⚡ [STEP 4A: BI-ENCODER FINAL OUTPUT] Tier={user_tier.upper()}, scope={scope}, limit_docs={limit_docs}, " + f"min_sim={min_sim}, bi_cap={bi_encoder_limit}, pool={bi_encoder_metrics.get('pool_size', 0)}, " + f"final={len(bi_encoder_final_docs)}, stubs_skipped={bi_encoder_metrics.get('stubs_skipped', 0)}, " + f"noise_rejected={bi_encoder_metrics.get('noise_rejected', 0)}, dups_collapsed={bi_encoder_metrics.get('dups_collapsed', 0)}" + ) + + # ========================================================= + # STEP 4B: TIERED CROSS-ENCODER REFINEMENT (e.g., amazon/rerank-v1 on 40 / 80 bi-encoder finalists -> top 6) + # ========================================================= + active_provider = str(cfg.get("reranker_provider", "openrouter")).strip().lower() + + active_model = str(cfg.get("reranker_model", "amazon/rerank-v1")).strip() + + ordered_qualifying = list(bi_encoder_final_docs) + + if cross_enabled and bi_encoder_final_docs: + + print(f"[{req_id}] 📊 [STEP 4B: CROSS-ENCODER REFINEMENT ({len(bi_encoder_final_docs)} bi-encoder finalists -> top {MAX_CACHE_DEPTH}) Tier={user_tier.upper()}, Provider={active_provider}, Model={active_model}]") + + t_rerank_0 = time.perf_counter() + + try: + + pairs = [ + [search_term, f"{d.get('reference', '')}: {d.get('text_english', '')}"[:2000]] + for d in bi_encoder_final_docs + ] + + async with bounded_stage("reranking"): + + scores = await async_get_rerank_scores(pairs, provider=active_provider, model=active_model) + + ranked_indices = np.argsort(scores)[::-1] + top_logit = float(scores[ranked_indices[0]]) if len(ranked_indices) > 0 else -9.0 + # If cloud reranker (e.g. amazon/rerank-v1) scores valid bi-encoder survivors below + # min_rerank on short/transliterated texts, never drop all bi-encoder survivors to []; + # enforce min_rerank when top_logit >= min_rerank, else prune only steep (>5.0 logit) dropoffs. + effective_gate = min_rerank if top_logit >= min_rerank else (top_logit - 5.0) + + refined_docs = [] + + for idx in ranked_indices: + + sc = float(scores[idx]) + if sc < effective_gate: + + break + + reranked_doc = dict(bi_encoder_final_docs[idx]) + reranked_doc["rerank_score"] = round(sc, 4) + refined_docs.append(reranked_doc) + + if len(refined_docs) >= MAX_CACHE_DEPTH: + + break + + ordered_qualifying = refined_docs + + used_cross_encoder = True + + t_rerank_ms = (time.perf_counter() - t_rerank_0) * 1000.0 + + except Exception as err: + + logger.warning(f"[{req_id}] Cross-encoder fallback engaged; keeping bi-encoder final output ({err})") + + ordered_qualifying = list(bi_encoder_final_docs) + + for doc in ordered_qualifying: + + if len(cached_candidates) >= MAX_CACHE_DEPTH: + + break + + ref_id = doc.get('reference', 'N/A') + + is_quran_doc = _is_quran_candidate(doc) + + + + if is_quran_doc: + + doc['is_quran'] = True + + doc['grade'] = "Divine Revelation" + + surah_no = doc.get('surah_no') + + ayah_no = doc.get('ayah_no') + + if surah_no and ayah_no: + + target_ref = str(doc.get('reference') or f"Surah {surah_no}:{ayah_no}") + + if target_ref == "N/A" or not target_ref.strip(): + + target_ref = f"Surah {surah_no}:{ayah_no}" + + doc['reference'] = target_ref + + doc['target_reference'] = target_ref + + doc['audio_urls'] = get_quran_audio_urls(int(surah_no), [int(ayah_no)], language) + + surah_doc = await _get_surah_doc_from_r2(surah_no) + + if surah_doc: + + ayahs_list = surah_doc.get("ayahs", []) + + target_idx = next((idx for idx, a in enumerate(ayahs_list) if a.get("ayah_no") == ayah_no), None) + + if target_idx is not None: + + target_entry = ayahs_list[target_idx] + + if not doc.get("translations") and isinstance(target_entry.get("translations"), dict): + + doc["translations"] = dict(target_entry["translations"]) + + if not doc.get("text_arabic") and target_entry.get("text_arabic"): + + doc["text_arabic"] = target_entry["text_arabic"] + + if not doc.get("text_english"): + + doc["text_english"] = target_entry.get("translations", {}).get("en.sahih", target_entry.get("text_english", "")) + + start_idx = max(0, target_idx - 3) + + end_idx = min(len(ayahs_list), target_idx + 4) + + candidate_indices = list(range(start_idx, end_idx)) + + included_indices = [target_idx] + + try: + + candidate_texts = [ + + ayahs_list[idx].get('translations', {}).get('en.sahih', ayahs_list[idx].get('text_english', '')) + + for idx in candidate_indices + + ] + + candidate_vecs = await async_get_embedding(candidate_texts) + + target_local_idx = candidate_indices.index(target_idx) + + target_vec = candidate_vecs[target_local_idx] + + context_threshold = SEARCH_CONFIG["quran_context_similarity_threshold"] + + for idx in range(target_local_idx - 1, -1, -1): + + sim = np.dot(target_vec, candidate_vecs[idx]) + + if sim > context_threshold: + + included_indices.append(candidate_indices[idx]) + + else: + + break + + for idx in range(target_local_idx + 1, len(candidate_indices)): + + sim = np.dot(target_vec, candidate_vecs[idx]) + + if sim > context_threshold: + + included_indices.append(candidate_indices[idx]) + + else: + + break + + except Exception as ctx_err: + + logger.warning(f"[{req_id}] Quran neighbor context embedding skipped: {ctx_err}") + + included_indices.sort() + + context_ayahs = [ + + { + + "ayah_no": ayahs_list[idx].get("ayah_no"), + + "text_arabic": ayahs_list[idx].get("text_arabic", ""), + + "translations": ayahs_list[idx].get("translations", {}), + + "text_english": ayahs_list[idx].get("text_english", ""), + + } + + for idx in included_indices + + ] + + ayah_nums = [a.get("ayah_no") for a in context_ayahs] + + doc['context_ayahs'] = context_ayahs + + doc['has_neighbor_context'] = len(context_ayahs) > 1 + + if len(context_ayahs) > 1: + + doc['context_reference'] = f"Surah {surah_no}: {ayah_nums}" + + doc['audio_urls'] = get_quran_audio_urls(int(surah_no), ayah_nums, language) + + + + cached_candidates.append(doc) + + + + # Immediately warm Canonical 6-record Cache in Redis & L1 memory (only on clean non-partial results) + + if cached_candidates and not partial_failures: + + await set_cached_canonical_documents( + + [query, search_term], + + cached_candidates, + + books, + + query_vec, + + tier_cfg=cfg, + + ) + + + + return { + + "candidates": cached_candidates, + + "bi_encoder_candidates": bi_encoder_final_docs, + + "bi_encoder_metrics": bi_encoder_metrics, + + "query_vec": query_vec, + + "search_term": search_term, + + "used_bi_encoder": True, + + "used_cross_encoder": used_cross_encoder, + + "cache_hit": False, + + "cache_type": "PARTIAL_FAILURE" if partial_failures else "COLD_SEARCH", + + "search_status": "PARTIAL_FAILURE" if partial_failures else "OK", + + "partial_failures": partial_failures, + + "threshold_applied": min_sim, + + "num_candidates_used": scope, + + "timings": { + + "rew_ms": t_rew_ms, + + "embed_ms": t_embed_ms, + + "atlas_ms": t_atlas_ms, + + "rerank_ms": t_rerank_ms, + + }, + + } + + + + + +# ========================================================= + +# 8. MASTER API ROUTE (/ask) WITH HF LIFECYCLE LOGGING + +# ========================================================= + +@router.post("/ask") + +@limiter.limit("3000/minute" if not settings.IS_PROD else "10/minute") + +async def ask_handler(payload: AskRequest, request: Request, background_tasks: BackgroundTasks, user: dict = Depends(get_current_user)): + + payload.user_id = user["uid"] + + if not payload.session_id: + + payload.session_id = f"web-{user['uid']}" + + payload.session_id = str(payload.session_id)[:128] + + + + # Pure database-search utility: ignore all conversation/session history end to end + + payload.history = [] + + + + req_id = uuid.uuid4().hex[:8] + + t_start = time.perf_counter() + + t_auth_ms = float(user.get("_auth_duration_ms", 0.0)) + + t_cache_ms = 0.0 + + t_intent_ms = 0.0 + + t_embed_ms = 0.0 + + t_atlas_ms = 0.0 + + t_rerank_ms = 0.0 + + used_bi_encoder = False + + used_cross_encoder = False + + rag_cache_hit = False + + other_cache_hit = False + + was_in_flight = False + + partial_failures: List[str] = [] + + search_status = "OK" + + telemetry_cache_type = "COLD_SEARCH" + + + + user_tier = resolve_user_tier(user) + + tier_cfg = await get_tier_rag_config(user_tier) + + effective_top_k = resolve_effective_limit(payload.top_k, tier_cfg, hard_cap=MAX_CANONICAL_CACHE_DOCS) + + + + logger.info( + + f"[{req_id}] ASK_INIT: user={payload.user_id[:6]}*** tier={user_tier} auth={t_auth_ms:.1f}ms " + + f"lang={payload.language} req_k={payload.top_k} eff_k={effective_top_k} strict={payload.strict_mode} " + + f"books={payload.books} q_len={len(payload.query)}" + + ) + + + + def _greeting_reply_message(q_text: str) -> str: + + q_low = (q_text or "").lower() + + if "salam" in q_low or "assalam" in q_low: + + return "Wa Alaikum Assalam! I am a Quran and Hadith database search utility, not a chatbot. Please enter a topic, keyword, Quran verse (e.g., 2:255), or Hadith number (e.g., Bukhari 1) to search." + + return "Hello! I am SahihIslam, a Quran and Hadith database search utility. Please enter a topic, keyword, Quran verse, or Hadith number to search." + + + + # 🛑 Fast Greeting Check BEFORE Quota Consumption (Greetings do not consume search quota) + + if is_greeting_query(payload.query): + + msg = _greeting_reply_message(payload.query) + + greet_ms = (time.perf_counter() - t_start) * 1000.0 + + background_tasks.add_task( + + record_search_metric, + + used_bi_encoder=False, + + used_cross_encoder=False, + + rag_cache_hit=False, + + other_cache_hit=False, + + latency_ms=greet_ms, + + query_intent="greeting", + + language=payload.language, + + books_scope=payload.books, + + doc_count=0, + + cache_type="GREETING", + + ) + + return await stream_direct_message( + + msg, + + payload.user_id, + + payload.session_id, + + payload.query, + + background_tasks, + + "greeting", + + payload.language, + + effective_top_k, + + should_cache=False, + + audio_urls=[], + + books=payload.books, + + req_id=req_id, + + t_start=t_start, + + doc_count=0, + + ) + + + + # 🚀 ENFORCE PRO / DAILY FREE QUOTA VIA REDIS (DYNAMIC TIER PROFILE) + + daily_limit = int(tier_cfg.get("daily_query_limit", 10)) + + quota_consumed = False + + is_test_user = any(str(user.get("uid", "")).lower().startswith(p) for p in ("locust", "test", "mock", "dev", "sim")) + + if daily_limit > 0 and (settings.IS_PROD or not is_test_user): + + allowed, remaining = await redis_manager.check_and_increment_daily_ai_limit(user["uid"], limit=daily_limit, request_id=req_id) + + if not allowed: + + tier_name = tier_cfg.get("name", f"{user_tier.upper()} Tier") + + raise HTTPException( + + status_code=429, + + detail=f"Daily AI search limit ({daily_limit} queries) reached for {tier_name}. Upgrade to Sahih Islam Pro for higher limits.", + + ) + + quota_consumed = True + + + + # 🚀 STEP 1b: DETERMINISTIC CITATION & SEARCH ROUTING BEFORE CACHE READS (Zero Embedding Overhead) + + # Explicit citations & scope conflicts must be validated before reading caches so stale/mismatched cache entries cannot mask them. + + normalized_books = [b.lower() for b in payload.books] if payload.books else [] + + is_quran_only_mode = bool(normalized_books and len(normalized_books) == 1 and "quran" in normalized_books[0]) + + quran_allowed = (not normalized_books) or any("quran" in b for b in normalized_books) + + + + t_intent_0 = time.perf_counter() + + q_low = payload.query.lower() + + quran_match = _EXACT_QURAN_CITATION_RE.search(q_low) + + hadith_match = _EXACT_HADITH_CITATION_RE.search(q_low) + + is_explicit_citation_lookup = False + + citation_scope_conflict = False + + intent = "SEARCH_DB" + + + + if hadith_match: + + intent = "hadith_by_number" + + is_explicit_citation_lookup = True + + if is_quran_only_mode: + + citation_scope_conflict = True + + elif quran_match: + + intent = "quran_search" + + is_explicit_citation_lookup = True + + if not quran_allowed: + + citation_scope_conflict = True + + t_intent_ms = (time.perf_counter() - t_intent_0) * 1000.0 + + + + # Sync dynamic corpus revision across workers before reading any semantic response/canonical caches + + await refresh_corpus_revision() + + + + if not is_explicit_citation_lookup: + + # ⚡ TIER 1: EXACT RESPONSE CACHE (<1ms) — isolated by tier retrieval policy, corpus revision, query, limit, language + + t_c0 = time.perf_counter() + + cached_answer = await get_cached_llm_answer( + + query=payload.query, + + language=payload.language, + + top_k=effective_top_k, + + books=payload.books, + + strict_mode=payload.strict_mode, + + include_sanad=payload.include_sanad, + + tier_cfg=tier_cfg, + + ) + + t_cache_ms += (time.perf_counter() - t_c0) * 1000.0 + + if cached_answer and cached_answer.get("response"): + + hit_ms = (time.perf_counter() - t_start) * 1000.0 + + cached_doc_count = int(cached_answer.get("doc_count") or effective_top_k) + + print(f"[{req_id}] ⚡ [FULL RESPONSE CACHE HIT] Answer loaded in {hit_ms:.1f}ms. Bypassing DB & Embedding!") + + logger.info( + + f"[{req_id}] ⏱️ [TIMING][CACHE_HIT] " + + f"auth={t_auth_ms:.1f}ms cache={t_cache_ms:.1f}ms intent={t_intent_ms:.1f}ms embed=0.0ms atlas=0.0ms rerank=0.0ms " + + f"total={hit_ms:.1f}ms status=HIT type=FULL_RESPONSE docs={cached_doc_count}" + + ) + + background_tasks.add_task( + + record_search_metric, + + used_bi_encoder=False, + + used_cross_encoder=False, + + rag_cache_hit=False, + + other_cache_hit=True, + + latency_ms=hit_ms, + + query_intent="SEARCH_DB", + + language=payload.language, + + books_scope=payload.books, + + doc_count=cached_doc_count, + + cache_type="FULL_RESPONSE", + + ) + + return await stream_direct_message( + + cached_answer["response"], + + payload.user_id, + + payload.session_id, + + payload.query, + + background_tasks, + + "SEARCH_DB", + + payload.language, + + effective_top_k, + + source=cached_answer.get("source", "N/A"), + + grade=cached_answer.get("grade", "N/A"), + + narrator=cached_answer.get("narrator", "N/A"), + + should_cache=False, + + audio_urls=cached_answer.get("audio_urls", []), + + books=payload.books, + + req_id=req_id, + + t_start=t_start, + + doc_count=cached_doc_count, + + tier_cfg=tier_cfg, + + ) + + + + # ⚡ TIER 1b: MULTILINGUAL CANONICAL 6-RECORD CACHE (<1ms) — isolated by tier retrieval policy & corpus revision + + t_c1 = time.perf_counter() + + cached_canonical = await get_cached_canonical_documents( + + query=payload.query, + + top_k=effective_top_k, + + language=payload.language, + + books=payload.books, + + include_sanad=payload.include_sanad, + + allow_semantic_fallback=False, + + tier_cfg=tier_cfg, + + ) + + t_cache_ms += (time.perf_counter() - t_c1) * 1000.0 + + if cached_canonical: + + hit_ms = (time.perf_counter() - t_start) * 1000.0 + + print(f"[{req_id}] ⚡ [MULTILINGUAL CANONICAL CACHE HIT] {len(cached_canonical)} docs loaded in {hit_ms:.1f}ms for lang={payload.language}. Bypassing DB & Embedding!") + + direct_response, comb_refs, comb_grades, comb_narrators, comb_audio_urls, had_llm_failure = await _format_hadith_search_response_for_mode( + + cached_canonical, + + language=payload.language, + + include_sanad=payload.include_sanad, + + strict_mode=payload.strict_mode, + + ) + + if payload.strict_mode: + + direct_response = f"### 🔒 Strict Mode (Direct Database Match)\n\n{direct_response}" + + logger.info( + + f"[{req_id}] ⏱️ [TIMING][CACHE_HIT] " + + f"auth={t_auth_ms:.1f}ms cache={t_cache_ms:.1f}ms intent={t_intent_ms:.1f}ms embed=0.0ms atlas=0.0ms rerank=0.0ms " + + f"total={hit_ms:.1f}ms status=HIT type=MULTILINGUAL_CANONICAL lang={payload.language} docs={len(cached_canonical)}" + + ) + + background_tasks.add_task( + + record_search_metric, + + used_bi_encoder=False, + + used_cross_encoder=False, + + rag_cache_hit=False, + + other_cache_hit=True, + + latency_ms=hit_ms, + + query_intent="SEARCH_DB", + + language=payload.language, + + books_scope=payload.books, + + doc_count=len(cached_canonical), + + cache_type="MULTILINGUAL_CANONICAL", + + ) + + return await stream_direct_message( + + direct_response, + + payload.user_id, + + payload.session_id, + + payload.query, + + background_tasks, + + "SEARCH_DB", + + payload.language, + + effective_top_k, + + source=comb_refs, + + grade=comb_grades, + + narrator=comb_narrators, + + should_cache=not had_llm_failure, + + audio_urls=comb_audio_urls, + + books=payload.books, + + req_id=req_id, + + t_start=t_start, + + include_sanad=payload.include_sanad, + + doc_count=len(cached_canonical), + + tier_cfg=tier_cfg, + + strict_mode=payload.strict_mode, + + ) + + + + # Approximate global semantic-response substitution is removed so misses run fresh bi-encoder/Atlas search. + + query_vec = None + + final_hadiths: List[Dict[str, Any]] = [] + + citation_error = False + + # 🔍 Database Search Routing (Exact citation lookup first; nonexistent or scope-conflicting citations do not fall back to semantic search) + + if intent == "quran_search" and quran_match and not citation_scope_conflict: + + surah_no = int(quran_match.group(1) or quran_match.group(3) or quran_match.group(5)) + + _raw_ayat = quran_match.group(2) or quran_match.group(4) or quran_match.group(6) + + ayat_no = int(_raw_ayat) if _raw_ayat is not None else None + + telemetry_cache_type = "EXACT_CITATION" + + if 1 <= surah_no <= 114: + + print(f" • Parsing Exact Quran Match -> Surah {surah_no}, Ayat {ayat_no}") + + try: + + surah_doc = await _get_surah_doc_from_r2(surah_no, raise_on_error=True) + + except SurahLookupError as q_err: + + logger.error(f"[{req_id}] Exact Quran citation lookup failed for Surah {surah_no}: {q_err}") + + surah_doc = None + + citation_error = True + + search_status = "FAILED" + + if surah_doc: + + ayahs_list = surah_doc.get("ayahs", []) + + if ayat_no is not None: + + if ayat_no >= 1: + + target_ayah = next((a for a in ayahs_list if a.get("ayah_no") == ayat_no), None) + + if target_ayah: + + other_cache_hit = True + + final_hadiths.append({ + + "is_quran": True, + + "collection": "The Holy Quran", + + "surah_no": surah_no, + + "ayah_no": ayat_no, + + "reference": f"Surah {surah_no}:{ayat_no}", + + "target_reference": f"Surah {surah_no}:{ayat_no}", + + "grade": "Divine Revelation", + + "narrator": "Quran", + + "text_arabic": target_ayah.get('text_arabic', ''), + + "text_english": target_ayah.get('translations', {}).get('en.sahih', target_ayah.get('text_english', '')), + + "translations": target_ayah.get('translations', {}), + + "audio_urls": get_quran_audio_urls(surah_no, [ayat_no], payload.language), + + }) + + else: + + context_ayahs = ayahs_list[:min(effective_top_k, 3)] + + if context_ayahs: + + other_cache_hit = True + + for a in context_ayahs: + + a_no = a.get("ayah_no") + + final_hadiths.append({ + + "is_quran": True, + + "collection": "The Holy Quran", + + "surah_no": surah_no, + + "ayah_no": a_no, + + "reference": f"Surah {surah_no}:{a_no}", + + "target_reference": f"Surah {surah_no}:{a_no}", + + "grade": "Divine Revelation", + + "narrator": "Quran", + + "text_arabic": a.get('text_arabic', ''), + + "text_english": a.get('translations', {}).get('en.sahih', a.get('text_english', '')), + + "translations": a.get('translations', {}), + + "audio_urls": get_quran_audio_urls(surah_no, [a_no], payload.language) if a_no else [], + + }) + + elif intent == "hadith_by_number" and hadith_match and not citation_scope_conflict: + + target_id = int(hadith_match.group(1)) + + telemetry_cache_type = "EXACT_CITATION" + + print(f" • Parsing Exact Hadith Reference Match -> ID {target_id}") + + exact_filter: Dict[str, Any] = {"$or": [{"hadith_id": target_id}, {"hadith_id": str(target_id)}]} + + collection_mapping = { + + "bukhari": "Bukhari", "muslim": "Muslim", "tirmidhi": "Tirmidhi", "tirmizi": "Tirmidhi", + + "dawud": "Dawud", "dawood": "Dawud", "nasai": "Nasa'i", "majah": "Majah", + + "muwatta": "Muwatta", "ahmad": "Ahmad", "darimi": "Darimi", "daraqutni": "Daraqutni" + + } + + detected_col = next((val for key, val in collection_mapping.items() if key in q_low), None) + + if detected_col: + + exact_filter["collection"] = {"$regex": detected_col, "$options": "i"} + + elif payload.books and "The Holy Quran" not in payload.books: + + exact_filter["collection"] = {"$in": payload.books} + + try: + + exact_docs = await hadith_collection.find(exact_filter).to_list(length=effective_top_k) + + if exact_docs: + + final_hadiths = exact_docs[:effective_top_k] + + except Exception as exact_err: + + logger.error(f"[{req_id}] Exact Hadith citation DB query failed: {exact_err}") + + citation_error = True + + search_status = "FAILED" + + elif citation_scope_conflict: + + telemetry_cache_type = "EXACT_CITATION" + + # 🚀 UNIFIED HADITH + QURAN VECTOR SEARCH ENGINE (only for topic/semantic searches, never invalid explicit citations) + + if not final_hadiths and not is_explicit_citation_lookup and search_status != "FAILED": + + sf_key = make_canonical_docs_key(payload.query, payload.books, tier_cfg=tier_cfg) + + if payload.strict_mode and _needs_english_translation(payload.query): + + sf_key = f"{sf_key}:strict_q" + + was_in_flight = sf_key in single_flight_manager._flights + + t_sf_0 = time.perf_counter() + + sf_res = await single_flight_manager.execute( + + sf_key, + + _execute_cold_retrieval, + + query=payload.query, + + books=payload.books, + + history=None, + + language=payload.language, + + top_k=effective_top_k, + + include_sanad=payload.include_sanad, + + strict_mode=payload.strict_mode, + + user_tier=user_tier, + + tier_cfg=tier_cfg, + + req_id=req_id, + + ) + + t_retrieval_ms = (time.perf_counter() - t_sf_0) * 1000.0 + + cached_candidates = sf_res.get("candidates", []) + + query_vec = sf_res.get("query_vec") + + used_bi_encoder = bool(sf_res.get("used_bi_encoder", False)) + + used_cross_encoder = bool(sf_res.get("used_cross_encoder", False)) + + sf_cache_hit = bool(sf_res.get("cache_hit", False)) + + search_status = sf_res.get("search_status", "OK") + + partial_failures = list(sf_res.get("partial_failures") or []) + + t_timings = sf_res.get("timings", {}) + + t_embed_ms = float(t_timings.get("embed_ms", 0.0) or 0.0) + + t_atlas_ms = float(t_timings.get("atlas_ms", 0.0) or 0.0) + + t_rerank_ms = float(t_timings.get("rerank_ms", 0.0) or 0.0) + + # Slice the shared full canonical pool independently per caller (never reuse another caller's slice/language) + + final_hadiths = [dict(d) for d in cached_candidates[:effective_top_k]] + + if search_status == "FAILED": + + telemetry_cache_type = "FAILURE" + + elif was_in_flight: + + other_cache_hit = True + + telemetry_cache_type = "SINGLE_FLIGHT_COALESCED" + + elif sf_cache_hit: + + other_cache_hit = True + + telemetry_cache_type = sf_res.get("cache_type", "CANONICAL_TRANSLATED") + + else: + + telemetry_cache_type = sf_res.get("cache_type", "COLD_SEARCH") + + logger.info( + + f"[{req_id}] RETRIEVAL_TIMING: embed={t_embed_ms:.1f}ms atlas={t_atlas_ms:.1f}ms " + + f"rerank={t_rerank_ms:.1f}ms total_prep={(time.perf_counter() - t_start)*1000.0:.1f}ms " + + f"docs={len(final_hadiths)} status={search_status} cache_type={telemetry_cache_type} " + + f"bi_encoder={used_bi_encoder} cross_encoder={used_cross_encoder} was_coalesced={was_in_flight}" + + ) + + # Infrastructure / DB search failure MUST be distinguished from zero matches + + if search_status == "FAILED" or citation_error: + + if quota_consumed: + + try: + + await redis_manager.refund_daily_ai_limit(user["uid"], request_id=req_id) + + except Exception: + + pass + + fail_ms = (time.perf_counter() - t_start) * 1000.0 + + background_tasks.add_task( + + record_search_metric, + + used_bi_encoder=used_bi_encoder, + + used_cross_encoder=used_cross_encoder, + + rag_cache_hit=False, + + other_cache_hit=False, + + latency_ms=fail_ms, + + query_intent=intent, + + language=payload.language, + + books_scope=payload.books, + + doc_count=0, + + cache_type="FAILURE", + + ) + + raise HTTPException( + + status_code=503, + + detail="Database search service temporarily unavailable. Please try again.", + + ) + + if not final_hadiths: + + if citation_scope_conflict: + + msg = "No matching record found: the cited reference is outside the selected book scope." + + elif is_explicit_citation_lookup: + + msg = "No exact database record was found for the cited reference." + + else: + + msg = "No matching authentic records were found in the database for this query." + + if partial_failures: + + msg = ( + + f"Search failed for collection(s): {', '.join(partial_failures)}; " + + "no matching records were found in the remaining collections." + + ) + + miss_ms = (time.perf_counter() - t_start) * 1000.0 + + background_tasks.add_task( + + record_search_metric, + + used_bi_encoder=used_bi_encoder, + + used_cross_encoder=used_cross_encoder, + + rag_cache_hit=rag_cache_hit, + + other_cache_hit=other_cache_hit, + + latency_ms=miss_ms, + + query_intent=intent, + + language=payload.language, + + books_scope=payload.books, + + doc_count=0, + + cache_type=telemetry_cache_type, + + ) + + return await stream_direct_message( + + msg, + + payload.user_id, + + payload.session_id, + + payload.query, + + background_tasks, + + intent, + + payload.language, + + effective_top_k, + + should_cache=False, + + audio_urls=[], + + books=payload.books, + + req_id=req_id, + + t_start=t_start, + + doc_count=0, + + ) + + # Format Database Records: Strict Mode is pure DB text only; Non-Strict translates/transliterates missing translations via LLM + + direct_response, comb_refs, comb_grades, comb_narrators, comb_audio_urls, had_llm_failure = await _format_hadith_search_response_for_mode( + + final_hadiths, + + language=payload.language, + + include_sanad=payload.include_sanad, + + strict_mode=payload.strict_mode, + + ) + + if partial_failures: + + partial_note = f"*(Note: Database search error occurred for {', '.join(partial_failures)}. Showing available results from remaining collections.)*\n\n" + + direct_response = f"{partial_note}{direct_response}" + + if payload.strict_mode: + + direct_response = f"### 🔒 Strict Mode (Direct Database Match)\n\n{direct_response}" + + t_total_ms = (time.perf_counter() - t_start) * 1000.0 + + logger.info( + + f"[{req_id}] ⏱️ [TIMING][DIRECT_DB_SERVED] " + + f"auth={t_auth_ms:.1f}ms cache={t_cache_ms:.1f}ms intent={t_intent_ms:.1f}ms " + + f"embed={t_embed_ms:.1f}ms atlas={t_atlas_ms:.1f}ms rerank={t_rerank_ms:.1f}ms " + + f"total={t_total_ms:.1f}ms lang={payload.language} docs={len(final_hadiths)} " + + f"type={telemetry_cache_type} bi_encoder={used_bi_encoder}" + + ) + + background_tasks.add_task( + + record_search_metric, + + used_bi_encoder=used_bi_encoder, + + used_cross_encoder=used_cross_encoder, + + rag_cache_hit=rag_cache_hit, + + other_cache_hit=other_cache_hit, + + latency_ms=t_total_ms, + + query_intent=intent, + + language=payload.language, + + books_scope=payload.books, + + doc_count=len(final_hadiths), + + cache_type=telemetry_cache_type, + + ) + + return await stream_direct_message( + + direct_response, + + payload.user_id, + + payload.session_id, + + payload.query, + + background_tasks, + + intent, + + payload.language, + + effective_top_k, + + source=comb_refs, + + grade=comb_grades, + + narrator=comb_narrators, + + should_cache=(not bool(partial_failures)) and (not had_llm_failure), + + audio_urls=comb_audio_urls, + + precomputed_query_vec=query_vec, + + books=payload.books, + + req_id=req_id, + + t_start=t_start, + + include_sanad=payload.include_sanad, + + doc_count=len(final_hadiths), + + tier_cfg=tier_cfg, + + strict_mode=payload.strict_mode, + + ) + + + + + +# ========================================================= + +# 9. DAILY CONTENT ENGINE (Hadith of the Day / Ayah of the Day) + +# ========================================================= + +# Architecture for 1M users: + +# - We never run a semantic search per user per day. Instead we build + +# a SHARED, ordered "pool" of items (≈30) ONCE per Islamic month + +# (hadith) or per pool version (ayah) and cache it in MongoDB. + +# - Each user's "today" pick is a pure O(1) index into that pool by + +# day-of-month (hadith) or day-of-year (ayah). Same day → same item + +# for everyone; the pool ordering guarantees no repeat within a + +# month. Location only matters in that it decides which *Hijri* + +# date the user is on (different timezones can be on different days). + +# - The endpoints are wrapped in try/except and always degrade to a + +# safe fallback so the homepage never blocks on them. + + + +# Thematic semantic-search query per Hijri month. Drives which hadiths + +# surface for "Hadith of the Day" during that month. + +HIJRI_MONTH_THEMES = { + + 1: "the sanctity of Muharram, fasting the day of Ashura, the Islamic new year and sincere repentance", + + 2: "trust and reliance upon Allah, patience through hardship, and rejecting superstition and bad omens", + + 3: "the noble character and example of the Prophet Muhammad, his life (seerah) and sending blessings upon him", + + 4: "following the Sunnah of the Prophet, seeking beneficial knowledge and steadfast guidance", + + 5: "patience and gratitude during ease and hardship, generosity and charity to others", + + 6: "the remembrance of Allah (dhikr), constant supplication (dua) and turning to Allah", + + 7: "the sacred month of Rajab, preparing the heart for worship and seeking forgiveness", + + 8: "the month of Sha'ban, preparing for Ramadan, voluntary fasting and the night of forgiveness", + + 9: "the virtues of Ramadan, fasting, reciting the Quran, Laylatul Qadr, charity and night prayer", + + 10: "the six fasts of Shawwal, the joy and etiquette of Eid, and gratitude after Ramadan", + + 11: "the sacred months, peace and security, and preparing for the pilgrimage to Makkah", + + 12: "the virtues of the ten days of Dhul Hijjah, the Hajj pilgrimage, the day of Arafah and the sacrifice of Eid al-Adha", + +} + + + +# ============================================================================= +# DAILY AYAH & DAILY HADITH ENDPOINTS (FAJR AZAAN REFRESH ARCHITECTURE) +# ============================================================================= + +@router.post("/daily/refresh-fajr") +@limiter.limit("5/minute") +async def refresh_daily_content_endpoint( + request: Request, + current_user: dict = Depends(require_superadmin), + date: Optional[str] = None, + tz: Optional[str] = None, + fajr: Optional[str] = None, + force: bool = False, +): + """ + SuperAdmin administrative endpoint: triggers or forces Daily Ayah & Daily Hadith publication. + Accepts optional date (YYYY-MM-DD), IANA timezone (tz), Fajr Azaan time (fajr), and force flag. + """ + body_data = {} + content_type = "" + try: + raw_ct = request.headers.get("content-type", "") + if isinstance(raw_ct, str): + content_type = raw_ct + except Exception: + content_type = "" + + if content_type.startswith("application/json"): + try: + res_json = await request.json() + if isinstance(res_json, dict): + body_data = res_json + except Exception: + body_data = {} + + target_date = date + if not target_date and isinstance(body_data, dict): + raw_d = body_data.get("date") + if isinstance(raw_d, str): + target_date = raw_d + + target_tz = tz + if not target_tz and isinstance(body_data, dict): + raw_tz = body_data.get("tz") + if isinstance(raw_tz, str): + target_tz = raw_tz + + target_fajr = fajr + if not target_fajr and isinstance(body_data, dict): + raw_fajr = body_data.get("fajr") + if isinstance(raw_fajr, str): + target_fajr = raw_fajr + + is_force = force or (isinstance(body_data, dict) and bool(body_data.get("force", False))) + + from app.services.daily_content.common.timezone_utils import ( + validate_iana_timezone, + get_user_fajr_date, + ) + + if target_date: + target_date = str(target_date).strip() + try: + datetime.date.fromisoformat(target_date) + except ValueError: + raise HTTPException( + status_code=400, + detail=f"Invalid date format '{target_date}'. Expected YYYY-MM-DD." + ) + else: + try: + validated_tz = validate_iana_timezone(target_tz) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + target_date = get_user_fajr_date(validated_tz, fajr_time_str=target_fajr) + + from app.services.daily_content.coordinator import daily_coordinator + operator_uid = current_user.get("uid") or current_user.get("user_id") or "superadmin" + logger.info(f"🛡️ [ADMIN_REFRESH] Manual daily refresh invoked by SuperAdmin {operator_uid} for Fajr date {target_date} (force={is_force})") + summary = await daily_coordinator.execute_both_streams(target_date, force=is_force) + return { + "success": True, + "status": "completed", + "message": f"Daily Ayah & Hadith streams executed successfully for {target_date}.", + "target_date": target_date, + "triggered_by": operator_uid, + "summary": summary, + "force": is_force, + } + + +@router.get("/daily/status") +async def get_daily_status(current_user: dict = Depends(require_superadmin)): + """Observability endpoint for Daily Content Coordinator and stream health.""" + from app.services.daily_content.coordinator import daily_coordinator + return daily_coordinator.get_status() + + +@router.get("/hadith-of-the-day") +@limiter.limit("1200/minute") +async def hadith_of_the_day( + request: Request, + response: Response, + user: Optional[dict] = Depends(get_optional_user), + tz: Optional[str] = None, + fajr: Optional[str] = None, +): + """ + Retrieves the authoritative Daily Hadith from Redis cache. + Calculates the user's Fajr-Azaan publication date from their validated IANA timezone + and Fajr time, rolling over at Fajr Azaan rather than 12:00 AM midnight. + """ + from app.services.daily_content.common.timezone_utils import ( + validate_iana_timezone, + get_user_fajr_date, + seconds_until_next_fajr, + format_fajr_time, + ) + from app.services.daily_content.hadith.cache import HadithCacheManager + + try: + validated_tz = validate_iana_timezone(tz) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + fajr_time_str = format_fajr_time(fajr) + publication_date = get_user_fajr_date(validated_tz, fajr_time_str=fajr) + cached = await HadithCacheManager.get_active_hadith(publication_date) + + if not cached or cached.get("available") is not True: + try: + from app.services.daily_content.coordinator import daily_coordinator + await daily_coordinator.ensure_target_date_published(publication_date) + cached = await HadithCacheManager.get_active_hadith(publication_date) + except Exception as e: + logger.warning(f"On-demand hadith generation failed for {publication_date}: {e}") + + if not cached or cached.get("available") is not True: + from app.services.daily_content.fallback_pool import get_fallback_hadith_payload + cached = get_fallback_hadith_payload(publication_date) + try: + from app.services.daily_content.hadith.models import DailyHadithPayload + hadith_data = cached.get("hadith", {}) + payload_obj = DailyHadithPayload( + hadith_id=str(hadith_data.get("hadith_id", "1")), + collection=hadith_data.get("collection", "Sahih Bukhari"), + book_name=hadith_data.get("book_name", ""), + book_no=str(hadith_data.get("book_no", "1")), + volume=str(hadith_data.get("volume", "1")), + grade=hadith_data.get("grade", "Sahih"), + narrator=hadith_data.get("narrator", ""), + reference=hadith_data.get("reference", ""), + text_arabic=hadith_data.get("text_arabic", ""), + text_english=hadith_data.get("text_english", ""), + text_urdu=hadith_data.get("text_urdu", ""), + text_hinglish=hadith_data.get("text_hinglish", ""), + date=publication_date, + month_name=cached.get("month_name", "Authentic Hadith Sanctuary"), + content_version=cached.get("content_version", f"hadith:{publication_date}:fallback"), + translations=hadith_data.get("translations", {}), + ) + await HadithCacheManager.publish_hadith(payload_obj) + except Exception as e: + logger.warning(f"Failed caching fallback hadith: {e}") + + ttl_seconds = seconds_until_next_fajr(validated_tz, fajr_time_str=fajr) + try: + response.headers["Cache-Control"] = f"public, max-age={ttl_seconds}" + except Exception: + pass + + hadith_obj = cached.get("hadith", cached) + return { + "available": True, + "success": True, + "publication_date": publication_date, + "date": publication_date, + "timezone": validated_tz, + "fajr_time": fajr_time_str, + "content_version": cached.get("content_version", ""), + "hadith": hadith_obj, + "month_name": cached.get("month_name", "Authentic Hadith Sanctuary"), + "ttl": ttl_seconds, + "ttl_seconds": ttl_seconds, + "expires_in": ttl_seconds, + } + + +@router.get("/ayah-of-the-day") +@limiter.limit("1200/minute") +async def ayah_of_the_day( + request: Request, + response: Response, + user: Optional[dict] = Depends(get_optional_user), + tz: Optional[str] = None, + fajr: Optional[str] = None, +): + """ + Retrieves the authoritative Daily Ayah from Redis cache. + Calculates the user's Fajr-Azaan publication date from their validated IANA timezone + and Fajr time, rolling over at Fajr Azaan rather than 12:00 AM midnight. + """ + from app.services.daily_content.common.timezone_utils import ( + validate_iana_timezone, + get_user_fajr_date, + seconds_until_next_fajr, + format_fajr_time, + ) + from app.services.daily_content.ayah.cache import AyahCacheManager + + try: + validated_tz = validate_iana_timezone(tz) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + fajr_time_str = format_fajr_time(fajr) + publication_date = get_user_fajr_date(validated_tz, fajr_time_str=fajr) + cached = await AyahCacheManager.get_active_ayah(publication_date) + + if not cached or cached.get("available") is not True: + try: + from app.services.daily_content.coordinator import daily_coordinator + await daily_coordinator.ensure_target_date_published(publication_date) + cached = await AyahCacheManager.get_active_ayah(publication_date) + except Exception as e: + logger.warning(f"On-demand ayah generation failed for {publication_date}: {e}") + + if not cached or cached.get("available") is not True: + from app.services.daily_content.fallback_pool import get_fallback_ayah_payload + cached = get_fallback_ayah_payload(publication_date) + try: + from app.services.daily_content.ayah.models import DailyAyahPayload + ayah_data = cached.get("ayah", {}) + payload_obj = DailyAyahPayload( + surah_no=int(ayah_data.get("surah_no", 1)), + ayah_no=int(ayah_data.get("ayah_no", 1)), + text_arabic=ayah_data.get("text_arabic", ""), + text_urdu=ayah_data.get("text_urdu", ""), + text_english=ayah_data.get("text_english", ""), + text_hinglish=ayah_data.get("text_hinglish", ""), + reference=ayah_data.get("reference", ""), + date=publication_date, + content_version=cached.get("content_version", f"ayah:{publication_date}:fallback"), + translations=ayah_data.get("translations", {}), + ) + await AyahCacheManager.publish_ayah(payload_obj) + except Exception as e: + logger.warning(f"Failed caching fallback ayah: {e}") + + ttl_seconds = seconds_until_next_fajr(validated_tz, fajr_time_str=fajr) + try: + response.headers["Cache-Control"] = f"public, max-age={ttl_seconds}" + except Exception: + pass + + ayah_obj = dict(cached.get("ayah", cached)) + try: + s_no = ayah_obj.get("surah_no") + a_no = ayah_obj.get("ayah_no") + if s_no and a_no: + from app.services.daily_content.ayah.repository import AyahRepository + from app.services.daily_content.common.language_registry import SUPPORTED_DAILY_LANGUAGES + + db_source = await AyahRepository.fetch_authoritative_ayah(int(s_no), int(a_no)) + if db_source is not None: + merged_trans = dict(ayah_obj.get("translations") or {}) + for k, v in (db_source.raw_translations or {}).items(): + if v and str(v).strip(): + merged_trans[k] = str(v).strip() + + if db_source.text_arabic: + ayah_obj["text_arabic"] = db_source.text_arabic + merged_trans["ar"] = db_source.text_arabic + merged_trans["text_arabic"] = db_source.text_arabic + if db_source.text_urdu: + ayah_obj["text_urdu"] = db_source.text_urdu + merged_trans["ur"] = db_source.text_urdu + merged_trans["text_urdu"] = db_source.text_urdu + merged_trans["ur.jalandhry"] = db_source.text_urdu + if db_source.text_english: + ayah_obj["text_english"] = db_source.text_english + merged_trans["en"] = db_source.text_english + merged_trans["text_english"] = db_source.text_english + merged_trans["en.sahih"] = db_source.text_english + if db_source.text_hinglish: + ayah_obj["text_hinglish"] = db_source.text_hinglish + merged_trans["hinglish"] = db_source.text_hinglish + merged_trans["roman_urdu"] = db_source.text_hinglish + merged_trans["text_hinglish"] = db_source.text_hinglish + merged_trans["ur.roman"] = db_source.text_hinglish + if db_source.text_kashmiri: + ayah_obj["text_kashmiri"] = db_source.text_kashmiri + merged_trans["ks"] = db_source.text_kashmiri + merged_trans["text_kashmiri"] = db_source.text_kashmiri + merged_trans["ks.kashmiri"] = db_source.text_kashmiri + + for lang_code, meta in SUPPORTED_DAILY_LANGUAGES.items(): + c_key = meta.get("canonical_key") + if c_key and c_key in merged_trans and merged_trans[c_key]: + merged_trans[lang_code] = merged_trans[c_key] + + ayah_obj["translations"] = merged_trans + except Exception as enrich_err: + logger.debug(f"Daily ayah DB enrichment skipped: {enrich_err}") + + return { + "available": True, + "success": True, + "publication_date": publication_date, + "date": publication_date, + "timezone": validated_tz, + "fajr_time": fajr_time_str, + "content_version": cached.get("content_version", ""), + "ayah": ayah_obj, + "ttl": ttl_seconds, + "ttl_seconds": ttl_seconds, + "expires_in": ttl_seconds, + } + + +class DailyTranslationRequest(BaseModel): + content_type: str = 'ayah' # strictly 'ayah' or 'hadith' + surah_no: Optional[int] = None + ayah_no: Optional[int] = None + collection: Optional[str] = None + hadith_id: Optional[str] = None + content_version: Optional[str] = None + text: Optional[str] = None + target_language: Optional[str] = None + target_code: str = 'en' + reference: Optional[str] = '' + tz: Optional[str] = None + fajr: Optional[str] = None + + +@router.post('/translate-daily-content') +@router.post('/api/translate-daily-content') +@limiter.limit('600/minute') +async def translate_daily_content(req: DailyTranslationRequest, request: Request): + """ + Language switching translation resolver. + Retrieves the requested translation from DB/R2 or versioned Fajr-day Redis cache. + """ + c_type = (req.content_type or '').strip().lower() + if c_type not in ("ayah", "hadith"): + raise HTTPException( + status_code=400, + detail=f"Invalid content_type '{req.content_type}'. Must be strictly 'ayah' or 'hadith'." + ) + target_code = (req.target_code or 'en').strip().lower() + from app.services.daily_content.common.language_registry import is_supported_language + if not is_supported_language(target_code): + raise HTTPException( + status_code=400, + detail=f"Unsupported target_code '{target_code}'. Must be in configured languages." + ) + + from app.services.daily_content.common.timezone_utils import ( + validate_iana_timezone, + get_user_fajr_date, + ) + + try: + validated_tz = validate_iana_timezone(req.tz) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + publication_date = get_user_fajr_date(validated_tz, fajr_time_str=req.fajr) + + if c_type == "ayah": + from app.services.daily_content.ayah.cache import ( + AyahCacheManager, + key_ayah_translation_versioned, + key_ayah_payload_versioned, + ) + from app.services.daily_content.common.language_registry import ( + get_language_meta, + normalize_language_code, + ) + from app.services.daily_content.common.timezone_utils import RETENTION_SECONDS + from app.services.daily_content.ayah.repository import AyahRepository + from app.services.daily_content.ayah.processor import daily_ayah_processor + + norm_code = normalize_language_code(target_code) + meta = get_language_meta(norm_code) or {} + c_key = meta.get("canonical_key") + text: Optional[str] = None + + def _extract_from_tmap(t_map: dict) -> Optional[str]: + if not isinstance(t_map, dict) or not t_map: + return None + for k in (target_code, norm_code, getattr(req, "target_language", None), c_key): + if k and k in t_map and t_map[k]: + v = str(t_map[k]).strip() + if v and v.lower() not in ("null", "none", "not available", "n/a"): + return v + for k, v in t_map.items(): + k_str = str(k).strip().lower() + if (k_str == norm_code or k_str.startswith(f"{norm_code}.")) and not (norm_code == "ur" and k_str == "ur.roman"): + cleaned = str(v).strip() + if cleaned and cleaned.lower() not in ("null", "none", "not available", "n/a"): + return cleaned + return None + + # 1. Fast path: Redis translation cache + text = await AyahCacheManager.get_ayah_translation(publication_date, norm_code) + if not text and target_code != norm_code: + text = await AyahCacheManager.get_ayah_translation(publication_date, target_code) + + active_ayah = await AyahCacheManager.get_active_ayah(publication_date) if not text else None + ayah_data = active_ayah.get("ayah", active_ayah) if active_ayah else {} + t_map = ayah_data.get("translations", {}) if isinstance(ayah_data.get("translations"), dict) else {} + + surah_no = int(ayah_data.get("surah_no") or req.surah_no or 1) + ayah_no = int(ayah_data.get("ayah_no") or req.ayah_no or 1) + + if not text and t_map: + text = _extract_from_tmap(t_map) + + # 2. Authoritative MongoDB + R2 database lookup FIRST for ANY language before LLM + db_source = None + if not text: + db_source = await AyahRepository.fetch_authoritative_ayah(surah_no, ayah_no) + if db_source is not None: + candidate = daily_ayah_processor.translator.find_db_translation( + db_source, norm_code, canonical_key=c_key + ) + if candidate: + is_valid, _ = daily_ayah_processor.translator.validator.validate_translation( + norm_code, candidate, db_source.text_arabic + ) + if is_valid: + text = candidate + + # 3. Call LLM ONLY for languages unavailable in DB/R2 + if not text: + llm_source = db_source + if llm_source is None and ayah_data.get("text_arabic"): + from app.services.daily_content.ayah.models import DailyAyahSource + llm_source = DailyAyahSource( + surah_no=surah_no, + ayah_no=ayah_no, + reference=ayah_data.get("reference") or f"Surah {surah_no}:{ayah_no}", + text_arabic=ayah_data.get("text_arabic"), + text_urdu=ayah_data.get("text_urdu") or "", + text_english=ayah_data.get("text_english") or "", + ) + if llm_source is not None: + text = await daily_ayah_processor.translator._translate_single_language(llm_source, norm_code) + + # Cache resolved translation back to Redis so repeat hits are instant + if text and active_ayah: + version = active_ayah.get("content_version") or "v1" + from app.redis_client import redis_manager + await redis_manager.set( + key_ayah_translation_versioned(publication_date, version, norm_code), + text, + expire_seconds=RETENTION_SECONDS, + ) + if isinstance(t_map, dict): + t_map[norm_code] = text + if c_key: + t_map[c_key] = text + ayah_data["translations"] = t_map + active_ayah["ayah"] = ayah_data + await redis_manager.set( + key_ayah_payload_versioned(publication_date, version), + json.dumps(active_ayah, ensure_ascii=False), + expire_seconds=RETENTION_SECONDS, + ) + else: + from app.services.daily_content.hadith.cache import ( + HadithCacheManager, + key_hadith_translation_versioned, + key_hadith_payload_versioned, + ) + from app.services.daily_content.common.timezone_utils import RETENTION_SECONDS + text = await HadithCacheManager.get_hadith_translation(publication_date, target_code) + if not text: + active_hadith = await HadithCacheManager.get_active_hadith(publication_date) + if active_hadith: + hadith_data = active_hadith.get("hadith", active_hadith) + t_map = hadith_data.get("translations", {}) if isinstance(hadith_data.get("translations"), dict) else {} + text = t_map.get(target_code) or t_map.get(getattr(req, "target_language", None)) + if not text: + from app.services.daily_content.common.language_registry import get_language_meta + meta = get_language_meta(target_code) or {} + c_key = meta.get("canonical_key") + if c_key and c_key in t_map: + text = t_map[c_key] + + # Core languages (Arabic, Urdu, English, Roman Urdu) must be fetched from DB + if not text: + if target_code in ("ar", "text_arabic"): + text = hadith_data.get("text_arabic") or hadith_data.get("text") + elif target_code in ("ur", "text_urdu", "ur.jalandhry"): + text = hadith_data.get("text_urdu") + elif target_code in ("en", "text_english", "en.sahih"): + text = hadith_data.get("text_english") + elif target_code in ("hinglish", "text_hinglish", "roman_urdu", "ur.roman"): + text = hadith_data.get("text_hinglish") or hadith_data.get("text_roman_urdu") or hadith_data.get("ur.roman") + elif target_code in ("ks", "kashmiri", "ks.kashmiri", "text_kashmiri"): + text = hadith_data.get("text_kashmiri") or hadith_data.get("kashmiri") or hadith_data.get("ks.kashmiri") + + # If not present in payload, query MongoDB directly for the 4 core languages + if not text and target_code in ("ar", "ur", "en", "hinglish", "roman_urdu", "ur.roman", "text_arabic", "text_urdu", "text_english", "text_hinglish", "ks", "kashmiri", "ks.kashmiri", "text_kashmiri"): + try: + h_id = str(hadith_data.get("hadith_id") or req.hadith_id or "").strip() + col = str(hadith_data.get("collection") or req.collection or "").strip() + if h_id: + from app.database import hadith_collection + q = {"hadith_id": h_id} + if col: + q["collection"] = {"$regex": f"^{col}$", "$options": "i"} + h_doc = await hadith_collection.find_one(q) + if h_doc: + if target_code in ("ar", "text_arabic"): + text = h_doc.get("text_arabic") + elif target_code in ("ur", "text_urdu", "ur.jalandhry"): + text = h_doc.get("text_urdu") or h_doc.get("text_ur") + elif target_code in ("en", "text_english", "en.sahih"): + text = h_doc.get("text_english") or h_doc.get("text_en") + elif target_code in ("hinglish", "text_hinglish", "roman_urdu", "ur.roman"): + text = h_doc.get("text_hinglish") or h_doc.get("text_roman_urdu") or h_doc.get("roman_urdu") or h_doc.get("ur.roman") + elif target_code in ("ks", "kashmiri", "ks.kashmiri", "text_kashmiri"): + text = h_doc.get("text_kashmiri") or h_doc.get("kashmiri") or h_doc.get("ks.kashmiri") + except Exception as e: + logger.error(f"[DAILY_HADITH_TRANSLATE] Error querying core DB translation: {e}") + + # Rest translations are generated by LLM from Arabic Matn + if not text and (hadith_data.get("text_arabic") or hadith_data.get("text")): + from app.services.daily_content.hadith.processor import daily_hadith_processor + from app.services.daily_content.hadith.models import DailyHadithSource + h_id = str(hadith_data.get("hadith_id") or req.hadith_id or "1") + col = str(hadith_data.get("collection") or req.collection or "Sahih al-Bukhari") + ar_matn = hadith_data.get("text_arabic") or hadith_data.get("text") or "" + source = DailyHadithSource( + hadith_id=h_id, + collection=col, + book_name=str(hadith_data.get("book_name") or ""), + book_no=str(hadith_data.get("book_no") or ""), + volume=str(hadith_data.get("volume") or ""), + grade=str(hadith_data.get("grade") or "Sahih Authentic"), + narrator=str(hadith_data.get("narrator") or ""), + reference=str(hadith_data.get("reference") or f"{col} {h_id}"), + raw_text_arabic=ar_matn, + extracted_matn_arabic=ar_matn, + raw_text_english=hadith_data.get("text_english") or "", + raw_text_urdu=hadith_data.get("text_urdu") or "", + raw_text_roman_urdu=hadith_data.get("text_hinglish") or "", + ) + text = await daily_hadith_processor.translator._translate_matn_to_language(source, ar_matn, target_code) + if text: + version = active_hadith.get("content_version") or "v1" + from app.redis_client import redis_manager + await redis_manager.set( + key_hadith_translation_versioned(publication_date, version, target_code), + text, + expire_seconds=RETENTION_SECONDS, + ) + t_map[target_code] = text + hadith_data["translations"] = t_map + active_hadith["hadith"] = hadith_data + await redis_manager.set( + key_hadith_payload_versioned(publication_date, version), + json.dumps(active_hadith, ensure_ascii=False), + expire_seconds=RETENTION_SECONDS, + ) + + is_canonical = False + if not text and c_type == "hadith" and getattr(req, "hadith_id", None): + try: + h_col = str(getattr(req, "collection", "")).strip() + h_id = str(getattr(req, "hadith_id", "")).strip() + from app.database import hadith_collection + query = {"hadith_id": h_id} + if h_col: + query["collection"] = {"$regex": f"^{h_col}$", "$options": "i"} + h_doc = await hadith_collection.find_one(query) + if h_doc: + if target_code in ("hinglish", "roman_urdu"): + text = h_doc.get("text_hinglish") or h_doc.get("roman_urdu") + if text: + is_canonical = True + elif target_code == "en": + text = h_doc.get("text_english") + if text: + is_canonical = True + elif target_code == "ur": + text = h_doc.get("text_urdu") + if text: + is_canonical = True + elif target_code == "ar": + text = h_doc.get("text_arabic") + if text: + is_canonical = True + except Exception as e: + logger.debug(f"Direct canonical DB lookup note: {e}") + + if text: + return { + "success": True, + "status": "completed" if not is_canonical else "ready", + "translation": text, + "cached": not is_canonical, + "canonical": is_canonical, + "target_code": target_code, + "content_type": c_type, + "publication_date": publication_date, + "date": publication_date, + "timezone": validated_tz, + } + + return { + "success": False, + "status": "unavailable", + "translation": None, + "cached": False, + "target_code": target_code, + "content_type": c_type, + "publication_date": publication_date, + "date": publication_date, + "timezone": validated_tz, + } + + +class BookHadithTranslateRequest(BaseModel): + target_code: str = Field(..., min_length=2, max_length=32) + target_language: Optional[str] = Field(None, max_length=64) + text_arabic: Optional[str] = Field("", max_length=12000) + text_english: Optional[str] = Field("", max_length=12000) + text_urdu: Optional[str] = Field("", max_length=12000) + reference: Optional[str] = Field("", max_length=250) + collection: Optional[str] = Field("", max_length=120) + narrator: Optional[str] = Field("", max_length=250) + tz: Optional[str] = Field(None, max_length=64) + + +@router.get("/book-hadith/quota") +@router.get("/api/book-hadith/quota") +@limiter.limit("60/minute") +async def book_hadith_quota_endpoint( + request: Request, + tz: Optional[str] = None, + current_user: Optional[dict] = Depends(get_optional_user), +): + """ + Read-only daily quota status for real-time Book Hadith card AI translations. + Returns {tier, limit, used, remaining} without incrementing or persisting anything. + """ + from app.services.book_hadith_translation import get_book_hadith_quota_status + + client_ip = ( + request.headers.get("cf-connecting-ip") + or (request.headers.get("x-forwarded-for") or "").split(",")[0].strip() + or (request.client.host if request.client else "anon") + ) + status = await get_book_hadith_quota_status( + user=current_user, + client_ip=client_ip, + tz=tz, + ) + return { + "success": True, + **status, + } + + +@router.post("/book-hadith/translate") +@router.post("/api/book-hadith/translate") +@limiter.limit("60/minute") +async def translate_book_hadith_endpoint( + req: BookHadithTranslateRequest, + request: Request, + current_user: Optional[dict] = Depends(get_optional_user), +): + """ + Independent real-time LLM translation for Hadith cards shared from Books. + Strictly separated from Hadith of the Day and never persisted in Redis/MongoDB. + Enforces daily plan-based limits (Free: 1, Other paid plans: 3, Plus: 5, Pro: 10). + """ + from app.services.daily_content.common.language_registry import is_supported_language + from app.services.book_hadith_translation import translate_book_hadith_realtime + + if not is_supported_language(req.target_code): + raise HTTPException( + status_code=400, + detail=f"Unsupported target_code '{req.target_code}'.", + ) + + client_ip = ( + request.headers.get("cf-connecting-ip") + or (request.headers.get("x-forwarded-for") or "").split(",")[0].strip() + or (request.client.host if request.client else "anon") + ) + + try: + result = await translate_book_hadith_realtime( + target_code=req.target_code, + target_language=req.target_language, + text_arabic=req.text_arabic or "", + text_english=req.text_english or "", + text_urdu=req.text_urdu or "", + reference=req.reference or "", + collection=req.collection or "", + narrator=req.narrator or "", + user=current_user, + client_ip=client_ip, + tz=req.tz, + ) + except ValueError as ve: + raise HTTPException(status_code=400, detail=str(ve)) + + if result.get("quota_exceeded"): + limit = result.get("limit", 1) + tier = result.get("tier", "free") + tier_label = { + "pro": "Pro", + "plus": "Progress Plus", + "other_plan": "your current plan", + "free": "Free", + }.get(tier, tier) + return JSONResponse( + status_code=429, + content={ + "success": False, + "quota_exceeded": True, + "tier": tier, + "limit": limit, + "used": result.get("used", limit), + "remaining": 0, + "detail": ( + f"Daily book Hadith translation limit reached ({limit}/{limit} per day for {tier_label})." + ), + }, + ) + + if result.get("failed") or not result.get("translation"): + return JSONResponse( + status_code=503, + content={ + "success": False, + "status": "unavailable", + "translation": None, + "detail": "Unable to generate translation right now. Please try again.", + }, + ) + + return { + "success": True, + "status": "completed", + "translation": result["translation"], + "target_code": result["target_code"], + "tier": result["tier"], + "limit": result["limit"], + "remaining": result["remaining"], + "ephemeral": True, + "cached": False, + } + + +class AiResponseReportRequest(BaseModel): + response_text: str = Field(..., min_length=5, max_length=5000, description="The AI-generated response text being reported") + query: Optional[str] = Field(None, max_length=500, description="The prompt or query that triggered the response") + source: Optional[str] = Field(None, max_length=250, description="Attributed source or citation metadata") + reason: str = Field(..., max_length=50, description="Report reason category") + details: Optional[str] = Field(None, max_length=500, description="Optional user details or context") + session_id: Optional[str] = Field(None, max_length=100, description="Optional session or chat identifier") + +ALLOWED_AI_REPORT_REASONS = { + "fabricated_quran_hadith", + "offensive_abusive", + "harmful_advice", + "privacy_exposure", + "other", +} + +_AI_REPORT_MEM_CACHE: Dict[str, List[float]] = {} + + +@router.post("/api/ai/report-response") +@router.post("/ai/report-response") +async def report_ai_response( + payload: AiResponseReportRequest, + request: Request, + user: dict = Depends(get_current_user), +): + """ + Google Play Policy Compliant In-App Reporting for Generative AI Responses (F-02). + Allows users to report offensive, fabricated, or policy-violating AI responses. + Secured with per-IP rate limiting, payload validation, authenticated identity, and administrative review logging. + """ + import time + client_ip = request.client.host if request.client else "unknown" + user_id = user.get("uid") + if not user_id: + raise HTTPException(status_code=401, detail="Authentication required to report AI responses.") + client_ip_hash = hashlib.sha256(client_ip.encode("utf-8")).hexdigest()[:16] + + # 1. Validate reason category + clean_reason = payload.reason.strip().lower() + if clean_reason not in ALLOWED_AI_REPORT_REASONS: + raise HTTPException( + status_code=400, + detail=f"Invalid report reason. Allowed categories: {list(ALLOWED_AI_REPORT_REASONS)}", + ) + + # 2. Rate limiting (prevent flood spam: max 5 reports per 10 minutes per user/IP) + rate_key = f"ai_report_limit:{user_id}:{client_ip}" + redis_checked = False + try: + current_count = await redis_manager.incr(rate_key) + if current_count == 1: + await redis_manager.expire(rate_key, 600) # 10 minutes + if current_count > 5: + raise HTTPException( + status_code=429, + detail="Too many reports submitted. Please wait a few minutes before submitting another report.", + ) + redis_checked = True + except HTTPException: + raise + except Exception as e: + logger.warning(f"[AI REPORT] Redis rate limit check failed, falling back to bounded in-memory limiter: {e}") + + if not redis_checked: + now_ts = time.time() + # Clean cache if oversized + if len(_AI_REPORT_MEM_CACHE) > 2000: + stale_keys = [k for k, v in _AI_REPORT_MEM_CACHE.items() if not v or v[-1] < (now_ts - 600)] + for k in stale_keys: + _AI_REPORT_MEM_CACHE.pop(k, None) + mem_timestamps = [t for t in _AI_REPORT_MEM_CACHE.get(rate_key, []) if t > (now_ts - 600)] + if len(mem_timestamps) >= 5: + _AI_REPORT_MEM_CACHE[rate_key] = mem_timestamps + raise HTTPException( + status_code=429, + detail="Too many reports submitted. Please wait a few minutes before submitting another report.", + ) + mem_timestamps.append(now_ts) + _AI_REPORT_MEM_CACHE[rate_key] = mem_timestamps + + # 3. Store report securely in MongoDB + now_dt = datetime.datetime.utcnow() + report_id = f"AIR_{uuid.uuid4().hex[:12]}" + report_doc = { + "report_id": report_id, + "user_id": user_id, + "client_ip_hash": client_ip_hash, + "reason": clean_reason, + "details": (payload.details or "").strip()[:500], + "query": (payload.query or "").strip()[:500], + "response_snippet": payload.response_text.strip()[:1000], + "source": (payload.source or "").strip()[:250], + "session_id": (payload.session_id or "").strip()[:100], + "status": "pending_review", + "created_at": now_dt, # Native BSON Date + "timestamp": now_dt.isoformat(), + } + + try: + from app.infrastructure.mongodb import ai_response_reports_collection + await ai_response_reports_collection.insert_one(report_doc) + logger.info(f"[AI REPORT] Registered report {report_id} by user {user_id} for reason: {clean_reason}") + except Exception as e: + logger.error(f"[AI REPORT] Failed to save report to database: {e}") + raise HTTPException(status_code=500, detail="Database failure recording report. Please try again later.") + + return { + "status": "ok", + "report_id": report_id, + "message": "Report submitted successfully for scholarly and safety review. Thank you for your feedback.", + "created_at": report_doc["timestamp"], + } + + +async def close_hadith_clients() -> None: + + """Closes shared httpx clients and stops memory indexing worker upon process shutdown.""" + + global _hadith_http_clients + + await stop_memory_indexing_worker() + + for client in list(_hadith_http_clients.values()): + + if not client.is_closed: + + try: + + await client.aclose() + + except Exception: + + pass + + _hadith_http_clients.clear() +