File size: 37,302 Bytes
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
b30f068
9e42edc
 
b30f068
 
 
 
9e42edc
 
 
 
 
 
 
 
 
 
 
b30f068
 
 
 
9e42edc
 
 
 
 
b30f068
 
745bce3
 
 
9e42edc
 
 
 
745bce3
9e42edc
 
 
 
 
b30f068
 
 
9e42edc
 
 
 
 
 
 
 
 
 
745bce3
 
 
 
 
5c47a28
 
 
 
745bce3
 
5c47a28
9e42edc
745bce3
9e42edc
 
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
 
b30f068
 
9e42edc
 
 
b30f068
 
 
 
9e42edc
 
 
 
b30f068
 
 
 
 
 
 
 
9e42edc
b30f068
9e42edc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b30f068
 
 
 
 
 
 
9e42edc
 
b30f068
 
9e42edc
 
 
 
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
b30f068
9e42edc
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
b30f068
9e42edc
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
b30f068
 
 
 
 
 
9e42edc
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
b30f068
 
 
 
 
 
 
9e42edc
b30f068
 
 
 
 
 
 
9e42edc
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745bce3
b30f068
 
745bce3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b30f068
 
 
 
 
 
 
 
 
9e42edc
 
745bce3
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e42edc
b30f068
 
 
9e42edc
 
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
"""
CDMS Label Search Tool
Search for pesticide product labels from the CDMS database with full citations
"""

import os
from typing import Dict, Any, Optional
from pathlib import Path
import sys

# Add project root to path
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from src.cdms.rag_search import CDMSRAGSearch


def _offline_index_enabled() -> bool:
    """Legacy env flag, retained as a hallucination guard elsewhere.

    Still read by llm_response_generator to refuse ungrounded Tavily-only
    summaries. It no longer gates retrieval mode here — see _live_fallback_enabled.
    """
    return os.environ.get("CDMS_OFFLINE_INDEX", "1") == "1"


def _live_fallback_enabled() -> bool:
    """Auto-mode: on an index miss, live-fetch the label and cache it for the session.

    On (default) the tool serves from the committed index when the label is present
    and only reaches out to CDMS (Tavily + download + re-embed) when it isn't —
    caching the result in-process so repeat asks are fast. Set CDMS_LIVE_FALLBACK=0
    to force index-only (e.g. a keyless deploy or to cap live-fetch cost).
    """
    return os.environ.get("CDMS_LIVE_FALLBACK", "1") == "1"


