File size: 24,661 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584a26b
 
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584a26b
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584a26b
 
 
 
 
 
 
 
 
 
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Configuration module for IntentForge v2
//!
//! Handles loading and managing application configuration from YAML files
//! and environment variables.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Main application configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub meilisearch: MeilisearchConfig,
    pub qdrant: QdrantConfig,
    pub redis: RedisConfig,
    pub crawler: CrawlerConfig,
    pub indexer: IndexerConfig,
    pub trending: TrendingConfig,
    pub discovery: DiscoveryConfig,
    pub logging: LoggingConfig,
    pub extraction: ExtractionConfig,
    pub inference: InferenceConfig,
    #[serde(default)]
    pub anti_detection: AntiDetectionConfig,
    #[serde(default)]
    pub self_improvement: SelfImprovementConfig,
    #[serde(default = "default_whoogle_url")]
    pub whoogle_url: String,
    #[serde(default = "default_librex_url")]
    pub librex_url: String,
    #[serde(default = "default_searxng_url")]
    pub searxng_url: String,
    #[serde(default = "default_query_layer_url")]
    pub query_layer_url: String,
    #[serde(default)]
    pub video_discovery: VideoDiscoveryConfig,
    #[serde(default)]
    pub image_search: ImageSearchConfig,
    pub api_key: Option<String>,
}

/// Meilisearch configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeilisearchConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    pub url: String,
    pub master_key: String,
    pub index_name: String,
    #[serde(default = "default_binary_quantization")]
    pub binary_quantization: bool,
    #[serde(default = "default_semantic_ratio")]
    pub semantic_ratio: f32,
    #[serde(default = "default_task_timeout")]
    pub task_timeout_secs: u64,
    #[serde(default = "default_true")]
    pub redis_cache_enabled: bool,
    #[serde(default = "default_search_cache_ttl")]
    pub redis_cache_ttl_secs: u64,
}

/// Qdrant configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QdrantConfig {
    pub url: String,
    pub api_key: Option<String>,
    #[serde(default = "default_qdrant_collection")]
    pub collection_name: String,
}

fn default_qdrant_collection() -> String {
    "intentforge".to_string()
}

fn default_search_cache_ttl() -> u64 {
    3600 // 1 hour
}

/// Redis configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedisConfig {
    pub url: String,
    #[serde(default = "default_bloom_fp_rate")]
    pub bloom_fp_rate: f64,
    #[serde(default = "default_simhash_threshold")]
    pub simhash_threshold: u8,
}

/// Crawler configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlerConfig {
    #[serde(default = "default_rate_limit")]
    pub rate_limit: u32,
    #[serde(default = "default_max_concurrent")]
    pub max_concurrent: usize,
    #[serde(default = "default_timeout_secs")]
    pub timeout_secs: u64,
    #[serde(default = "default_user_agent")]
    pub user_agent: String,
    #[serde(default = "default_true")]
    pub respect_robots: bool,
    #[serde(default = "default_true")]
    pub static_first: bool,
    #[serde(default = "default_max_retries")]
    pub max_retries: u32,
    #[serde(default = "default_robots_cache_ttl")]
    pub robots_cache_ttl_secs: u64,
    #[serde(default)]
    pub js_whitelist: Vec<String>,
}

/// Indexer configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexerConfig {
    #[serde(default = "default_batch_size")]
    pub inference_batch_size: usize,
    #[serde(default = "default_min_content_length")]
    pub min_content_length: usize,
    #[serde(default = "default_snippet_length")]
    pub snippet_length: usize,
}

/// Trending monitor configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendingConfig {
    #[serde(default = "default_refresh_interval")]
    pub refresh_interval: u64,
    #[serde(default = "default_top_n")]
    pub top_n: usize,
}

