snm-brightdata-client 0.4.0

Bright Data Wrapper Client Highly compacted Data implemented in Rust with Actix Web
Documentation
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
// src/tools/stock.rs - ENHANCED VERSION WITH REDIS CACHE AND DEDUCT_DATA SUPPORT
use crate::tool::{Tool, ToolResult, McpContent};
use crate::error::BrightDataError;
use crate::filters::{ResponseFilter, ResponseStrategy, ResponseType};
use crate::extras::logger::JSON_LOGGER;
use crate::metrics::brightdata_logger::BRIGHTDATA_METRICS;
use crate::services::cache::stock_cache::get_stock_cache;
use async_trait::async_trait;
use reqwest::Client;
use serde_json::{json, Value};
use std::env;
use std::time::{Duration, Instant};
use std::collections::HashMap;
use log::{info, warn, error};
use crate::symbols::stock_symbol::match_symbol_from_query;

// Struct to organize URLs by method
#[derive(Debug, Clone)]
pub struct MethodUrls {
    pub proxy: Vec<(String, String)>,  // (url, description)
    pub direct: Vec<(String, String)>, // (url, description)
}

pub struct StockDataTool;

#[async_trait]
impl Tool for StockDataTool {
    fn name(&self) -> &str {
        "get_stock_data"
    }