class CDMSLabelTool:
    """
    Tool for searching CDMS pesticide labels

    Auto-mode (default): serve from the committed Qdrant index when the label is
    already indexed; otherwise fetch it live via Tavily (cdms.net domain filter),
    download + index it, and answer — caching it in the running process so later
    asks for the same label are fast. With no Tavily key (or CDMS_LIVE_FALLBACK=0)
    it degrades to index-only and abstains for un-indexed products.
    """

    def __init__(self, offline: bool = None):
        """Initialize the CDMS label search tool.

        offline: None -> auto-mode (index first, live-fetch on miss when a Tavily
        key is available; see _live_fallback_enabled). True -> force index-only
        (never live-fetch). False -> allow live fallback. Retained for callers/tests
        that still pass it explicitly.
        """
        # force_index_only: never reach out to CDMS, answer only from the index.
        if offline is None:
            self.force_index_only = not _live_fallback_enabled()
        else:
            self.force_index_only = bool(offline)
        self.tool_name = "cdms_label_search"
        self.description = "Search for pesticide product labels and safety data sheets from the CDMS database"

        # The index searcher is always available (offline or not).
        self.rag_search = CDMSRAGSearch()
        self.client = None
        self.pdf_downloader = None
        self.document_loader = None
        # live_available gates the fetch-on-miss path. Building the Tavily stack
        # needs a key; if it's absent (or the import fails), we simply stay
        # index-only and abstain on a miss rather than crashing the request.
        self.live_available = False
        if not self.force_index_only:
            try:
                from src.api_clients.tavily_client import TavilyAPIClient
                from src.cdms.pdf_downloader import CDMSPDFDownloader
                from src.cdms.document_loader import DocumentLoader
                from src.config.paths import PDF_DIR
                # Both the searcher and the loader default to the process-wide
                # shared vector store (get_shared_vector_store), so search AND
                # indexing use the SAME single embedded-Qdrant client — no second
                # client to lock-fail, and safe across concurrent requests.
                self.client = TavilyAPIClient()
                self.pdf_downloader = CDMSPDFDownloader()
                self.document_loader = DocumentLoader(pdf_folder=str(PDF_DIR))
                self.live_available = True
            except Exception as e:
                print(f"⚠️  Live fetch unavailable ({e}); serving from the offline index only.")
                self.live_available = False
    
    def search(
        self,
        product_name: str,
        active_ingredient: Optional[str] = None,
        max_results: int = 5
    ) -> Dict[str, Any]:
        """
        Search for CDMS pesticide labels
        
        Args:
            product_name: Product or brand name (e.g., "Roundup", "Sevin")
            active_ingredient: Optional active ingredient (e.g., "glyphosate")
            max_results: Maximum number of label results to return (1-5)
        
        Returns:
            Dict with:
                - success: bool
                - product_name: str
                - active_ingredient: str or None
                - summary: str (AI-generated summary)
                - labels: List[Dict] with:
                    - title: str (label name)
                    - url: str (direct PDF link)
                    - snippet: str (preview text)
                    - relevance: float (0-1)
                - label_count: int
                - citations: str (formatted citation text)
        """
        # Perform search via Tavily client
        raw_results = self.client.search_cdms_labels(
            product_name=product_name,
            active_ingredient=active_ingredient,
            max_results=max_results
        )
        
        if not raw_results.get("success"):
            return {
                "success": False,
                "error": raw_results.get("error", "Search failed"),
                "product_name": product_name,
                "labels": [],
                "label_count": 0
            }
        
        # Format results with full citation info
        labels = []
        for result in raw_results.get("results", []):
            label = {
                "title": result.get("title", "No title"),
                "url": result.get("url", ""),
                "snippet": result.get("content", "")[:300],  # First 300 chars
                "relevance": result.get("score", 0.0)
            }
            labels.append(label)
        
        # Generate formatted citations
        citations = self._format_citations(labels)
        
        # Build response
        return {
            "success": True,
            "product_name": product_name,
            "active_ingredient": active_ingredient,
            "summary": raw_results.get("answer", ""),
            "labels": labels,
            "label_count": len(labels),
            "citations": citations,
            "query_used": raw_results.get("query", ""),
            "search_metadata": raw_results.get("search_metadata", {}),
            "raw_tavily_results": raw_results  # Keep for PDF extraction
        }
    
    def _format_citations(self, labels: list) -> str:
        """
        Format label results as citation text
        
        Args:
            labels: List of label results
        
        Returns:
            Formatted citation string
        """
        if not labels:
            return "No citations available."
        
        citation_parts = ["**Sources:**\n"]
        
        for i, label in enumerate(labels, 1):
            citation_parts.append(
                f"{i}. **{label['title']}**\n"
                f"   - URL: {label['url']}\n"
                f"   - Relevance: {label['relevance']:.2f}\n"
            )
        
        return "\n".join(citation_parts)
    
    def format_response_for_user(self, result: Dict[str, Any]) -> str:
        """
        Format search results for user-friendly display
        
        Args:
            result: Search result from search()
        
        Returns:
            Formatted string for display to user
        """
        if not result.get("success"):
            return f"❌ Could not find labels: {result.get('error', 'Unknown error')}"
        
        product = result.get("product_name", "Unknown product")
        ingredient = result.get("active_ingredient")
        summary = result.get("summary", "")
        labels = result.get("labels", [])
        
        # Build response
        response_parts = []
        
        # Header
        if ingredient:
            response_parts.append(f"**CDMS Labels for {product} ({ingredient})**\n")
        else:
            response_parts.append(f"**CDMS Labels for {product}**\n")
        
        # Summary
        if summary:
            response_parts.append(f"**Summary:** {summary}\n")
        
        # Labels found
        response_parts.append(f"**Found {len(labels)} label(s):**\n")
        
        for i, label in enumerate(labels, 1):
            response_parts.append(
                f"{i}. **{label['title']}**\n"
                f"   📄 Download: {label['url']}\n"
                f"   📝 Preview: {label['snippet'][:150]}...\n"
            )
        
        # Citations
        response_parts.append(f"\n{result.get('citations', '')}")
        
        return "\n".join(response_parts)
    
    def download_pdfs(self, tavily_results: Dict[str, Any], product_name: str) -> Dict[str, Any]:
        """
        Download PDFs from Tavily search results
        
        Args:
            tavily_results: Results from search() method (includes raw_tavily_results)
            product_name: Product name for filename
        
        Returns:
            Dict with:
                - success: bool
                - downloaded_pdfs: List[Dict] with filepath, filename, cached status
                - pdf_count: int
                - errors: List[str] (any download errors)
        """
        # Extract PDF URLs from Tavily results
        raw_results = tavily_results.get("raw_tavily_results", tavily_results)
        pdf_urls = self.pdf_downloader.extract_pdf_urls(raw_results)
        
        if not pdf_urls:
            print(f"⚠️  No PDF URLs found in Tavily results for {product_name}")
            # Also check labels directly
            labels = tavily_results.get("labels", [])
            for label in labels:
                url = label.get("url", "")
                if url and (url.lower().endswith('.pdf') or 'pdf' in url.lower()):
                    pdf_urls.append(url)
                    print(f"   Found PDF URL in labels: {url}")
            
            if not pdf_urls:
                return {
                    "success": False,
                    "error": "No PDF URLs found in search results",
                    "downloaded_pdfs": [],
                    "pdf_count": 0
                }
        
        print(f"📥 Found {len(pdf_urls)} PDF URL(s) to download for {product_name}")
        
        # Download top 3 PDFs
        downloaded_pdfs = []
        errors = []
        
        for i, url in enumerate(pdf_urls[:3], 1):  # Top 3
            print(f"   Downloading PDF {i}/{min(len(pdf_urls), 3)}: {url[:60]}...")
            result = self.pdf_downloader.download_pdf(url, product_name)
            if result.get("success"):
                cached_status = "cached" if result.get("cached") else "downloaded"
                print(f"   ✅ {cached_status}: {result.get('filename')}")
                downloaded_pdfs.append({
                    "filepath": result["filepath"],
                    "filename": result["filename"],
                    "cached": result["cached"],
                    "url": result["url"],
                    "url_hash": result["url_hash"]
                })
            else:
                error_msg = result.get('error', 'Unknown error')
                print(f"   ❌ Failed: {error_msg}")
                errors.append(f"Failed to download {url}: {error_msg}")
        
        if downloaded_pdfs:
            print(f"✅ Successfully downloaded {len(downloaded_pdfs)} PDF(s)")
        else:
            print("❌ No PDFs were downloaded")
        
        return {
            "success": len(downloaded_pdfs) > 0,
            "downloaded_pdfs": downloaded_pdfs,
            "pdf_count": len(downloaded_pdfs),
            "errors": errors if errors else None
        }
    
    def _is_pdf_indexed(self, pdf_path: str) -> bool:
        """
        Check if PDF is already indexed in Qdrant
        
        Args:
            pdf_path: Path to PDF file
            
        Returns:
            True if PDF is indexed, False otherwise
        """
        try:
            from src.cdms.schema import Document, DatabaseManager
            db_manager = DatabaseManager()
            session = db_manager.get_session()
            
            try:
                pdf_path_obj = Path(pdf_path)
                doc_id = Document.generate_id(str(pdf_path_obj))
                existing_doc = session.query(Document).filter_by(id=doc_id).first()
                
                if existing_doc and existing_doc.processed == 1:
                    return True
                return False
            finally:
                session.close()
        except Exception:
            return False
    
    def search_with_rag(
        self,
        product_name: str,
        user_question: str,
        active_ingredient: Optional[str] = None,
        on_step=None,
    ) -> Dict[str, Any]:
        """
        Auto-mode RAG pipeline: index-first, live-fetch (Tavily → Download →
        Process → Index → RAG Search) only on an index miss, then cache.

        Args:
            product_name: Product name (e.g., "Roundup")
            user_question: User's question (e.g., "What's the application rate?")
            active_ingredient: Optional active ingredient
            on_step: Optional callback(str) invoked at each stage, so the UI can
                surface the live pipeline (and show that a first-time label fetch
                is what's taking the extra time).

        Returns:
            Dict with:
                - success: bool
                - product_name: str
                - rag_chunks: List[Dict] with content, page_number, score
                - pdfs_downloaded: int
                - pdfs_indexed: int
                - total_chunks_found: int
                - source: "index" | "live" (where the answer came from)
        """
        def _step(msg: str) -> None:
            if on_step:
                try:
                    on_step(msg)
                except Exception:
                    pass  # never let step reporting break the pipeline

        # Step A: try the committed/local index first (fast path). Chunks already
        # carry pdf_url from the payload for a real Sources link.
        _step(f"Searching indexed labels for “{product_name}”…")
        rag_chunks = self.rag_search.search(
            query=user_question,
            product_name=product_name,
            limit=5,
            score_threshold=0.4
        )

        # Served from the index, OR nothing to fall back to (no live stack /
        # forced index-only) — return the index result (which may abstain).
        if rag_chunks or not self.live_available:
            if rag_chunks:
                _step("Found matching label pages in the index.")
            elif self.force_index_only:
                _step("Label not in the index (index-only mode).")
            else:
                _step("Label not in the index and live fetch is unavailable.")
            return {
                "success": True,
                "product_name": product_name,
                "rag_chunks": rag_chunks,
                "pdfs_downloaded": 0,
                "pdfs_indexed": 0,
                "total_chunks_found": len(rag_chunks),
                "offline_index": True,
                "source": "index",
            }

        # Step B: index miss + live fetch available — fetch, index, re-search,
        # and cache the label in-process for subsequent requests.
        _step(f"Not indexed yet — fetching “{product_name}” from CDMS…")

        # Step 1: Tavily search for PDF URLs
        print(f"🔍 Step 1: Searching Tavily for '{product_name}' PDFs...")
        tavily_result = self.search(
            product_name=product_name,
            active_ingredient=active_ingredient,
            max_results=3
        )
        
        if not tavily_result.get("success"):
            error_msg = tavily_result.get("error", "Tavily search failed")
            print(f"❌ Tavily search failed: {error_msg}")
            return {
                "success": False,
                "error": error_msg,
                "product_name": product_name
            }
        
        labels_found = tavily_result.get("label_count", 0)
        print(f"✅ Tavily search successful: Found {labels_found} label(s)")

        # Step 2: Download PDFs
        _step("Downloading the label PDF from CDMS…")
        print(f"📥 Step 2: Downloading PDFs for '{product_name}'...")
        download_result = self.download_pdfs(tavily_result, product_name)
        
        if not download_result.get("success"):
            error_msg = download_result.get("error", "PDF download failed")
            print(f"❌ PDF download failed: {error_msg}")
            return {
                "success": False,
                "error": error_msg,
                "product_name": product_name
            }
        
        downloaded_pdfs = download_result.get("downloaded_pdfs", [])

        # Step 3: Process and index PDFs (if not already indexed)
        _step("Processing & indexing the label (first-time only)…")
        pdfs_indexed = 0
        for pdf_info in downloaded_pdfs:
            pdf_path = pdf_info["filepath"]
            pdf_url = pdf_info.get("url", "")  # PHASE 1 FIX: Get URL from download info
            
            # Check if already indexed
            if not self._is_pdf_indexed(pdf_path):
                # Process and index with PDF URL
                try:
                    index_result = self.document_loader.load_pdf(
                        pdf_path, 
                        force_reprocess=False,
                        pdf_url=pdf_url  # PHASE 1 FIX: Pass PDF URL to store in metadata
                    )
                    if index_result.get("success"):
                        pdfs_indexed += 1
                except Exception as e:
                    print(f"⚠️  Warning: Could not index {pdf_path}: {e}")
        
        # Step 4: RAG search
        _step("Reading the freshly indexed label…")
        rag_chunks = self.rag_search.search(
            query=user_question,
            product_name=product_name,
            limit=5,
            score_threshold=0.4
        )

        # PHASE 1 FIX: Create multiple mapping strategies for PDF URL matching
        # Strategy 1: Filename to URL mapping (for backwards compatibility)
        filename_to_url = {}
        # Strategy 2: URL hash to URL mapping (most reliable)
        url_hash_to_url = {}
        
        for pdf_info in downloaded_pdfs:
            filename = pdf_info.get("filename", "")
            url = pdf_info.get("url", "")
            url_hash = pdf_info.get("url_hash", "")
            
            if filename and url:
                filename_to_url[filename] = url
            if url_hash and url:
                url_hash_to_url[url_hash] = url
        
        # Strategy 4: Create mapping from Tavily labels (fallback for PDFs not downloaded)
        tavily_urls = {}
        tavily_labels = tavily_result.get("labels", [])
        for label in tavily_labels:
            url = label.get("url", "")
            if url and url.lower().endswith('.pdf'):
                # Use URL as key (for direct matching)
                tavily_urls[url] = url
                # Also try to match by extracting identifier from URL
                # CDMS URLs often have format: .../ldat/mp50B003.pdf
                if '/ldat/' in url:
                    url_id = url.split('/ldat/')[-1].replace('.pdf', '')
                    tavily_urls[url_id] = url
        
        # PHASE 1 FIX: Enhanced URL matching with multiple fallback strategies
        chunks_with_url = 0
        chunks_without_url = 0
        
        for chunk in rag_chunks:
            # Strategy 1: Check if URL already in chunk (from Qdrant metadata - preferred)
            if chunk.get("pdf_url"):
                chunks_with_url += 1
                continue  # Already has URL from metadata
            
            source_file = chunk.get("source_file", "")
            document_id = chunk.get("document_id", "")
            chunk_url_hash = chunk.get("url_hash", "")
            
            # Strategy 2: Match by URL hash (most reliable - from Qdrant metadata)
            if chunk_url_hash and chunk_url_hash in url_hash_to_url:
                chunk["pdf_url"] = url_hash_to_url[chunk_url_hash]
                chunks_with_url += 1
                continue
            
            # Strategy 3: Match by document_id (reliable - from Qdrant metadata)
            # Document IDs are generated from filepath, so we can match by checking downloaded PDFs
            if document_id:
                for pdf_info in downloaded_pdfs:
                    # Generate document ID from filepath to match
                    from src.cdms.schema import Document
                    pdf_doc_id = Document.generate_id(pdf_info["filepath"])
                    if pdf_doc_id == document_id:
                        chunk["pdf_url"] = pdf_info.get("url", "")
                        if chunk["pdf_url"]:
                            chunks_with_url += 1
                            break
                if chunk.get("pdf_url"):
                    continue
            
            # Strategy 4: Match by exact filename
            if source_file in filename_to_url:
                chunk["pdf_url"] = filename_to_url[source_file]
                chunks_with_url += 1
                continue
            
            # Strategy 5: Match by source_file partial match (handle sanitized filenames)
            # Try to find URL by matching product name in filename
            product_lower = product_name.lower()
            matched = False
            for filename, url in filename_to_url.items():
                if product_lower in filename.lower():
                    chunk["pdf_url"] = url
                    chunks_with_url += 1
                    matched = True
                    break
            
            if matched:
                continue
            
            # Strategy 6: Fallback to Tavily labels (if no match found)
            if not chunk.get("pdf_url"):
                # Try to match by checking if any Tavily URL matches
                # This is a last resort - use first available Tavily URL
                if tavily_urls:
                    # Use the first Tavily URL as fallback
                    chunk["pdf_url"] = list(tavily_urls.values())[0]
                    chunks_with_url += 1
                else:
                    chunks_without_url += 1
                    print(f"⚠️  Warning: Could not find PDF URL for chunk from {source_file} (document_id: {document_id})")
        
        # Log URL matching results
        if chunks_without_url > 0:
            print(f"⚠️  Warning: {chunks_without_url} chunk(s) missing PDF URLs")
        print(f"✅ PDF URL matching: {chunks_with_url}/{len(rag_chunks)} chunks have URLs")
        
        # Step 5: Return results
        _step("Writing the answer…")
        return {
            "success": True,
            "product_name": product_name,
            "rag_chunks": rag_chunks,
            "pdfs_downloaded": len(downloaded_pdfs),
            "pdfs_indexed": pdfs_indexed,
            "total_chunks_found": len(rag_chunks),
            "source": "live",
            "tavily_results": tavily_result,
            "download_info": download_result,
            "pdf_urls": list(filename_to_url.values()),  # All PDF URLs
            "tavily_labels": tavily_labels  # Include Tavily labels with URLs
        }