/// Discovery service configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveryConfig {
    #[serde(default = "default_discovery_interval")]
    pub interval_secs: u64,
    #[serde(default = "default_max_queue_size")]
    pub max_queue_size: usize,
    #[serde(default = "default_true")]
    pub follow_links: bool,
    #[serde(default = "default_link_threshold")]
    pub link_threshold: f32,
    #[serde(default)]
    pub common_crawl_delta: Option<CommonCrawlDeltaConfig>,
}

/// Common Crawl delta automation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommonCrawlDeltaConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_cc_delta_interval")]
    pub interval_secs: u64,
    #[serde(default = "default_cc_crawl_id")]
    pub crawl_id: String,
    #[serde(default)]
    pub domains: Vec<String>,
    #[serde(default = "default_cc_max_entries")]
    pub max_entries_per_domain: usize,
    #[serde(default = "default_cc_data_dir")]
    pub data_dir: String,
    #[serde(default = "default_cc_quality_threshold")]
    pub quality_threshold: f32,
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    #[serde(default = "default_log_level")]
    pub level: String,
    #[serde(default = "default_log_format")]
    pub format: String,
}

/// Trafilatura extraction configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractionConfig {
    #[serde(default = "default_trafilatura_url")]
    pub trafilatura_url: String,
    #[serde(default = "default_extract_batch_size")]
    pub batch_size: usize,
    #[serde(default = "default_extract_timeout")]
    pub timeout_secs: u64,
}

/// ONNX inference configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferenceConfig {
    #[serde(default = "default_model_path")]
    pub model_path: String,
    #[serde(default = "default_inference_batch_size")]
    pub inference_batch_size: usize,
    #[serde(default = "default_embedding_dim")]
    pub embedding_dim: usize,
    #[serde(default = "default_max_seq_length")]
    pub max_seq_length: usize,
    /// Threshold for the fast keyword-based intent scorer (0.0 - 1.0)
    #[serde(default = "default_fast_intent_threshold")]
    pub fast_intent_threshold: f32,
}

/// Anti-detection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AntiDetectionConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_rotation_interval")]
    pub rotation_interval: u32,
    #[serde(default = "default_true")]
    pub use_client_hints: bool,
    #[serde(default)]
    pub invidious_instances: Vec<String>,
    pub stackoverflow_api_key: Option<String>,
    pub pubmed_api_key: Option<String>,
    pub semantic_scholar_api_key: Option<String>,
}

/// Video discovery configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoDiscoveryConfig {
    #[serde(default = "default_ytdlp_path")]
    pub ytdlp_path: String,
    #[serde(default = "default_ytdlp_update_interval")]
    pub ytdlp_update_interval_hours: u64,
    #[serde(default)]
    pub piped_instances: Vec<String>,
    #[serde(default)]
    pub invidious_instances: Vec<String>,
    #[serde(default)]
    pub youtube_api_key: Option<String>,
    #[serde(default)]
    pub rapidapi_key: Option<String>,
    #[serde(default = "default_video_sources")]
    pub enabled_sources: Vec<String>,
    #[serde(default = "default_video_search_limit")]
    pub search_limit: usize,
    #[serde(default = "default_video_cache_ttl")]
    pub cache_ttl_secs: u64,
}

impl Default for VideoDiscoveryConfig {
    fn default() -> Self {
        Self {
            ytdlp_path: default_ytdlp_path(),
            ytdlp_update_interval_hours: default_ytdlp_update_interval(),
            piped_instances: vec![
                "https://pipedapi.kavin.rocks".to_string(),
                "https://pipedapi.adminforge.de".to_string(),
                "https://api.piped.yt".to_string(),
                "https://pipedapi.leptonsh.top".to_string(),
                "https://piped.qiangdai.cn".to_string(),
            ],
            invidious_instances: vec![
                "https://invidious.nerdvpn.de".to_string(),
                "https://inv.tux.pizza".to_string(),
                "https://yewtu.be".to_string(),
            ],
            youtube_api_key: std::env::var("YOUTUBE_API_KEY").ok(),
            rapidapi_key: std::env::var("RAPIDAPI_KEY").ok(),
            enabled_sources: default_video_sources(),
            search_limit: default_video_search_limit(),
            cache_ttl_secs: default_video_cache_ttl(),
        }
    }
}