    fn description(&self) -> &str {
        "Get comprehensive stock data including prices, performance, market cap, volumes with intelligent filtering and priority-based processing. Supports both direct BrightData API and proxy fallback."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Stock symbol (e.g. TATAMOTORS, TCS, AAPL), company name, comparison query, or market overview request"
                },
                "symbol": {
                    "type": "string",
                    "description": "Stock symbol (e.g. TATAMOTORS, TCS, AAPL), company name, comparison query, or market overview request"
                },
                "market": {
                    "type": "string",
                    "enum": ["indian", "us", "global"],
                    "default": "indian",
                    "description": "Market region - indian for NSE/BSE stocks, us for NASDAQ/NYSE, global for international"
                },
                "data_type": {
                    "type": "string",
                    "enum": ["price", "fundamentals", "technical", "news", "all"],
                    "default": "all",
                    "description": "Type of stock data to focus on"
                },
                "timeframe": {
                    "type": "string",
                    "enum": ["realtime", "day", "week", "month", "quarter", "year"],
                    "default": "realtime",
                    "description": "Time period for stock data analysis"
                },
                "include_ratios": {
                    "type": "boolean",
                    "default": true,
                    "description": "Include financial ratios like P/E, P/B, ROE"
                },
                "include_volume": {
                    "type": "boolean",
                    "default": true,
                    "description": "Include trading volume and liquidity data"
                },
                "session_id": {
                    "type": "string",
                    "description": "Session identifier for caching (optional, will use default if not provided)"
                },
            },
            "required": ["query"]
        })
    }

    async fn execute(&self, parameters: Value) -> Result<ToolResult, BrightDataError> {
        self.execute_internal(parameters).await
    }

    async fn execute_internal(&self, parameters: Value) -> Result<ToolResult, BrightDataError> {
        let raw_query = parameters
            .get("symbol")
            .and_then(|v| v.as_str())
            .ok_or_else(|| BrightDataError::ToolError("Missing 'symbol' parameter".into()))?;

        let session_id = parameters
            .get("user_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| BrightDataError::ToolError("Missing 'user_id' parameter".into()))?;

        // Step 1: Resolve known symbols (or fallback)
        let matched_symbol = match_symbol_from_query(raw_query);

        // Step 2: Strip trailing .com / .xyz etc.
        let query = matched_symbol.split('.').next().unwrap_or(&matched_symbol);

        let market = parameters
            .get("market")
            .and_then(|v| v.as_str())
            .unwrap_or("indian");

        let data_type = parameters
            .get("data_type")
            .and_then(|v| v.as_str())
            .unwrap_or("all");

        let timeframe = parameters
            .get("timeframe")
            .and_then(|v| v.as_str())
            .unwrap_or("realtime");

        let include_ratios = parameters
            .get("include_ratios")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let include_volume = parameters
            .get("include_volume")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let query_priority = ResponseStrategy::classify_query_priority(query);
        let recommended_tokens = ResponseStrategy::get_recommended_token_allocation(query);

        let execution_id = format!("stock_{}", chrono::Utc::now().format("%Y%m%d_%H%M%S%.3f"));
        
        info!("๐Ÿ“ˆ Stock query: '{}' (market: {}, priority: {:?}, tokens: {}, session: {})", 
              query, market, query_priority, recommended_tokens, session_id);
        
        // ๐ŸŽฏ CACHE CHECK - Check Redis cache first
        match self.check_cache_first(query, session_id).await {
            Ok(Some(cached_result)) => {
                info!("๐Ÿš€ Cache HIT: Returning cached data for {} in session {}", query, session_id);
                
                // Create tool result from cached data
                let content = cached_result.get("content").and_then(|c| c.as_str()).unwrap_or("");
                let source_used = cached_result.get("source_used").and_then(|s| s.as_str()).unwrap_or("Cache");
                let method_used = "Redis Cache";
                
                let formatted_response = self.create_formatted_stock_response(
                    query, market, content, source_used, method_used, 
                    data_type, timeframe, include_ratios, include_volume, &execution_id
                );
                
                let tool_result = ToolResult::success_with_raw(
                    vec![McpContent::text(formatted_response)], 
                    cached_result
                );
                
                // Apply filtering only if DEDUCT_DATA=true
                if self.is_data_reduction_enabled() {
                    return Ok(ResponseStrategy::apply_size_limits(tool_result));
                } else {
                    return Ok(tool_result);
                }
            }
            Ok(None) => {
                info!("๐Ÿ’พ Cache MISS: Fetching fresh data for {} in session {}", query, session_id);
            }
            Err(e) => {
                warn!("๐Ÿšจ Cache error (continuing with fresh fetch): {}", e);
            }
        }

        // ๐ŸŒ FRESH FETCH - Cache miss, fetch from sources
        match self.fetch_stock_data_with_fallbacks_and_priority(
            query, market, data_type, timeframe, include_ratios, include_volume,
            query_priority, recommended_tokens, &execution_id
        ).await {
            Ok(result) => {
                // ๐Ÿ—„๏ธ CACHE STORE - Store successful result in cache
                if let Err(e) = self.store_in_cache(query, session_id, &result).await {
                    warn!("Failed to store result in cache: {}", e);
                }
                
                let content = result.get("content").and_then(|c| c.as_str()).unwrap_or("");
                let source_used = result.get("source_used").and_then(|s| s.as_str()).unwrap_or("Unknown");
                let method_used = result.get("method_used").and_then(|m| m.as_str()).unwrap_or("Unknown");
                
                // Create formatted response based on DEDUCT_DATA setting
                let formatted_response = self.create_formatted_stock_response(
                    query, market, content, source_used, method_used, 
                    data_type, timeframe, include_ratios, include_volume, &execution_id
                );
                
                let tool_result = ToolResult::success_with_raw(
                    vec![McpContent::text(formatted_response)], 
                    result
                );
                
                // Apply filtering only if DEDUCT_DATA=true
                if self.is_data_reduction_enabled() {
                    Ok(ResponseStrategy::apply_size_limits(tool_result))
                } else {
                    Ok(tool_result)
                }
            }
            Err(_e) => {
                // Return empty data for BrightData errors - Anthropic will retry
                warn!("BrightData error for query '{}', returning empty data for retry", query);
                let empty_response = json!({
                    "query": query,
                    "market": market,
                    "status": "no_data",
                    "reason": "brightdata_error",
                    "execution_id": execution_id,
                    "session_id": session_id
                });
                
                Ok(ToolResult::success_with_raw(
                    vec![McpContent::text("๐Ÿ“ˆ **No Data Available**\n\nPlease try again with a more specific stock symbol.".to_string())],
                    empty_response
                ))
            }
        }
    }
}

impl StockDataTool {
    /// ENHANCED: Check if data reduction is enabled via DEDUCT_DATA environment variable only
    fn is_data_reduction_enabled(&self) -> bool {
        std::env::var("DEDUCT_DATA")
            .unwrap_or_else(|_| "false".to_string())
            .to_lowercase() == "true"
    }

    /// ENHANCED: Create formatted response with DEDUCT_DATA control
    fn create_formatted_stock_response(
        &self,
        query: &str,
        market: &str, 
        content: &str,
        source: &str,
        method: &str,
        data_type: &str,
        timeframe: &str,
        include_ratios: bool,
        include_volume: bool,
        execution_id: &str
    ) -> String {
        // If DEDUCT_DATA=false, return full content with basic formatting
        if !self.is_data_reduction_enabled() {
            return format!(
                "๐Ÿ“ˆ **{}** | {} Market\n\n## Full Content\n{}\n\n*Source: {} via {} โ€ข Type: {} โ€ข Period: {}*",
                query.to_uppercase(), 
                market.to_uppercase(), 
                content,
                source, 
                method, 
                data_type, 
                timeframe
            );
        }

        // TODO: Add filtered data extraction logic when DEDUCT_DATA=true
        // For now, return full content formatted
        format!(
            "๐Ÿ“ˆ **{}** | {} Market\n\n## Content (TODO: Add Filtering)\n{}\n\n*Source: {} via {} โ€ข Type: {} โ€ข Period: {}*",
            query.to_uppercase(), 
            market.to_uppercase(), 
            content,
            source, 
            method, 
            data_type, 
            timeframe
        )
    }
    
