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
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
# DEPENDENCIES
import re
from typing import List
from typing import Dict
from typing import Tuple 
from typing import Optional
from collections import defaultdict
from config.models import DocumentChunk
from config.models import ChunkWithScore
from config.logging_config import get_logger
from utils.error_handler import CitationError
from utils.error_handler import handle_errors


# Setup Logging
logger = get_logger(__name__)


class CitationTracker:
    """
    Citation tracking and management: Tracks source citations in generated text and provides citation formatting and validation
    """
    def __init__(self):
        """
        Initialize citation tracker
        """
        self.logger           = logger
        self.citation_pattern = re.compile(r'\[(\d+)\]')
    

    def extract_citations(self, text: str) -> List[int]:
        """
        Extract citation numbers from text
        
        Arguments:
        ----------
            text { str } : Text containing citations
        
        Returns:
        --------
             { list }    : List of citation numbers found in text
        """
        if not text:
            return []
        
        try:
            matches          = self.citation_pattern.findall(text)
            citation_numbers = [int(match) for match in matches]
            
            # Remove duplicates and sort
            unique_citations = sorted(set(citation_numbers))
            
            self.logger.debug(f"Extracted {len(unique_citations)} citations from text")
            
            return unique_citations
        
        except Exception as e:
            self.logger.error(f"Citation extraction failed: {repr(e)}")
            return []
    

    def validate_citations(self, text: str, sources: List[ChunkWithScore]) -> Tuple[bool, List[int]]:
        """
        Validate that all citations in text reference existing sources
        
        Arguments:
        ----------
            text    { str }  : Text containing citations
            
            sources { list } : List of available sources
        
        Returns:
        --------
              { Tuple[bool, List[int]] } : (is_valid, invalid_citations)
        """
        citation_numbers = self.extract_citations(text = text)
        
        if not citation_numbers:
            return True, []
        
        # Check if all citation numbers are within valid range
        max_valid         = len(sources)
        invalid_citations = [num for num in citation_numbers if (num < 1) or (num > max_valid)]
        
        if invalid_citations:
            self.logger.warning(f"Invalid citations found: {invalid_citations}. Valid range: 1-{max_valid}")
            return False, invalid_citations
        
        return True, []
    

    def format_citations(self, sources: List[ChunkWithScore], style: str = "numeric") -> str:
        """
        Format citations as reference list
        
        Arguments:
        ----------
            sources { list } : List of sources to format
            
            style   { str }  : Citation style ('numeric', 'verbose')
        
        Returns:
        --------
               { str }       : Formatted citation text
        """
        if not sources:
            return ""
        
        try:
            citations = list()

            for i, source in enumerate(sources, 1):
                if (style == "verbose"):
                    citation = self._format_verbose_citation(source = source, 
                                                             number = i,
                                                            )
                
                else:
                    citation = self._format_numeric_citation(source = source, 
                                                             number = i,
                                                            )
                
                citations.append(citation)
            
            citation_text = "\n".join(citations)
            
            self.logger.debug(f"Formatted {len(citations)} citations in {style} style")
            
            return citation_text
        
        except Exception as e:
            self.logger.error(f"Citation formatting failed: {repr(e)}")
            return ""
    

    def _format_numeric_citation(self, source: ChunkWithScore, number: int) -> str:
        """
        Format citation in numeric style with sanitization
        
        Arguments:
        ----------
            source { ChunkWithScore } : Source to format

            number      { int }       : Citation number
        
        Returns:
        --------
                { str }              : Formatted citation
        """
        chunk = source.chunk
        
        parts = [f"[{number}]"]
        
        # Add source information with proper sanitization
        if (hasattr(chunk, 'metadata') and chunk.metadata):
            if ('filename' in chunk.metadata):
                # Sanitize filename more thoroughly
                filename = str(chunk.metadata['filename'])
                
                # Remove problematic characters that could break citation parsing: Keep only alphanumeric, spaces, dots, hyphens, underscores
                filename = re.sub(r'[^\w\s\.\-]', '_', filename)
                
                # Limit length to prevent overflow
                if (len(filename) > 50):
                    filename = filename[:47] + "..."
                
                parts.append(f"Source: {filename}")
        
        if chunk.page_number:
            parts.append(f"Page {chunk.page_number}")
        
        if chunk.section_title:
            # Sanitize section title similarly
            section = str(chunk.section_title)
            section = re.sub(r'[^\w\s\.\-]', '_', section)
            
            if (len(section) > 40):
                section = section[:37] + "..."
            
            parts.append(f"Section: {section}")
        
        # Add relevance score if available
        if (source.score > 0):
            parts.append(f"(Relevance: {source.score:.2f})")
        
        return " ".join(parts)
    

    def _format_verbose_citation(self, source: ChunkWithScore, number: int) -> str:
        """
        Format citation in verbose style - SAFER VERSION
        
        Arguments:
        ----------
            source { ChunkWithScore } : Source to format

            number     { int }        : Citation number
        
        Returns:
        --------
                { str }              : Formatted citation
        """
        chunk = source.chunk
        
        parts = [f"Citation {number}:"]
        
        # Document information with sanitization
        if (hasattr(chunk, 'metadata')):
            meta = chunk.metadata
            
            if ('filename' in meta):
                filename = str(meta['filename'])
                filename = re.sub(r'[^\w\s\.\-]', '_', filename)
                
                if (len(filename) > 50):
                    filename = filename[:47] + "..."

                parts.append(f"Document: {filename}")
            
            if ('title' in meta):
                title = str(meta['title'])
                title = re.sub(r'[^\w\s\.\-]', '_', title)
                
                if (len(title) > 60):
                    title = title[:57] + "..."
                
                parts.append(f"Title: {title}")
            
            if ('author' in meta):
                author = str(meta['author'])
                author = re.sub(r'[^\w\s\.\-]', '_', author)
                
                if (len(author) > 40):
                    author = author[:37] + "..."
                    
                parts.append(f"Author: {author}")
        
        # Location information
        location_parts = list()
        
        if chunk.page_number:
            location_parts.append(f"page {chunk.page_number}")
        
        if chunk.section_title:
            section = str(chunk.section_title)
            section = re.sub(r'[^\w\s\.\-]', '_', section)
            
            if (len(section) > 40):
                section = section[:37] + "..."
            
            location_parts.append(f"section '{section}'")
        
        if location_parts:
            parts.append("(" + ", ".join(location_parts) + ")")
        
        # Relevance information
        if (source.score > 0):
            parts.append(f"[Relevance score: {source.score:.3f}]")
        
        return " ".join(parts)
    

    def generate_citation_map(self, sources: List[ChunkWithScore]) -> Dict[int, Dict]:
        """
        Generate mapping from citation numbers to source details
        
        Arguments:
        ----------
            sources { list } : List of sources
        
        Returns:
        --------
               { dict }      : Dictionary mapping citation numbers to source details
        """
        citation_map = dict()

        for i, source in enumerate(sources, 1):
            chunk           = source.chunk
            
            citation_map[i] = {'chunk_id'      : chunk.chunk_id,
                               'document_id'   : chunk.document_id,
                               'score'         : source.score,
                               'text_preview'  : chunk.text[:200] + "..." if (len(chunk.text) > 200) else chunk.text,
                               'metadata'      : getattr(chunk, 'metadata', {}),
                               'page_number'   : chunk.page_number,
                               'section_title' : chunk.section_title,
                              }
        
        return citation_map
    

    def replace_citation_markers(self, text: str, citation_map: Dict[int, str]) -> str:
        """
        Replace citation markers with formatted citations - FIXED
        
        Arguments:
        ----------
            text         { str }  : Text containing citation markers
            
            citation_map { dict } : Mapping of citation numbers to formatted strings
        
        Returns:
        --------
                  { str }         : Text with replaced citations
        """
        def replacement(match):
            try:
                citation_num     = int(match.group(1))
                
                # Get replacement text and sanitize it
                replacement_text = citation_map.get(citation_num, match.group(0))
                
                return str(replacement_text)
            
            except (ValueError, IndexError):
                # Return original match if parsing fails
                return match.group(0)
        
        try:
            return self.citation_pattern.sub(replacement, text)
        
        except Exception as e:
            self.logger.error(f"Citation replacement failed: {repr(e)}")
            # Return original text on error
            return text  
    

    def get_citation_statistics(self, text: str, sources: List[ChunkWithScore]) -> Dict:
        """
        Get statistics about citations in text
        
        Arguments:
        ----------
            text    { str }  : Text containing citations
            
            sources { list } : List of sources
        
        Returns:
        --------
              { dict }       : Citation statistics
        """
        citation_numbers = self.extract_citations(text = text)
        
        if not citation_numbers:
            return {"total_citations": 0}
        
        # Calculate citation distribution
        citation_counts = defaultdict(int)

        for num in citation_numbers:
            if 1 <= num <= len(sources):
                source = sources[num - 1]
                doc_id = source.chunk.document_id
                citation_counts[doc_id] += 1
        
        return {"total_citations"      : len(citation_numbers),
                "unique_citations"     : len(set(citation_numbers)),
                "citation_distribution": dict(citation_counts),
                "citations_per_source" : {i: citation_numbers.count(i) for i in set(citation_numbers)},
               }
    

    def ensure_citation_consistency(self, text: str, sources: List[ChunkWithScore]) -> str:
        """
        Ensure citation numbers are consistent and sequential
        
        Arguments:
        ----------
            text    { str }  : Text containing citations
            
            sources { list } : List of sources
        
        Returns:
        --------
              { str }        : Text with consistent citations
        """
        is_valid, invalid_citations = self.validate_citations(text, sources)
        
        if not is_valid:
            self.logger.warning("Invalid citations found, attempting to fix consistency")
            
            # Extract current citations and create mapping
            current_citations = self.extract_citations(text = text)
            
            if not current_citations:
                return text
            
            # Create mapping from old to new citation numbers
            citation_mapping = dict()
            
            for i, old_num in enumerate(sorted(set(current_citations)), 1):
                if (old_num <= len(sources)):
                    citation_mapping[old_num] = i
            
            # Replace citations in text
            def consistent_replacement(match):
                old_num = int(match.group(1))
                new_num = citation_mapping.get(old_num, old_num)
                
                return f"[{new_num}]"
            
            fixed_text = self.citation_pattern.sub(consistent_replacement, text)
            
            self.logger.info(f"Fixed citation consistency: {current_citations} -> {list(citation_mapping.values())}")
            
            return fixed_text
        
        return text


# Global citation tracker instance
_citation_tracker = None


def get_citation_tracker() -> CitationTracker:
    """
    Get global citation tracker instance (singleton)
    
    Returns:
    --------
        { CitationTracker }    : CitationTracker instance
    """
    global _citation_tracker
    
    if _citation_tracker is None:
        _citation_tracker = CitationTracker()
    
    return _citation_tracker


@handle_errors(error_type = CitationError, log_error = True, reraise = False)
def extract_and_validate_citations(text: str, sources: List[ChunkWithScore]) -> Tuple[List[int], bool]:
    """
    Convenience function for citation extraction and validation
    
    Arguments:
    ----------
        text    { str }  : Text containing citations
        
        sources { list } : List of sources
    
    Returns:
    --------
             { Tuple[List[int], bool] } : (citation_numbers, is_valid)
    """
    tracker   = get_citation_tracker()
    citations = tracker.extract_citations(text = text)
    is_valid, _ = tracker.validate_citations(text    = text, 
                                             sources = sources,
                                            )
    
    return citations, is_valid