/// External image search API configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageSearchConfig {
    #[serde(default)]
    pub pixabay_api_key: Option<String>,
    #[serde(default)]
    pub pexels_api_key: Option<String>,
    #[serde(default = "default_image_search_limit")]
    pub search_limit: usize,
    #[serde(default = "default_image_cache_ttl")]
    pub cache_ttl_secs: u64,
}

impl Default for ImageSearchConfig {
    fn default() -> Self {
        Self {
            pixabay_api_key: std::env::var("PIXABAY_API_KEY").ok(),
            pexels_api_key: std::env::var("PEXELS_API_KEY").ok(),
            search_limit: default_image_search_limit(),
            cache_ttl_secs: default_image_cache_ttl(),
        }
    }
}

/// Self-improvement configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SelfImprovementConfig {
    #[serde(default = "default_self_imp_enabled")]
    pub enabled: bool,
    #[serde(default = "default_min_gap_score")]
    pub min_gap_score: f32,
    #[serde(default = "default_max_results_per_query")]
    pub max_results_per_query: usize,
    #[serde(default = "default_process_interval")]
    pub process_interval_secs: u64,
    /// Maximum number of gap queries to process concurrently
    #[serde(default = "default_max_parallel_gaps")]
    pub max_parallel_gaps: usize,
    /// Minimum number of quality URLs to index before considering a gap filled
    #[serde(default = "default_min_urls_per_gap")]
    pub min_urls_per_gap: usize,
    /// Minimum intent score (cosine similarity) for a URL to count as quality
    #[serde(default = "default_min_intent_score")]
    pub min_intent_score: f32,
    /// Minimum relevance score for a URL to count as quality
    #[serde(default = "default_min_relevance_score")]
    pub min_relevance_score: f32,
    /// Maximum rounds of meta-search queries to try per gap
    #[serde(default = "default_max_search_rounds")]
    pub max_search_rounds: usize,
}

// Default value functions
fn default_binary_quantization() -> bool {
    true
}
fn default_semantic_ratio() -> f32 {
    0.7
}
fn default_task_timeout() -> u64 {
    60
}
fn default_bloom_fp_rate() -> f64 {
    0.01
}
fn default_simhash_threshold() -> u8 {
    3
}
fn default_rate_limit() -> u32 {
    10
}
fn default_max_concurrent() -> usize {
    8
}
fn default_timeout_secs() -> u64 {
    30
}
fn default_user_agent() -> String {
    "IntentForge/0.1 (Intent Discovery Engine)".to_string()
}
fn default_true() -> bool {
    true
}
fn default_batch_size() -> usize {
    32
}
fn default_min_content_length() -> usize {
    100
}
fn default_snippet_length() -> usize {
    200
}
fn default_refresh_interval() -> u64 {
    300
}
fn default_top_n() -> usize {
    50
}
fn default_discovery_interval() -> u64 {
    3600
}
fn default_max_queue_size() -> usize {
    10000
}
fn default_link_threshold() -> f32 {
    0.8
}
fn default_log_level() -> String {
    "info".to_string()
}
fn default_log_format() -> String {
    "json".to_string()
}
fn default_max_retries() -> u32 {
    3
}
fn default_robots_cache_ttl() -> u64 {
    3600
}
fn default_trafilatura_url() -> String {
    "http://localhost:8080".to_string()
}
fn default_extract_batch_size() -> usize {
    16
}
fn default_extract_timeout() -> u64 {
    60
}
fn default_model_path() -> String {
    "models/all-MiniLM-L6-v2.onnx".to_string()
}
fn default_inference_batch_size() -> usize {
    32
}
fn default_embedding_dim() -> usize {
    384
}
fn default_max_seq_length() -> usize {
    128
}
fn default_fast_intent_threshold() -> f32 {
    0.4
}
fn default_cc_delta_interval() -> u64 {
    2592000 // 30 days
}
fn default_cc_crawl_id() -> String {
    "CC-MAIN-2025-08".to_string() // latest CC crawl as of 2026-03
}
fn default_cc_max_entries() -> usize {
    100
}
fn default_cc_data_dir() -> String {
    "./cc_data".to_string()
}
fn default_cc_quality_threshold() -> f32 {
    0.3
}
fn default_rotation_interval() -> u32 {
    10
}
fn default_self_imp_enabled() -> bool {
    false
}
fn default_min_gap_score() -> f32 {
    0.5
}
fn default_max_results_per_query() -> usize {
    10
}
fn default_process_interval() -> u64 {
    300
}
fn default_max_parallel_gaps() -> usize {
    3
}
fn default_min_urls_per_gap() -> usize {
    25
}
fn default_min_intent_score() -> f32 {
    0.3
}
fn default_min_relevance_score() -> f32 {
    0.3
}
fn default_max_search_rounds() -> usize {
    5
}
fn default_whoogle_url() -> String {
    String::from("http://whoogle:5000")
}
fn default_librex_url() -> String {
    String::from("http://librex:80")
}
fn default_searxng_url() -> String {
    String::from("http://searxng:8080")
}