    /// TODO: Extract essential stock data using existing filter methods
    fn extract_essential_stock_data(&self, content: &str, query: &str) -> String {
        // TODO: Add essential stock data extraction logic
        // For now, return original content
        content.to_string()
    }
    
    /// TODO: Extract financial lines when filtering is disabled
    fn extract_financial_lines(&self, content: &str) -> String {
        // TODO: Add financial lines extraction logic
        // For now, return original content
        content.to_string()
    }
    
    /// TODO: Format financial metrics into clean markdown
    fn format_financial_metrics(&self, data: &str) -> String {
        // TODO: Add financial metrics formatting logic
        // For now, return data as-is
        data.to_string()
    }

    // ๐ŸŽฏ ADDED: Check Redis cache first
    async fn check_cache_first(
        &self,
        query: &str,
        session_id: &str,
    ) -> Result<Option<Value>, BrightDataError> {
        let cache_service = get_stock_cache().await?;
        cache_service.get_cached_stock_data(session_id, query).await
    }

    // ๐Ÿ—„๏ธ ADDED: Store successful result in Redis cache
    async fn store_in_cache(
        &self,
        query: &str,
        session_id: &str,
        data: &Value,
    ) -> Result<(), BrightDataError> {
        let cache_service = get_stock_cache().await?;
        cache_service.cache_stock_data(session_id, query, data.clone()).await
    }

    // ๐Ÿ” ADDED: Get all cached symbols for session (useful for comparisons)
    pub async fn get_session_cached_symbols(&self, session_id: &str) -> Result<Vec<String>, BrightDataError> {
        let cache_service = get_stock_cache().await?;
        cache_service.get_session_stock_symbols(session_id).await
    }

    // ๐Ÿ—‘๏ธ ADDED: Clear cache for specific symbol
    pub async fn clear_symbol_cache(
        &self,
        symbol: &str,
        session_id: &str,
    ) -> Result<(), BrightDataError> {
        let cache_service = get_stock_cache().await?;
        cache_service.clear_stock_symbol_cache(session_id, symbol).await
    }

    // ๐Ÿ—‘๏ธ ADDED: Clear entire session cache
    pub async fn clear_session_cache(&self, session_id: &str) -> Result<u32, BrightDataError> {
        let cache_service = get_stock_cache().await?;
        cache_service.clear_session_stock_cache(session_id).await
    }

    // ๐Ÿ“Š ADDED: Get cache statistics
    pub async fn get_cache_stats(&self) -> Result<Value, BrightDataError> {
        let cache_service = get_stock_cache().await?;
        cache_service.get_stock_cache_stats().await
    }

    // ๐Ÿฅ ADDED: Enhanced connectivity test including cache
    pub async fn test_connectivity_with_cache(&self) -> Result<String, BrightDataError> {
        let mut results = Vec::new();
        
        // Test cache connectivity
        info!("๐Ÿงช Testing Redis Cache...");
        match get_stock_cache().await {
            Ok(cache_service) => {
                match cache_service.health_check().await {
                    Ok(_) => results.push("โœ… Redis Cache: SUCCESS".to_string()),
                    Err(e) => results.push(format!("โŒ Redis Cache: FAILED - {}", e)),
                }
            }
            Err(e) => results.push(format!("โŒ Redis Cache: FAILED - {}", e)),
        }
        
        // Test existing connectivity
        let api_test = self.test_connectivity().await?;
        results.push(api_test);
        
        Ok(format!("๐Ÿ” Enhanced Connectivity Test Results:\n{}", results.join("\n")))
    }