def execute_cdms_label_tool(question: str, conversation_context: list = None, offline: bool = None, on_step=None) -> Dict:
    """
    Execute CDMS label search tool
    
    This is the interface for the tool executor.
    Extracts product name and active ingredient from the question and searches CDMS.
    Uses conversation context for follow-up questions.
    
    Args:
        question: User's natural language question
        conversation_context: Optional list of previous messages for context
    
    Returns:
        Dict with:
        {
            "success": True/False,
            "tool": "cdms_label",
            "data": {...search results with citations...},
            "error": "error message" if failed
        }
    """
    try:
        # Parameter extraction.
        #
        # Product recognition is driven by the ProductCatalog (what we have
        # actually indexed) instead of a fixed six-name keyword list. The old
        # hard-coded list -- ["roundup", "sevin", "2,4-d", "glyphosate",
        # "carbaryl", "atrazine"] -- failed to recognise every other product in
        # the index (Dauntless, Kozami, Megalodon, ...). When it failed, the
        # pipeline ran a global vector search that surfaced the dominant product
        # (Roundup here, "Trust" in the deployed data) for unrelated questions.
        from src.cdms.product_catalog import get_catalog
        catalog = get_catalog()

        product_name = None
        active_ingredient = None

        question_lower = question.lower()

        # 1) Resolve against products we can actually answer for.
        product_name = catalog.resolve(question)

        # 2) If not in the current question, carry it over from the conversation
        #    (handles follow-ups like "what about its safety?").
        if not product_name and conversation_context:
            for msg in reversed(conversation_context):  # most recent first
                resolved = catalog.resolve(msg.get("content", ""))
                if resolved:
                    product_name = resolved
                    break
        
        # If still no product found, try to extract from phrases like "label for X" or "X label"
        if not product_name:
            if "label for" in question_lower:
                parts = question_lower.split("label for")
                if len(parts) > 1:
                    product_name = parts[1].strip().split()[0] if parts[1].strip() else None
            elif "label" in question_lower:
                parts = question_lower.split("label")
                if parts[0].strip():
                    words = parts[0].strip().split()
                    if words:
                        product_name = words[-1]
        
        # If no product found, check if this is a pesticide-related question
        # If it is, we'll try CDMS anyway (might find something), otherwise it will fallback
        is_pesticide_related = any(
            kw in question_lower for kw in [
                "pesticide", "herbicide", "insecticide", "fungicide", "label",
                "application rate", "safety", "mixing", "chemical", "cdms"
            ]
        )
        
        # PHASE 2 FIX: Be more flexible - if tool matcher selected CDMS, trust it and try to search
        # Extract any potential product name from the question itself
        if not product_name:
            # Try to extract product name from common patterns
            # Pattern: "X label", "label for X", "X pesticide", etc.
            words = question_lower.split()
            
            # Look for word before "label"
            if "label" in words:
                label_idx = words.index("label")
                if label_idx > 0:
                    # Take words before "label" as potential product name (could be multiple words)
                    # Example: "Actagro 10% Boron label" -> "Actagro 10% Boron"
                    potential_product_parts = []
                    for i in range(label_idx - 1, -1, -1):  # Go backwards from label
                        word = words[i]
                        if word in ["the", "a", "an", "find", "get", "show", "search", "for", "of"]:
                            break
                        potential_product_parts.insert(0, word)
                        if len(potential_product_parts) >= 4:  # Limit to 4 words max
                            break
                    if potential_product_parts:
                        product_name = " ".join(potential_product_parts)
            
            # Look for word before "pesticide", "herbicide", etc.
            if not product_name:
                for term in ["pesticide", "herbicide", "insecticide", "fungicide"]:
                    if term in words:
                        term_idx = words.index(term)
                        if term_idx > 0:
                            # Take words before the term
                            potential_product_parts = []
                            for i in range(term_idx - 1, -1, -1):
                                word = words[i]
                                if word in ["the", "a", "an", "find", "get", "show", "search", "for", "of"]:
                                    break
                                potential_product_parts.insert(0, word)
                                if len(potential_product_parts) >= 4:
                                    break
                            if potential_product_parts:
                                product_name = " ".join(potential_product_parts)
                                break
        
        # If still no product but pesticide-related, extract the product token robustly.
        if not product_name:
            if is_pesticide_related:
                # Preferred: the noun right after "for"/"of"/"about"
                # ("application rate for atrazine" -> "atrazine"). Otherwise drop
                # question words AND pesticide-domain filler and keep the remaining
                # content word(s). The old filter kept "is"/"application"/"rate", so
                # "What is the application rate for atrazine?" became the bogus product
                # "is application rate atrazine" -> live fetch then abstained on it.
                import re as _re
                _STOP = {
                    "what", "whats", "how", "tell", "me", "about", "find", "get", "show",
                    "give", "search", "for", "the", "a", "an", "is", "are", "was", "were",
                    "do", "does", "did", "can", "could", "will", "would", "should", "i",
                    "my", "need", "want", "know", "of", "on", "in", "at", "to", "and", "or",
                    "this", "that", "it", "its", "please", "label", "labels", "pesticide",
                    "herbicide", "insecticide", "fungicide", "application", "rate", "rates",
                    "apply", "applied", "safety", "mixing", "mix", "interval", "use",
                    "using", "chemical", "information", "info", "product", "amount", "dose",
                    "dosage", "much",
                }
                toks = [t for t in (_re.sub(r"[^\w%.-]", "", w) for w in question.split()) if t]
                lower = [t.lower() for t in toks]
                anchors = [i for i, lo in enumerate(lower) if lo in ("for", "of", "about")]
                cand = []
                if anchors:
                    cand = [toks[i] for i in range(max(anchors) + 1, len(toks)) if lower[i] not in _STOP]
                if not cand:  # no for/of/about, or nothing useful after it
                    cand = [t for t, lo in zip(toks, lower) if lo not in _STOP]
                product_name = " ".join(cand[:4]) if cand else "pesticide"
            else:
                # Not pesticide-related and no product - return error (will trigger fallback)
                return {
                    "success": False,
                    "tool": "cdms_label",
                    "error": "Could not identify the pesticide product name. Please specify a product (e.g., 'Find Roundup label')",
                    "should_fallback": True  # Flag for fallback
                }
        
        # Create tool (offline=None -> auto-mode: index first, live-fetch on miss
        # when a Tavily key is configured; True -> force index-only).
        tool = CDMSLabelTool(offline=offline)
        
        # Enhance question with context if this is a follow-up
        enhanced_question = question
        
        # Detect follow-up question types
        followup_keywords = {
            "safety": ["safety", "safe", "precaution", "hazard", "danger", "toxic", "poison", "warning", "protective"],
            "application": ["application", "apply", "rate", "dosage", "amount", "how much", "when to apply"],
            "mixing": ["mix", "mixing", "dilute", "dilution", "solution", "concentrate", "ratio"],
            "reentry": ["re-entry", "reentry", "rei", "when can i", "how long", "wait", "interval"],
            "storage": ["store", "storage", "keep", "shelf life", "expiration"],
            "crops": ["crop", "crops", "use on", "for", "suitable", "compatible"]
        }
        
        detected_type = None
        for ftype, fkeywords in followup_keywords.items():
            if any(kw in question_lower for kw in fkeywords):
                detected_type = ftype
                break
        
        # If this looks like a follow-up question, enhance with context
        is_followup = (
            conversation_context and (
                # No product name in current question but has context
                (not product_name or product_name == "pesticide") or
                # Question is vague/short
                len(question.split()) <= 5 or
                # Detected follow-up type
                detected_type is not None or
                # Common follow-up phrases
                any(phrase in question_lower for phrase in [
                    "what about", "how about", "tell me more", "and", "also", "what's the"
                ])
            )
        )
        
        if is_followup:
            # Find the most recent product mentioned in the conversation, using
            # the data-driven catalog. (The previous code iterated an undefined
            # `keywords` list -> NameError, silently breaking every follow-up.)
            context_product = None
            for msg in reversed(conversation_context):
                resolved = catalog.resolve(msg.get("content", ""))
                if resolved:
                    context_product = resolved
                    break
            
            # If we found a product in context, use it
            if context_product and (not product_name or product_name == "pesticide"):
                product_name = context_product
            
            # Enhance question with product context and follow-up type
            if product_name and product_name != "pesticide":
                if detected_type:
                    # Add specific context based on follow-up type
                    enhanced_question = f"{question} for {product_name} {detected_type}"
                else:
                    enhanced_question = f"{question} about {product_name}"
            elif detected_type:
                # Add follow-up type context
                enhanced_question = f"{question} {detected_type}"
        
        # Auto-mode RAG pipeline: index first, live-fetch + cache on a miss.
        result = tool.search_with_rag(
            product_name=product_name,
            user_question=enhanced_question,  # Pass enhanced question for RAG search
            active_ingredient=active_ingredient,
            on_step=on_step,
        )
        
        if not result.get("success"):
            return {
                "success": False,
                "tool": "cdms_label",
                "error": result.get("error", "CDMS RAG search failed")
            }
        
        # Return successful result with RAG chunks and page citations
        return {
            "success": True,
            "tool": "cdms_label",
            "data": result
        }
    
    except Exception as e:
        return {
            "success": False,
            "tool": "cdms_label",
            "error": f"Unexpected error: {str(e)}"
        }


# Test the tool
if __name__ == "__main__":
    print("=" * 80)
    print("Testing CDMS Label Tool with Citations")
    print("=" * 80)
    
    tool = CDMSLabelTool()
    
    # Test 1: Roundup (common product)
    print("\nTEST 1: Search for Roundup labels")
    print("-" * 80)
    
    result = tool.search(
        product_name="Roundup",
        active_ingredient="glyphosate",
        max_results=3
    )
    
    # Show formatted output
    print(tool.format_response_for_user(result))
    
    # Test 2: Sevin (another common product)
    print("\n" + "=" * 80)
    print("TEST 2: Search for Sevin labels")
    print("-" * 80)
    
    result = tool.search(
        product_name="Sevin",
        active_ingredient="carbaryl",
        max_results=3
    )
    
    print(tool.format_response_for_user(result))
    
    # Test 3: Just product name (no ingredient)
    print("\n" + "=" * 80)
    print("TEST 3: Search with product name only")
    print("-" * 80)
    
    result = tool.search(
        product_name="2,4-D",
        max_results=3
    )
    
    print(tool.format_response_for_user(result))
    
    print("\n" + "=" * 80)
    print("✅ All tests complete!")
    print("=" * 80)