fn default_query_layer_url() -> String {
    String::from("http://localhost:8000")
}

fn default_ytdlp_path() -> String {
    String::from("yt-dlp")
}

fn default_ytdlp_update_interval() -> u64 {
    12
}

fn default_video_sources() -> Vec<String> {
    vec![
        "youtube".to_string(),
        "rapid_youtube".to_string(),
        "piped".to_string(),
        "invidious".to_string(),
        "archive_org".to_string(),
        "dailymotion".to_string(),
        "vimeo".to_string(),
        "odysee".to_string(),
        "yt-dlp".to_string(),
    ]
}

fn default_video_search_limit() -> usize {
    50
}

fn default_video_cache_ttl() -> u64 {
    1800
}

fn default_image_search_limit() -> usize {
    20
}

fn default_image_cache_ttl() -> u64 {
    86400
}

impl Default for AntiDetectionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            rotation_interval: default_rotation_interval(),
            use_client_hints: true,
            invidious_instances: vec![
                "https://invidious.nerdvpn.de".to_string(),
                "https://inv.tux.pizza".to_string(),
                "https://yewtu.be".to_string(),
            ],
            stackoverflow_api_key: None,
            pubmed_api_key: None,
            semantic_scholar_api_key: None,
        }
    }
}

impl Default for SelfImprovementConfig {
    fn default() -> Self {
        Self {
            enabled: default_self_imp_enabled(),
            min_gap_score: default_min_gap_score(),
            max_results_per_query: default_max_results_per_query(),
            process_interval_secs: default_process_interval(),
            max_parallel_gaps: default_max_parallel_gaps(),
            min_urls_per_gap: default_min_urls_per_gap(),
            min_intent_score: default_min_intent_score(),
            min_relevance_score: default_min_relevance_score(),
            max_search_rounds: default_max_search_rounds(),
        }
    }
}

impl Default for CommonCrawlDeltaConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            interval_secs: default_cc_delta_interval(),
            crawl_id: default_cc_crawl_id(),
            domains: vec![
                "github.com".to_string(),
                "arxiv.org".to_string(),
                "news.ycombinator.com".to_string(),
                "stackoverflow.com".to_string(),
            ],
            max_entries_per_domain: default_cc_max_entries(),
            data_dir: default_cc_data_dir(),
            quality_threshold: default_cc_quality_threshold(),
        }
    }
}