    /// ENHANCED: Build URLs separated by method (proxy vs direct)
    fn build_prioritized_urls_with_priority(
        &self, 
        query: &str, 
        market: &str, 
        data_type: &str,
        priority: crate::filters::strategy::QueryPriority
    ) -> MethodUrls {
        let mut proxy_urls = Vec::new();
        let mut direct_urls = Vec::new();
        let clean_query = query.trim().to_uppercase();

        // Add priority-based URL limiting
        let max_sources = 3;

        if self.is_likely_stock_symbol(&clean_query) {
            match market {
                "indian" => {
                    // TODO: Add priority-based URL selection logic
                    let symbols_to_try = vec![
                        format!("{}.NS", clean_query),
                        format!("{}.BO", clean_query),
                        clean_query.clone(),
                    ];
                    
                    for (i, symbol) in symbols_to_try.iter().enumerate() {
                        if i >= max_sources { break; }
                        
                        let url = format!("https://finance.yahoo.com/quote/{}", symbol);
                        let description = format!("Yahoo Finance ({})", symbol);

                        let proxy_url = format!("https://finance.yahoo.com/quote/{}/", symbol);
                        let proxy_description = format!("Yahoo Finance ({})", symbol);
                        
                        // Add to both proxy and direct (same URLs, different methods)
                        proxy_urls.push((proxy_url, proxy_description));
                        direct_urls.push((url, description));
                    }
                }
                "us" => {
                    let url = format!("https://finance.yahoo.com/quote/{}.NS/", clean_query);
                    let description = format!("Yahoo Finance ({})", clean_query);

                    let proxy_url = format!("https://finance.yahoo.com/quote/{}.NS/", clean_query);
                    let proxy_description = format!("Yahoo Finance ({})", clean_query);
                    
                    proxy_urls.push((proxy_url, proxy_description));
                    direct_urls.push((url, description));
                }
                "global" => {
                    let url = format!("https://finance.yahoo.com/quote/{}.NS/", clean_query);
                    let description = format!("Yahoo Finance Global ({})", clean_query);

                    let proxy_url = format!("https://finance.yahoo.com/quote/{}.NS/", clean_query);
                    let proxy_description = format!("Yahoo Finance Global ({})", clean_query);
                    
                    proxy_urls.push((proxy_url, proxy_description));
                    direct_urls.push((url, description));
                }
                _ => {}
            }
        }

        // Add search fallbacks (no restrictions when DEDUCT_DATA=false)
        if proxy_urls.len() < max_sources {
            let url = format!("https://finance.yahoo.com/quote/{}", urlencoding::encode(query));
            let description = "Yahoo Finance Search".to_string();

            let proxy_url = format!("https://finance.yahoo.com/quote/{}", urlencoding::encode(query));
            let proxy_description = "Yahoo Finance Search".to_string();
            
            proxy_urls.push((proxy_url, proxy_description));
            direct_urls.push((url, description));
        }

        info!("๐ŸŽฏ Generated {} proxy URLs and {} direct URLs for query '{}' (priority: {:?})", 
              proxy_urls.len(), direct_urls.len(), query, priority);
        
        MethodUrls {
            proxy: proxy_urls,
            direct: direct_urls,
        }
    }

