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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
"""

Query Router Module



This module intelligently routes queries between local document search

and live web search based on query analysis and user preferences.



Technology: Custom routing logic with RAG + Live Search integration

"""

import logging
import time
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
from enum import Enum


class QueryType(Enum):
    """Enumeration of different query types for routing decisions."""

    FACTUAL = "factual"  # πŸ“Š Current facts, news, data
    CONCEPTUAL = "conceptual"  # πŸ’‘ Definitions, explanations
    PROCEDURAL = "procedural"  # πŸ”§ How-to, instructions
    ANALYTICAL = "analytical"  # πŸ“ˆ Analysis, comparisons
    TEMPORAL = "temporal"  # ⏰ Time-sensitive information
    HYBRID = "hybrid"  # πŸ”„ Requires both sources


class QueryRouter:
    """

    Intelligent query router that decides between local docs and live search.



    Features:

    - Query type classification

    - Intelligent routing decisions

    - Hybrid search coordination

    - Result fusion and ranking

    - Performance optimization

    """

    def __init__(

        self,

        local_query_processor,

        live_search_processor,

        config: Optional[Dict[str, Any]] = None,

    ):
        """

        Initialize the QueryRouter.



        Args:

            local_query_processor: Local document query processor

            live_search_processor: Live web search processor

            config: Configuration dictionary

        """
        self.local_processor = local_query_processor
        self.live_processor = live_search_processor
        self.config = config or {}
        self.logger = logging.getLogger(__name__)

        # 🎯 Routing configuration
        self.enable_hybrid_search = self.config.get("enable_hybrid_search", True)
        self.local_weight = self.config.get("local_weight", 0.6)
        self.live_weight = self.config.get("live_weight", 0.4)
        self.confidence_threshold = self.config.get("confidence_threshold", 0.5)
        self.max_hybrid_results = self.config.get("max_hybrid_results", 10)

        # πŸ“Š Analytics and caching
        self.routing_history = []
        self.routing_cache = {}

        # πŸ” Query classification patterns
        self._init_classification_patterns()

        self.logger.info("QueryRouter initialized with intelligent routing")

    def _init_classification_patterns(self):
        """Initialize patterns for query classification."""
        self.temporal_keywords = {
            "current",
            "latest",
            "recent",
            "today",
            "now",
            "2025",
            "breaking",
            "news",
            "update",
            "trending",
            "happening",
        }

        self.factual_keywords = {
            "what is",
            "who is",
            "when did",
            "where is",
            "statistics",
            "data",
            "facts",
            "numbers",
            "rate",
            "percentage",
        }

        self.procedural_keywords = {
            "how to",
            "steps",
            "guide",
            "tutorial",
            "instructions",
            "process",
            "method",
            "way to",
            "procedure",
        }

        self.conceptual_keywords = {
            "explain",
            "definition",
            "meaning",
            "concept",
            "theory",
            "principle",
            "idea",
            "understand",
            "clarify",
        }

    def route_query(

        self,

        query: str,

        use_live_search: bool = False,

        max_results: int = 5,

        search_options: Optional[Dict[str, Any]] = None,

        search_mode: str = "auto",

    ) -> Dict[str, Any]:
        """

        Route query to appropriate search method(s) with enhanced control.



        Args:

            query: User query string

            use_live_search: Enable live search (will use hybrid approach)

            max_results: Maximum results to return

            search_options: Additional search options

            search_mode: Search mode - "auto", "local_only", "live_only", "hybrid"



        Returns:

            Dictionary with routed results and metadata

        """
        if not query or not query.strip():
            return {
                "query": query,
                "results": [],
                "routing_decision": "error",
                "error": "Empty query provided",
            }

        self.logger.info(f" Routing query: {query[:100]}...")
        start_time = time.time()

        try:
            # 🎯 Classify query type
            query_type = self._classify_query(query)

            # πŸ”„ Make routing decision with enhanced logic
            routing_decision = self._make_enhanced_routing_decision(
                query, query_type, use_live_search, search_mode
            )

            # πŸš€ Execute search based on routing decision
            if routing_decision == "local_only":
                result = self._search_local_only(query, max_results)
            elif routing_decision == "live_only":
                result = self._search_live_only(query, max_results, search_options)
            elif routing_decision == "hybrid":
                result = self._search_hybrid(query, max_results, search_options)
            else:
                result = self._search_fallback(query, max_results)

            # πŸ“Š Add routing metadata
            result.update(
                {
                    "query_type": query_type.value,
                    "routing_decision": routing_decision,
                    "processing_time": time.time() - start_time,
                    "timestamp": datetime.now(),
                }
            )

            # πŸ“ˆ Track routing decision
            self._track_routing_decision(query, query_type, routing_decision)

            self.logger.info(
                f" Query routed via {routing_decision} in {result['processing_time']:.2f}s"
            )
            return result

        except Exception as e:
            self.logger.error(f" Error in query routing: {str(e)}")
            return {
                "query": query,
                "results": [],
                "routing_decision": "error",
                "error": str(e),
                "processing_time": time.time() - start_time,
            }

    def _classify_query(self, query: str) -> QueryType:
        """

        Classify query type for routing decisions.



        Args:

            query: Query string to classify



        Returns:

            QueryType enum value

        """
        query_lower = query.lower()

        # πŸ” Check for temporal indicators
        if any(keyword in query_lower for keyword in self.temporal_keywords):
            return QueryType.TEMPORAL

        # πŸ“Š Check for factual queries
        if any(keyword in query_lower for keyword in self.factual_keywords):
            return QueryType.FACTUAL

        # πŸ”§ Check for procedural queries
        if any(keyword in query_lower for keyword in self.procedural_keywords):
            return QueryType.PROCEDURAL

        # πŸ’‘ Check for conceptual queries
        if any(keyword in query_lower for keyword in self.conceptual_keywords):
            return QueryType.CONCEPTUAL

        # πŸ“ˆ Default to analytical for complex queries
        if len(query.split()) > 10:
            return QueryType.ANALYTICAL

        # πŸ”„ Default to hybrid for uncertain cases
        return QueryType.HYBRID

    def _make_routing_decision(

        self, query: str, query_type: QueryType, force_live: bool

    ) -> str:
        """

        Make intelligent routing decision based on query analysis.



        Args:

            query: Query string

            query_type: Classified query type

            force_live: Whether to enable live search (not force only live)



        Returns:

            Routing decision string

        """
        # πŸ”„ Smart hybrid approach when live search is enabled
        if force_live:
            # ✨ Instead of live_only, use hybrid to combine both sources
            if query_type == QueryType.TEMPORAL:
                return "hybrid"  # ⏰ Time-sensitive + stored context
            else:
                return "hybrid"  # 🎯 Always combine live + stored data

        # 🎯 Route based on query type (when live search is disabled)
        if query_type == QueryType.TEMPORAL:
            return "local_only"  # ⏰ Only stored data when live disabled

        elif query_type == QueryType.FACTUAL:
            return "local_only"  # πŸ“Š Facts from stored documents

        elif query_type == QueryType.PROCEDURAL:
            return "local_only"  # πŸ”§ Procedures likely in documents

        elif query_type == QueryType.CONCEPTUAL:
            return "local_only"  # πŸ’‘ Concepts likely in documents

        elif query_type == QueryType.ANALYTICAL:
            return "local_only"  # πŸ“ˆ Analysis from stored data

        else:  # QueryType.HYBRID
            return "local_only"  # πŸ”„ Default to local when live disabled

    def _make_enhanced_routing_decision(

        self, query: str, query_type: QueryType, use_live_search: bool, search_mode: str

    ) -> str:
        """

        Enhanced routing decision with explicit search mode control.



        Args:

            query: Query string

            query_type: Classified query type

            use_live_search: Whether live search is enabled

            search_mode: Explicit search mode preference



        Returns:

            Routing decision string

        """
        # 🎯 Explicit mode override - user ka choice priority
        if search_mode == "local_only":
            return "local_only"
        elif search_mode == "live_only":
            return "live_only" if self.live_processor.is_enabled() else "local_only"
        elif search_mode == "hybrid":
            return "hybrid" if self.live_processor.is_enabled() else "local_only"

        # 🧠 Auto mode - intelligent decision making
        elif search_mode == "auto":
            return self._make_routing_decision(query, query_type, use_live_search)

        # πŸ”„ Fallback to original logic
        else:
            return self._make_routing_decision(query, query_type, use_live_search)

    def _search_local_only(self, query: str, max_results: int) -> Dict[str, Any]:
        """Search only local documents."""
        self.logger.info(" Searching local documents only")

        try:
            local_result = self.local_processor.process_query(query)

            # πŸ”„ Format results consistently
            formatted_results = []
            for item in local_result.get("context", [])[:max_results]:
                formatted_results.append(
                    {
                        "title": f"Document: {item.get('source', 'Unknown')}",
                        "content": item.get("text", ""),
                        "score": item.get("score", 0.0),
                        "source": item.get("source", "local_document"),
                        "type": "local_document",
                        "metadata": item.get("metadata", {}),
                    }
                )

            return {
                "query": query,
                "results": formatted_results,
                "total_results": len(formatted_results),
                "sources": ["local_documents"],
                "local_results": local_result.get("total_results", 0),
            }

        except Exception as e:
            self.logger.error(f" Local search error: {str(e)}")
            return {
                "query": query,
                "results": [],
                "total_results": 0,
                "error": f"Local search failed: {str(e)}",
            }

    def _search_live_only(

        self, query: str, max_results: int, search_options: Optional[Dict[str, Any]]

    ) -> Dict[str, Any]:
        """Search only live web sources."""
        self.logger.info(" Searching live web sources only")

        try:
            # 🎯 Extract search options
            options = search_options or {}
            search_depth = options.get("search_depth", "basic")
            time_range = options.get("time_range", "month")

            live_result = self.live_processor.search_web(
                query,
                max_results=max_results,
                search_depth=search_depth,
                time_range=time_range,
            )

            return {
                "query": query,
                "results": live_result.get("results", []),
                "total_results": live_result.get("total_results", 0),
                "sources": ["live_web"],
                "live_results": live_result.get("total_results", 0),
                "search_params": live_result.get("search_params", {}),
            }

        except Exception as e:
            self.logger.error(f" Live search error: {str(e)}")
            return {
                "query": query,
                "results": [],
                "total_results": 0,
                "error": f"Live search failed: {str(e)}",
            }

    def _search_hybrid(

        self, query: str, max_results: int, search_options: Optional[Dict[str, Any]]

    ) -> Dict[str, Any]:
        """Perform hybrid search combining local and live sources."""
        self.logger.info(" Performing hybrid search")

        try:
            # πŸ“Š Calculate result distribution
            local_count = int(max_results * self.local_weight)
            live_count = max_results - local_count

            # πŸš€ Perform both searches concurrently (simplified sequential for now)
            local_result = self.local_processor.process_query(query)

            options = search_options or {}
            live_result = self.live_processor.search_web(
                query,
                max_results=live_count,
                search_depth=options.get("search_depth", "basic"),
                time_range=options.get("time_range", "month"),
            )

            # πŸ”„ Combine and rank results
            combined_results = self._fuse_results(
                local_result, live_result, local_count, live_count
            )

            return {
                "query": query,
                "results": combined_results[:max_results],
                "total_results": len(combined_results),
                "sources": ["local_documents", "live_web"],
                "local_results": local_result.get("total_results", 0),
                "live_results": live_result.get("total_results", 0),
                "fusion_method": "weighted_ranking",
            }

        except Exception as e:
            self.logger.error(f" Hybrid search error: {str(e)}")
            return self._search_fallback(query, max_results)

    def _fuse_results(

        self,

        local_result: Dict[str, Any],

        live_result: Dict[str, Any],

        local_count: int,

        live_count: int,

    ) -> List[Dict[str, Any]]:
        """

        Fuse results from local and live searches.



        Args:

            local_result: Results from local search

            live_result: Results from live search

            local_count: Number of local results to include

            live_count: Number of live results to include



        Returns:

            Fused and ranked results

        """
        fused_results = []

        # πŸ“š Process local results
        for item in local_result.get("context", [])[:local_count]:
            fused_results.append(
                {
                    "title": f"Document: {item.get('source', 'Unknown')}",
                    "content": item.get("text", ""),
                    "score": item.get("score", 0.0) * self.local_weight,
                    "source": item.get("source", "local_document"),
                    "type": "local_document",
                    "metadata": item.get("metadata", {}),
                    "fusion_score": item.get("score", 0.0) * self.local_weight,
                }
            )

        # 🌐 Process live results
        for item in live_result.get("results", [])[:live_count]:
            fused_results.append(
                {
                    "title": item.get("title", "Web Result"),
                    "content": item.get("content", ""),
                    "score": item.get("relevance_score", 0.0) * self.live_weight,
                    "source": item.get("url", "web_search"),
                    "type": "web_result",
                    "metadata": item.get("metadata", {}),
                    "fusion_score": item.get("relevance_score", 0.0) * self.live_weight,
                }
            )

        # πŸ”„ Sort by fusion score
        fused_results.sort(key=lambda x: x.get("fusion_score", 0), reverse=True)

        return fused_results

    def _search_fallback(self, query: str, max_results: int) -> Dict[str, Any]:
        """Fallback search method when other methods fail."""
        self.logger.warning(" Using fallback search method")

        try:
            # πŸ“š Try local search first
            local_result = self.local_processor.process_query(query)

            if local_result.get("context"):
                return self._search_local_only(query, max_results)
            else:
                return {
                    "query": query,
                    "results": [],
                    "total_results": 0,
                    "sources": [],
                    "error": "No results found in fallback search",
                }

        except Exception as e:
            self.logger.error(f" Fallback search failed: {str(e)}")
            return {
                "query": query,
                "results": [],
                "total_results": 0,
                "error": f"All search methods failed: {str(e)}",
            }

    def _track_routing_decision(

        self, query: str, query_type: QueryType, routing_decision: str

    ):
        """Track routing decisions for analytics."""
        self.routing_history.append(
            {
                "query": query[:100],  # Truncate for privacy
                "query_type": query_type.value,
                "routing_decision": routing_decision,
                "timestamp": datetime.now(),
            }
        )

        # πŸ“Š Keep only last 100 routing decisions
        if len(self.routing_history) > 100:
            self.routing_history = self.routing_history[-100:]

    def get_routing_analytics(self) -> Dict[str, Any]:
        """

        Get analytics about routing patterns.



        Returns:

            Dictionary with routing analytics

        """
        if not self.routing_history:
            return {
                "total_queries": 0,
                "routing_distribution": {},
                "query_type_distribution": {},
            }

        total_queries = len(self.routing_history)

        # πŸ“Š Calculate routing distribution
        routing_counts = {}
        query_type_counts = {}

        for entry in self.routing_history:
            routing = entry["routing_decision"]
            query_type = entry["query_type"]

            routing_counts[routing] = routing_counts.get(routing, 0) + 1
            query_type_counts[query_type] = query_type_counts.get(query_type, 0) + 1

        # πŸ“ˆ Convert to percentages
        routing_distribution = {
            k: round((v / total_queries) * 100, 1) for k, v in routing_counts.items()
        }

        query_type_distribution = {
            k: round((v / total_queries) * 100, 1) for k, v in query_type_counts.items()
        }

        return {
            "total_queries": total_queries,
            "routing_distribution": routing_distribution,
            "query_type_distribution": query_type_distribution,
            "recent_decisions": [
                {
                    "query": entry["query"][:50] + "...",
                    "type": entry["query_type"],
                    "routing": entry["routing_decision"],
                }
                for entry in self.routing_history[-5:]
            ],
        }

    def clear_cache(self):
        """Clear routing cache."""
        self.routing_cache.clear()
        self.logger.info(" Routing cache cleared")

    def clear_history(self):
        """Clear routing history."""
        self.routing_history.clear()
        self.logger.info(" Routing history cleared")