impl Config {
    /// Load configuration from a YAML file
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = std::fs::File::open(path.as_ref())
            .with_context(|| format!("Failed to open config file: {:?}", path.as_ref()))?;

        let content =
            std::io::read_to_string(file).with_context(|| "Failed to read config file")?;
        let config: Config =
            toml::from_str(&content).with_context(|| "Failed to parse config TOML")?;

        config.validate()?;
        Ok(config)
    }

    /// Load configuration from default locations
    pub fn load() -> Result<Self> {
        // Try loading from config.yaml in current directory
        let config_path = Path::new("config.yaml");
        if config_path.exists() {
            let mut config = Self::from_file(config_path)?;
            config.apply_env_overrides();
            return Ok(config);
        }

        // Try loading from ../config.yaml
        let config_path = Path::new("../config.yaml");
        if config_path.exists() {
            let mut config = Self::from_file(config_path)?;
            config.apply_env_overrides();
            return Ok(config);
        }

        // Return default configuration
        Self::default_config()
    }

    /// Apply environment variable overrides for Docker networking
    fn apply_env_overrides(&mut self) {
        if let Ok(url) = std::env::var("REDIS_URL") {
            self.redis.url = url;
        }
        if let Ok(url) = std::env::var("MEILI_URL") {
            self.meilisearch.url = url;
        }
        if let Ok(url) = std::env::var("MEILI_MASTER_KEY") {
            self.meilisearch.master_key = url;
        }
        if let Ok(url) = std::env::var("QDRANT_URL") {
            self.qdrant.url = url;
        }
        if let Ok(key) = std::env::var("QDRANT_API_KEY") {
            self.qdrant.api_key = Some(key);
        }
        if let Ok(url) = std::env::var("TRAFILATURA_URL") {
            self.extraction.trafilatura_url = url;
        }
        if let Ok(dir) = std::env::var("CC_DATA_DIR") {
            if let Some(ref mut cc) = self.discovery.common_crawl_delta {
                cc.data_dir = dir;
            }
        }
        if let Ok(url) = std::env::var("WHOOGLE_URL") {
            self.whoogle_url = url;
        }
        if let Ok(url) = std::env::var("LIBREX_URL") {
            self.librex_url = url;
        }
        if let Ok(url) = std::env::var("SEARXNG_URL") {
            self.searxng_url = url;
        }
        if let Ok(url) = std::env::var("QUERY_LAYER_URL") {
            self.query_layer_url = url;
        }
        if let Ok(key) = std::env::var("YOUTUBE_API_KEY") {
            self.video_discovery.youtube_api_key = Some(key);
        }
        if let Ok(key) = std::env::var("RAPIDAPI_KEY") {
            self.video_discovery.rapidapi_key = Some(key);
        }
        if let Ok(key) = std::env::var("PIXABAY_API_KEY") {
            self.image_search.pixabay_api_key = Some(key);
        }
        if let Ok(key) = std::env::var("PEXELS_API_KEY") {
            self.image_search.pexels_api_key = Some(key);
        }
        if let Ok(key) = std::env::var("INTENTFORGE_API_KEY") {
            self.api_key = Some(key);
        }
    }

    /// Create a default configuration
    pub fn default_config() -> Result<Self> {
        let config = Config {
            meilisearch: MeilisearchConfig {
                enabled: true,
                url: "http://localhost:7700".to_string(),
                master_key: "masterKey".to_string(),
                index_name: "intentforge".to_string(),
                binary_quantization: true,
                semantic_ratio: 0.7,
                task_timeout_secs: 60,
                redis_cache_enabled: true,
                redis_cache_ttl_secs: 3600,
            },
            qdrant: QdrantConfig {
                url: "http://localhost:6334".to_string(),
                api_key: None,
                collection_name: "intentforge".to_string(),
            },
            redis: RedisConfig {
                url: "redis://localhost:6379".to_string(),
                bloom_fp_rate: 0.01,
                simhash_threshold: 3,
            },
            crawler: CrawlerConfig {
                rate_limit: 10,
                max_concurrent: 8,
                timeout_secs: 30,
                user_agent: "IntentForge/0.1 (Intent Discovery Engine)".to_string(),
                respect_robots: true,
                static_first: true,
                max_retries: 3,
                robots_cache_ttl_secs: 3600,
                js_whitelist: vec![
                    "producthunt.com".to_string(),
                    "news.ycombinator.com".to_string(),
                ],
            },
            indexer: IndexerConfig {
                inference_batch_size: 32,
                min_content_length: 100,
                snippet_length: 200,
            },
            trending: TrendingConfig {
                refresh_interval: 300,
                top_n: 50,
            },
            discovery: DiscoveryConfig {
                interval_secs: 3600,
                max_queue_size: 10000,
                follow_links: true,
                link_threshold: 0.8,
                common_crawl_delta: Some(CommonCrawlDeltaConfig::default()),
            },
            logging: LoggingConfig {
                level: "info".to_string(),
                format: "json".to_string(),
            },
            extraction: ExtractionConfig {
                trafilatura_url: "http://localhost:8080".to_string(),
                batch_size: 16,
                timeout_secs: 60,
            },
            inference: InferenceConfig {
                model_path: "models/all-MiniLM-L6-v2.onnx".to_string(),
                inference_batch_size: 32,
                embedding_dim: 384,
                max_seq_length: 128,
                fast_intent_threshold: 0.4,
            },
            anti_detection: AntiDetectionConfig::default(),
            self_improvement: SelfImprovementConfig::default(),
            whoogle_url: default_whoogle_url(),
            librex_url: default_librex_url(),
            searxng_url: default_searxng_url(),
            query_layer_url: default_query_layer_url(),
            video_discovery: VideoDiscoveryConfig::default(),
            image_search: ImageSearchConfig::default(),
            api_key: std::env::var("INTENTFORGE_API_KEY").ok(),
        };

        config.validate()?;
        Ok(config)
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<()> {
        if self.meilisearch.enabled {
            anyhow::ensure!(
                !self.meilisearch.url.is_empty(),
                "Meilisearch URL cannot be empty when enabled"
            );
            anyhow::ensure!(
                !self.meilisearch.master_key.is_empty(),
                "Meilisearch master key cannot be empty when enabled"
            );
        }
        anyhow::ensure!(!self.qdrant.url.is_empty(), "Qdrant URL cannot be empty");
        anyhow::ensure!(!self.redis.url.is_empty(), "Redis URL cannot be empty");
        anyhow::ensure!(
            self.crawler.rate_limit > 0,
            "Crawler rate limit must be positive"
        );
        anyhow::ensure!(
            self.indexer.inference_batch_size > 0,
            "Inference batch size must be positive"
        );
        anyhow::ensure!(
            self.inference.embedding_dim > 0,
            "Embedding dimension must be positive"
        );
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = Config::default_config().unwrap();
        assert_eq!(config.meilisearch.index_name, "intentforge");
        assert!(config.meilisearch.binary_quantization);
        assert_eq!(config.meilisearch.semantic_ratio, 0.7);
    }

    #[test]
    fn test_default_js_whitelist() {
        let config = Config::default_config().unwrap();
        assert!(config
            .crawler
            .js_whitelist
            .contains(&"producthunt.com".to_string()));
    }

    #[test]
    fn test_extraction_defaults() {
        let config = Config::default_config().unwrap();
        assert_eq!(config.extraction.trafilatura_url, "http://localhost:8080");
        assert_eq!(config.extraction.batch_size, 16);
    }

    #[test]
    fn test_inference_defaults() {
        let config = Config::default_config().unwrap();
        assert_eq!(config.inference.embedding_dim, 384);
        assert_eq!(config.inference.inference_batch_size, 32);
        assert_eq!(config.inference.max_seq_length, 128);
    }
}