    /// ENHANCED: Main fetch function with method-separated URL structure
    async fn fetch_stock_data_with_fallbacks_and_priority(
        &self, 
        query: &str, 
        market: &str, 
        data_type: &str,
        timeframe: &str,
        include_ratios: bool,
        include_volume: bool,
        query_priority: crate::filters::strategy::QueryPriority,
        token_budget: usize,
        execution_id: &str
    ) -> Result<Value, BrightDataError> {
        let method_urls = self.build_prioritized_urls_with_priority(query, market, data_type, query_priority);
        let mut last_error = None;
        let mut attempts = Vec::new();

        // Define method priority: try direct first, then proxy
        let methods_to_try = vec![
            // ("direct", "Direct Call", &method_urls.direct),
            ("proxy", "Proxy Fallback", &method_urls.proxy)
        ];

        for (method_sequence, (method_type, method_name, urls_for_method)) in methods_to_try.iter().enumerate() {
            info!("๐Ÿ”„ Trying {} method with {} URLs", method_name, urls_for_method.len());
            
            for (url_sequence, (url, source_name)) in urls_for_method.iter().enumerate() {
                let attempt_result = match *method_type {
                    "direct" => {
                        info!("๐ŸŒ Trying Direct BrightData API for {} (method: {}, url: {}/{})", 
                              source_name, method_sequence + 1, url_sequence + 1, urls_for_method.len());
                        self.try_fetch_url_direct_api(
                            url, query, market, source_name, query_priority, token_budget, 
                            execution_id, url_sequence as u64, method_sequence as u64
                        ).await
                    }
                    "proxy" => {
                        info!("๐Ÿ”„ Trying Proxy method for {} (method: {}, url: {}/{})", 
                              source_name, method_sequence + 1, url_sequence + 1, urls_for_method.len());
                        self.try_fetch_url_via_proxy(
                            url, query, market, source_name, query_priority, token_budget, 
                            execution_id, url_sequence as u64, method_sequence as u64
                        ).await
                    }
                    _ => continue,
                };

                match attempt_result {
                    Ok(mut result) => {
                        let content = result.get("content").and_then(|c| c.as_str()).unwrap_or("");
                        
                        attempts.push(json!({
                            "source": source_name,
                            "url": url,
                            "method": method_name,
                            "status": "success",
                            "content_length": content.len(),
                            "method_sequence": method_sequence + 1,
                            "url_sequence": url_sequence + 1
                        }));
                        
                        // TODO: Add content quality check when DEDUCT_DATA=true
                        let should_try_next = if self.is_data_reduction_enabled() {
                            // TODO: Add quality-based next source logic
                            false
                        } else {
                            false
                        };
                        
                        if should_try_next && (url_sequence < urls_for_method.len() - 1 || method_sequence < methods_to_try.len() - 1) {
                            if url_sequence < urls_for_method.len() - 1 {
                                warn!("Content insufficient from {} via {}, trying next URL in same method", source_name, method_name);
                                continue; // Try next URL in same method
                            } else {
                                warn!("Content insufficient from {} via {}, trying next method", source_name, method_name);
                                break; // Try next method
                            }
                        }
                        
                        // SUCCESS - but validate data quality first only if DEDUCT_DATA=true
                        if self.is_data_reduction_enabled() {
                            // TODO: Add data quality validation when DEDUCT_DATA=true
                            // For now, accept all content
                        }
                        
                        // SUCCESS
                        result["source_used"] = json!(source_name);
                        result["url_used"] = json!(url);
                        result["method_used"] = json!(method_name);
                        result["execution_id"] = json!(execution_id);
                        result["priority"] = json!(format!("{:?}", query_priority));
                        result["token_budget"] = json!(token_budget);
                        result["attempts"] = json!(attempts);
                        result["successful_method_sequence"] = json!(method_sequence + 1);
                        result["successful_url_sequence"] = json!(url_sequence + 1);
                        
                        info!("โœ… Successfully fetched stock data from {} via {} (method: {}, url: {})", 
                              source_name, method_name, method_sequence + 1, url_sequence + 1);
                        
                        return Ok(result);
                    }
                    Err(e) => {
                        attempts.push(json!({
                            "source": source_name,
                            "url": url,
                            "method": method_name,
                            "status": "failed",
                            "error": e.to_string(),
                            "method_sequence": method_sequence + 1,
                            "url_sequence": url_sequence + 1
                        }));
                        
                        last_error = Some(e);
                        warn!("โŒ Failed to fetch from {} via {} (method: {}, url: {}): {:?}", 
                              source_name, method_name, method_sequence + 1, url_sequence + 1, last_error);
                    }
                }
            }
        }

        // All methods and sources failed - return empty data instead of error
        warn!("โŒ All sources and methods failed for query '{}'. Returning empty data for Anthropic retry", query);
        
        let empty_result = json!({
            "query": query,
            "market": market,
            "status": "no_data_found",
            "attempts": attempts,
            "execution_id": execution_id,
            "total_attempts": method_urls.direct.len() + method_urls.proxy.len(),
            "reason": "all_sources_failed"
        });
        
        Ok(empty_result)
    }

