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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
import faiss
import numpy as np
import sys
from pathlib import Path
from typing import Dict, List, Optional

# Use local components instead of external shared_utils
from src.core.platform_orchestrator import PlatformOrchestrator
from src.core.interfaces import Document


class BasicRAG:
    """Basic RAG system combining PDF processing, chunking, and embedding search."""

    def __init__(self):
        """
        Initialize BasicRAG with platform orchestrator.

        Recommended Usage:
        - For production: Use hybrid_query() method (best performance + quality)
        - For research: enhanced_hybrid_query() available but not recommended
        """
        self.orchestrator = PlatformOrchestrator("config/default.yaml")
        self.index = None
        self.chunks = []  # Store chunk text and metadata
        self.embedding_dim = 384  # multi-qa-MiniLM-L6-cos-v1 dimension
        self.hybrid_retriever: Optional[HybridRetriever] = None
        self.vocabulary_index: Optional[VocabularyIndex] = None

    def index_document(self, pdf_path: Path) -> int:
        """
        Process PDF into chunks, generate embeddings, and add to FAISS index.

        Args:
            pdf_path: Path to PDF file

        Returns:
            Number of chunks indexed
        """
        # Extract text from PDF with metadata
        text_data = extract_text_with_metadata(pdf_path)

        # Chunk the text using hybrid TOC + PDFPlumber approach
        chunks = parse_pdf_with_hybrid_approach(
            pdf_path,
            text_data,
            target_chunk_size=1400,
            min_chunk_size=800,
            max_chunk_size=2000,
        )

        # Generate embeddings
        chunk_texts = [chunk["text"] for chunk in chunks]
        embeddings = generate_embeddings(chunk_texts)

        # Initialize FAISS index if first document
        if self.index is None:
            self.index = faiss.IndexFlatIP(
                self.embedding_dim
            )  # Inner product for similarity

        # Add embeddings to FAISS index
        # Normalize embeddings for cosine similarity
        normalized_embeddings = embeddings / np.linalg.norm(
            embeddings, axis=1, keepdims=True
        )
        self.index.add(normalized_embeddings.astype(np.float32))

        # Store chunks with enhanced metadata from structure-preserving parser
        for i, chunk in enumerate(chunks):
            chunk_info = {
                "text": chunk["text"],
                "source": str(pdf_path),
                "page": chunk.get("page", 0),
                "chunk_id": len(self.chunks) + i,
                "start_char": chunk.get("start_char", 0),
                "end_char": chunk.get("end_char", len(chunk["text"])),
                # Structure-preserving metadata
                "title": chunk.get("title", ""),
                "parent_title": chunk.get("parent_title", ""),
                "context": chunk.get("context", ""),
                "level": chunk.get("level", 0),
                "quality_score": chunk.get("metadata", {}).get("quality_score", 0.0),
                "parsing_method": "structure_preserving",
            }
            self.chunks.append(chunk_info)

        # Initialize hybrid retriever and index chunks
        if self.hybrid_retriever is None:
            self.hybrid_retriever = HybridRetriever()

        # Re-index all chunks for hybrid search
        self.hybrid_retriever.index_documents(self.chunks)

        # Build or update vocabulary index
        if self.vocabulary_index is None:
            self.vocabulary_index = VocabularyIndex()

        # Build vocabulary from all chunks
        print("Building vocabulary index...")
        self.vocabulary_index.build_from_chunks(self.chunks)

        # Print vocabulary statistics
        stats = self.vocabulary_index.get_vocabulary_stats()
        print(
            f"Vocabulary stats: {stats['unique_terms']} unique terms, "
            f"{stats['technical_terms']} technical terms"
        )

        return len(chunks)

    def index_documents(self, pdf_folder: Path) -> Dict[str, int]:
        """
        Process multiple PDF documents from a folder into the unified index.

        Args:
            pdf_folder: Path to folder containing PDF files

        Returns:
            Dict mapping document names to number of chunks indexed

        Raises:
            ValueError: If folder doesn't exist or no PDFs found
        """
        if not pdf_folder.exists() or not pdf_folder.is_dir():
            raise ValueError(f"PDF folder not found: {pdf_folder}")

        pdf_files = list(pdf_folder.glob("*.pdf"))
        if not pdf_files:
            raise ValueError(f"No PDF files found in {pdf_folder}")

        results = {}
        total_chunks = 0

        print(f"Processing {len(pdf_files)} PDF documents...")

        for pdf_file in pdf_files:
            print(f"\nProcessing: {pdf_file.name}")
            try:
                chunk_count = self.index_document(pdf_file)
                results[pdf_file.name] = chunk_count
                total_chunks += chunk_count
                print(f"  βœ… Indexed {chunk_count} chunks")
            except Exception as e:
                print(f"  ❌ Failed to process {pdf_file.name}: {e}")
                results[pdf_file.name] = 0

        print(f"\nπŸ“Š Multi-document indexing complete:")
        print(
            f"   - {len([r for r in results.values() if r > 0])}/{len(pdf_files)} documents processed successfully"
        )
        print(f"   - {total_chunks} total chunks indexed")
        print(
            f"   - {len(set(chunk['source'] for chunk in self.chunks))} unique sources"
        )

        return results

    def query(self, question: str, top_k: int = 5) -> Dict:
        """
        Search for relevant chunks and return results.

        Args:
            question: User question
            top_k: Number of top results to return

        Returns:
            Dict with question, relevant chunks, and sources
        """
        if self.index is None or len(self.chunks) == 0:
            return {"question": question, "chunks": [], "sources": []}

        # Generate embedding for question
        question_embedding = generate_embeddings([question])
        normalized_question = question_embedding / np.linalg.norm(
            question_embedding, axis=1, keepdims=True
        )

        # Search FAISS index
        scores, indices = self.index.search(
            normalized_question.astype(np.float32), top_k
        )

        # Retrieve relevant chunks
        relevant_chunks = []
        sources = set()

        for score, idx in zip(scores[0], indices[0]):
            if idx < len(self.chunks):  # Valid index
                chunk = self.chunks[idx].copy()
                chunk["similarity_score"] = float(score)
                relevant_chunks.append(chunk)
                sources.add(chunk["source"])

        return {
            "question": question,
            "chunks": relevant_chunks,
            "sources": list(sources),
        }

    def hybrid_query(
        self, question: str, top_k: int = 5, dense_weight: float = 0.7
    ) -> Dict:
        """
        Enhanced query using hybrid dense + sparse retrieval.

        Combines semantic similarity (embeddings) with keyword matching (BM25)
        using Reciprocal Rank Fusion for optimal relevance ranking.

        Args:
            question: User query
            top_k: Number of results to return
            dense_weight: Weight for dense retrieval (0.7 = 70% semantic, 30% keyword)

        Returns:
            Enhanced results with hybrid_score field and retrieval method indicators

        Raises:
            ValueError: If hybrid retriever not initialized
        """
        if self.hybrid_retriever is None or len(self.chunks) == 0:
            return {
                "question": question,
                "chunks": [],
                "sources": [],
                "retrieval_method": "none",
            }

        # Perform hybrid search
        try:
            # Update hybrid retriever weight if different
            if abs(self.hybrid_retriever.dense_weight - dense_weight) > 0.01:
                self.hybrid_retriever.dense_weight = dense_weight

            hybrid_results = self.hybrid_retriever.search(question, top_k)

            # Process results for consistency with basic query format
            relevant_chunks = []
            sources = set()

            for chunk_idx, rrf_score, chunk_dict in hybrid_results:
                # Add hybrid-specific metadata
                enhanced_chunk = chunk_dict.copy()
                enhanced_chunk["hybrid_score"] = float(rrf_score)
                enhanced_chunk["retrieval_method"] = "hybrid"

                relevant_chunks.append(enhanced_chunk)
                sources.add(enhanced_chunk["source"])

            # Get retrieval statistics for transparency
            stats = self.hybrid_retriever.get_retrieval_stats()

            return {
                "question": question,
                "chunks": relevant_chunks,
                "sources": list(sources),
                "retrieval_method": "hybrid",
                "dense_weight": dense_weight,
                "sparse_weight": 1.0 - dense_weight,
                "stats": stats,
            }

        except Exception as e:
            # Fallback to basic semantic search on hybrid failure
            print(f"Hybrid search failed: {e}")
            print("Falling back to basic semantic search...")

            basic_result = self.query(question, top_k)
            basic_result["retrieval_method"] = "fallback_semantic"
            basic_result["error"] = str(e)

            return basic_result

    def enhanced_hybrid_query(
        self, question: str, top_k: int = 5, enable_enhancement: bool = False
    ) -> Dict:
        """
        Hybrid query with optional enhancement (DISABLED BY DEFAULT).

        Based on comprehensive evaluation, query enhancement does not provide
        meaningful improvements and adds computational overhead. Enhancement
        is disabled by default and standard hybrid search is recommended.

        Evaluation Results:
        - Enhancement shows no statistical significance (p=0.374)
        - 1.7x slower than standard hybrid search
        - Lower quality scores than baseline methods

        Args:
            question: User query string
            top_k: Number of results to return
            enable_enhancement: Enable query enhancement (NOT RECOMMENDED)

        Returns:
            Hybrid search results with optional enhancement metadata

        Recommendation: Use hybrid_query() directly for better performance
        """
        if not question or not question.strip():
            return {
                "question": question,
                "chunks": [],
                "sources": [],
                "retrieval_method": "none",
                "enhancement_applied": False,
            }

        # Check if enhancement is enabled (DISABLED BY DEFAULT)
        if not enable_enhancement:
            # Use standard hybrid search (RECOMMENDED)
            hybrid_result = self.hybrid_query(question, top_k)
            hybrid_result.update(
                {
                    "original_query": question,
                    "enhancement_applied": False,
                    "enhancement_disabled": True,
                    "retrieval_method": "hybrid_recommended",
                    "note": "Enhancement disabled based on evaluation - use hybrid_query() directly",
                }
            )
            return hybrid_result

        try:
            # Enhancement enabled (NOT RECOMMENDED - adds overhead without benefit)
            from shared_utils.query_processing.query_enhancer import QueryEnhancer

            # Initialize enhancer
            enhancer = QueryEnhancer()

            # Step 1: Get baseline semantic results for quality comparison
            baseline_result = self.query(question, top_k)
            baseline_score = 0.0
            if baseline_result.get("chunks"):
                baseline_score = baseline_result["chunks"][0].get(
                    "similarity_score", 0.0
                )

            # Step 2: Perform vocabulary-aware enhancement if available
            if self.vocabulary_index is not None:
                enhancement_result = enhancer.enhance_query_with_vocabulary(
                    question, vocabulary_index=self.vocabulary_index, min_frequency=3
                )
            else:
                # Fallback to conservative enhancement
                enhancement_result = enhancer.enhance_query(question, conservative=True)

            enhanced_query = enhancement_result["enhanced_query"]
            optimal_weight = enhancement_result["optimal_weight"]
            analysis = enhancement_result["analysis"]
            metadata = enhancement_result["enhancement_metadata"]

            # Step 3: Quality check - only enhance if expansion is minimal
            expansion_ratio = metadata.get("expansion_ratio", 1.0)
            should_enhance = (
                expansion_ratio <= 2.0  # Limit expansion bloat
                and analysis.get("technical_term_count", 0) > 0  # Has technical content
            )

            if should_enhance:
                # Execute hybrid search with enhanced query
                hybrid_result = self.hybrid_query(enhanced_query, top_k, optimal_weight)

                # Enhance result with query enhancement metadata
                hybrid_result.update(
                    {
                        "original_query": question,
                        "enhanced_query": enhanced_query,
                        "adaptive_weight": optimal_weight,
                        "query_analysis": analysis,
                        "enhancement_metadata": metadata,
                        "enhancement_applied": True,
                        "retrieval_method": "enhanced_hybrid",
                        "baseline_score": baseline_score,
                        "quality_validated": True,
                        "warning": "Enhancement enabled despite evaluation showing no benefit",
                    }
                )

                return hybrid_result
            else:
                # Enhancement not beneficial - use standard hybrid
                hybrid_result = self.hybrid_query(question, top_k)
                hybrid_result.update(
                    {
                        "original_query": question,
                        "enhancement_applied": False,
                        "fallback_reason": f"Enhancement not beneficial (expansion: {expansion_ratio:.1f}x)",
                        "baseline_score": baseline_score,
                        "quality_validated": True,
                    }
                )
                return hybrid_result

        except ImportError:
            # QueryEnhancer not available - fallback to basic hybrid
            print("QueryEnhancer not available, falling back to standard hybrid search")
            result = self.hybrid_query(question, top_k)
            result["enhancement_applied"] = False
            result["fallback_reason"] = "QueryEnhancer import failed"
            return result

        except Exception as e:
            # Enhancement failed - fallback to basic hybrid
            print(f"Query enhancement failed: {e}")
            print("Falling back to standard hybrid search...")

            try:
                result = self.hybrid_query(question, top_k)
                result.update(
                    {
                        "original_query": question,
                        "enhancement_applied": False,
                        "enhancement_error": str(e),
                        "fallback_reason": "Enhancement processing failed",
                    }
                )
                return result
            except Exception as hybrid_error:
                # Both enhancement and hybrid failed - fallback to semantic
                print(f"Hybrid search also failed: {hybrid_error}")
                print("Falling back to basic semantic search...")

                semantic_result = self.query(question, top_k)
                semantic_result.update(
                    {
                        "original_query": question,
                        "retrieval_method": "fallback_semantic",
                        "enhancement_applied": False,
                        "enhancement_error": str(e),
                        "hybrid_error": str(hybrid_error),
                        "fallback_reason": "Both enhancement and hybrid failed",
                    }
                )
                return semantic_result