    // Direct BrightData API method (existing implementation)
    async fn try_fetch_url_direct_api(
        &self, 
        url: &str, 
        query: &str, 
        market: &str, 
        source_name: &str, 
        priority: crate::filters::strategy::QueryPriority,
        token_budget: usize,
        execution_id: &str,
        sequence: u64,
        method_sequence: u64
    ) -> Result<Value, BrightDataError> {
        let max_retries = env::var("MAX_RETRIES")
            .ok()
            .and_then(|s| s.parse::<u32>().ok())
            .unwrap_or(1);
        
        let mut last_error = None;
        
        for retry_attempt in 0..max_retries {
            let start_time = Instant::now();
            let attempt_id = format!("{}_direct_s{}_m{}_r{}", execution_id, sequence, method_sequence, retry_attempt);
            
            info!("๐ŸŒ Direct API: Fetching from {} (execution: {}, retry: {}/{})", 
                  source_name, attempt_id, retry_attempt + 1, max_retries);
            
            let api_token = env::var("BRIGHTDATA_API_TOKEN")
                .or_else(|_| env::var("API_TOKEN"))
                .map_err(|_| BrightDataError::ToolError("Missing BRIGHTDATA_API_TOKEN environment variable".into()))?;

            let base_url = env::var("BRIGHTDATA_BASE_URL")
                .unwrap_or_else(|_| "https://api.brightdata.com".to_string());

            let zone = env::var("WEB_UNLOCKER_ZONE")
                .unwrap_or_else(|_| "mcp_unlocker".to_string());

            let payload = json!({
                "url": url,
                "zone": zone,
                "format": "raw",
                // "data_format": "markdown"
            });

            if retry_attempt == 0 {
                info!("๐Ÿ“ค Direct API Request:");
                info!("   Endpoint: {}/request", base_url);
                info!("   Zone: {}", zone);
                info!("   Target: {}", url);
            }

            let client = Client::builder()
                .timeout(Duration::from_secs(90))
                .build()
                .map_err(|e| BrightDataError::ToolError(format!("Failed to create HTTP client: {}", e)))?;

            let response = client
                .post(&format!("{}/request", base_url))
                .header("Authorization", format!("Bearer {}", api_token))
                .header("Content-Type", "application/json")
                .json(&payload)
                .send()
                .await
                .map_err(|e| BrightDataError::ToolError(format!("Direct API request failed to {}: {}", source_name, e)))?;

            let duration = start_time.elapsed();
            let status = response.status().as_u16();
            let response_headers: HashMap<String, String> = response
                .headers()
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
                .collect();

            info!("๐Ÿ“ฅ Direct API Response (retry {}):", retry_attempt + 1);
            info!("   Status: {}", status);
            info!("   Duration: {}ms", duration.as_millis());

            let response_text = response.text().await
                .map_err(|e| BrightDataError::ToolError(format!("Failed to read response body from {}: {}", source_name, e)))?;

            // Handle server errors with retry
            if matches!(status, 502 | 503 | 504) && retry_attempt < max_retries - 1 {
                let wait_time = Duration::from_millis(1000 + (retry_attempt as u64 * 1000));
                warn!("โณ Direct API: Server error {}, waiting {}ms before retry...", status, wait_time.as_millis());
                tokio::time::sleep(wait_time).await;
                last_error = Some(BrightDataError::ToolError(format!("Direct API server error: {}", status)));
                continue;
            }
            
            if !(200..300).contains(&status) {
                let error_msg = format!("Direct API: {} returned HTTP {}: {}", source_name, status, 
                                      &response_text[..response_text.len().min(500)]);
                last_error = Some(BrightDataError::ToolError(error_msg));
                if retry_attempt == max_retries - 1 {
                    return Err(last_error.unwrap());
                }
                continue;
            }

            // SUCCESS - Process response (apply filtering only if DEDUCT_DATA=true)
            let raw_content = response_text;
            let filtered_content = if self.is_data_reduction_enabled() {
                // TODO: Add content filtering logic when DEDUCT_DATA=true
                raw_content.clone()
            } else {
                raw_content.clone()
            };

            info!("๐Ÿ“Š Direct API: Content processed: {} bytes -> {} bytes", 
                  raw_content.len(), filtered_content.len());

            // Log metrics
            if let Err(e) = BRIGHTDATA_METRICS.log_call(
                &attempt_id,
                url,
                &zone,
                "raw",
                None,
                payload.clone(),
                status,
                response_headers.clone(),
                &raw_content,
                Some(&filtered_content),
                duration.as_millis() as u64,
                None,
                None,
            ).await {
                warn!("Failed to log direct API metrics: {}", e);
            }

            return Ok(json!({
                "content": filtered_content,
                "raw_content": raw_content,
                "query": query,
                "market": market,
                "source": source_name,
                "method": "Direct BrightData API",
                "priority": format!("{:?}", priority),
                "token_budget": token_budget,
                "execution_id": execution_id,
                "sequence": sequence,
                "method_sequence": method_sequence,
                "success": true,
                "url": url,
                "zone": zone,
                "format": "raw",
                "status_code": status,
                "response_size_bytes": raw_content.len(),
                "filtered_size_bytes": filtered_content.len(),
                "duration_ms": duration.as_millis(),
                "timestamp": chrono::Utc::now().to_rfc3339(),
                "retry_attempts": retry_attempt + 1,
                "max_retries": max_retries,
                "payload_used": payload
            }));
        }

        Err(last_error.unwrap_or_else(|| BrightDataError::ToolError("Direct API: All retry attempts failed".into())))
    }

    // Proxy-based method
    async fn try_fetch_url_via_proxy(
        &self, 
        url: &str, 
        query: &str, 
        market: &str, 
        source_name: &str, 
        priority: crate::filters::strategy::QueryPriority,
        token_budget: usize,
        execution_id: &str,
        sequence: u64,
        method_sequence: u64
    ) -> Result<Value, BrightDataError> {
        let max_retries = env::var("MAX_RETRIES")
            .ok()
            .and_then(|s| s.parse::<u32>().ok())
            .unwrap_or(1);
        
        let mut last_error = None;
        
        // Get proxy configuration from environment
        let proxy_host = env::var("BRIGHTDATA_PROXY_HOST")
            .map_err(|_| BrightDataError::ToolError("Missing BRIGHTDATA_PROXY_HOST environment variable".into()))?;
        let proxy_port = env::var("BRIGHTDATA_PROXY_PORT")
            .map_err(|_| BrightDataError::ToolError("Missing BRIGHTDATA_PROXY_PORT environment variable".into()))?;
        let proxy_username = env::var("BRIGHTDATA_PROXY_USERNAME")
            .map_err(|_| BrightDataError::ToolError("Missing BRIGHTDATA_PROXY_USERNAME environment variable".into()))?;
        let proxy_password = env::var("BRIGHTDATA_PROXY_PASSWORD")
            .map_err(|_| BrightDataError::ToolError("Missing BRIGHTDATA_PROXY_PASSWORD environment variable".into()))?;

        let proxy_url = format!("http://{}:{}@{}:{}", proxy_username, proxy_password, proxy_host, proxy_port);
        
        for retry_attempt in 0..max_retries {
            let start_time = Instant::now();
            let attempt_id = format!("{}_proxy_s{}_m{}_r{}", execution_id, sequence, method_sequence, retry_attempt);
            
            info!("๐Ÿ”„ Proxy: Fetching from {} via proxy (execution: {}, retry: {}/{})", 
                  source_name, attempt_id, retry_attempt + 1, max_retries);
            
            if retry_attempt == 0 {
                info!("๐Ÿ“ค Proxy Request:");
                info!("   Proxy: {}:{}@{}:{}", proxy_username, "***", proxy_host, proxy_port);
                info!("   Target: {}", url);
            }

            // Create client with proxy configuration
            let proxy = reqwest::Proxy::all(&proxy_url)
                .map_err(|e| BrightDataError::ToolError(format!("Failed to create proxy: {}", e)))?;

            let client = Client::builder()
                .proxy(proxy)
                .timeout(Duration::from_secs(90))
                .danger_accept_invalid_certs(true) // Often needed for proxy connections
                .build()
                .map_err(|e| BrightDataError::ToolError(format!("Failed to create proxy client: {}", e)))?;

            let response = client
                .get(url)
                .header("x-unblock-data-format", "markdown")
                .send()
                .await
                .map_err(|e| BrightDataError::ToolError(format!("Proxy request failed to {}: {}", source_name, e)))?;

            let duration = start_time.elapsed();
            let status = response.status().as_u16();
            let response_headers: HashMap<String, String> = response
                .headers()
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
                .collect();

            info!("๐Ÿ“ฅ Proxy Response (retry {}):", retry_attempt + 1);
            info!("   Status: {}", status);
            info!("   Duration: {}ms", duration.as_millis());

            let response_text = response.text().await
                .map_err(|e| BrightDataError::ToolError(format!("Failed to read proxy response body from {}: {}", source_name, e)))?;

            // Handle server errors with retry
            if matches!(status, 502 | 503 | 504) && retry_attempt < max_retries - 1 {
                let wait_time = Duration::from_millis(1000 + (retry_attempt as u64 * 1000));
                warn!("โณ Proxy: Server error {}, waiting {}ms before retry...", status, wait_time.as_millis());
                tokio::time::sleep(wait_time).await;
                last_error = Some(BrightDataError::ToolError(format!("Proxy server error: {}", status)));
                continue;
            }
            
            if !(200..300).contains(&status) {
                println!("-----------------------------------------------------------------");
                println!("MARKDOWN SUCCESS: {:?}", status.clone());
                println!("-----------------------------------------------------------------");
                let error_msg = format!("Proxy: {} returned HTTP {}: {}", source_name, status, 
                                      &response_text[..response_text.len().min(200)]);
                
                warn!("Proxy HTTP error: {}", error_msg);
                last_error = Some(BrightDataError::ToolError(error_msg));
                
                // Log error metrics for proxy
                let proxy_payload = json!({
                    "url": url,
                    "method": "proxy",
                    "proxy_host": proxy_host,
                    "proxy_port": proxy_port,
                    "error": format!("HTTP {}", status)
                });

                if let Err(e) = BRIGHTDATA_METRICS.log_call(
                    &attempt_id,
                    url,
                    "proxy",
                    "raw",
                    None,
                    proxy_payload,
                    status,
                    response_headers.clone(),
                    &response_text,
                    Some(&format!("Proxy HTTP {} Error", status)),
                    duration.as_millis() as u64,
                    None,
                    None,
                ).await {
                    warn!("Failed to log proxy error metrics: {}", e);
                }
                
                if retry_attempt == max_retries - 1 {
                    return Err(last_error.unwrap());
                }
                continue;
            }

            // SUCCESS - Process response (apply filtering only if DEDUCT_DATA=true)
            let raw_content = response_text;
            let filtered_content = if self.is_data_reduction_enabled() {
                // TODO: Add content filtering logic when DEDUCT_DATA=true
                raw_content.clone()
            } else {
                raw_content.clone()
            };

            info!("๐Ÿ“Š Proxy: Content processed: {} bytes -> {} bytes", 
                  raw_content.len(), filtered_content.len());

            // Log metrics (using a simplified payload for proxy requests)
            let proxy_payload = json!({
                "url": url,
                "method": "proxy",
                "proxy_host": proxy_host,
                "proxy_port": proxy_port
            });

            if let Err(e) = BRIGHTDATA_METRICS.log_call(
                &attempt_id,
                url,
                "proxy",
                "raw",
                None,
                proxy_payload.clone(),
                status,
                response_headers.clone(),
                &raw_content,
                Some(&filtered_content),
                duration.as_millis() as u64,
                None,
                None,
            ).await {
                warn!("Failed to log proxy metrics: {}", e);
            }

            return Ok(json!({
                "content": filtered_content,
                "raw_content": raw_content,
                "query": query,
                "market": market,
                "source": source_name,
                "method": "BrightData Proxy",
                "priority": format!("{:?}", priority),
                "token_budget": token_budget,
                "execution_id": execution_id,
                "sequence": sequence,
                "method_sequence": method_sequence,
                "success": true,
                "url": url,
                "proxy_host": proxy_host,
                "proxy_port": proxy_port,
                "status_code": status,
                "response_size_bytes": raw_content.len(),
                "filtered_size_bytes": filtered_content.len(),
                "duration_ms": duration.as_millis(),
                "timestamp": chrono::Utc::now().to_rfc3339(),
                "retry_attempts": retry_attempt + 1,
                "max_retries": max_retries,
                "payload_used": proxy_payload
            }));
        }

        Err(last_error.unwrap_or_else(|| BrightDataError::ToolError("Proxy: All retry attempts failed".into())))
    }

    fn is_likely_stock_symbol(&self, query: &str) -> bool {
        let clean = query.trim();
        
        if clean.len() < 1 || clean.len() > 15 {
            return false;
        }

        let valid_chars = clean.chars().all(|c| c.is_alphanumeric() || c == '.');
        let has_letters = clean.chars().any(|c| c.is_alphabetic());
        
        valid_chars && has_letters
    }

    /// Test both direct API and proxy connectivity
    pub async fn test_connectivity(&self) -> Result<String, BrightDataError> {
        let test_url = "https://finance.yahoo.com/quote/AAPL/";
        let mut results = Vec::new();
        
        // Test Direct API
        info!("๐Ÿงช Testing Direct BrightData API...");
        match self.try_fetch_url_direct_api(
            test_url, "AAPL", "us", "Yahoo Finance Test", 
            crate::filters::strategy::QueryPriority::High, 1000, 
            "connectivity_test", 0, 0
        ).await {
            Ok(_) => {
                results.push("โœ… Direct API: SUCCESS".to_string());
            }
            Err(e) => {
                results.push(format!("โŒ Direct API: FAILED - {}", e));
            }
        }
        
        // Test Proxy
        info!("๐Ÿงช Testing Proxy method...");
        match self.try_fetch_url_via_proxy(
            test_url, "AAPL", "us", "Yahoo Finance Test", 
            crate::filters::strategy::QueryPriority::High, 1000, 
            "connectivity_test", 0, 1
        ).await {
            Ok(_) => {
                results.push("โœ… Proxy: SUCCESS".to_string());
            }
            Err(e) => {
                results.push(format!("โŒ Proxy: FAILED - {}", e));
            }
        }
        
        Ok(format!("๐Ÿ” Connectivity Test Results:\n{}", results.join("\n")))
    }
}