File size: 24,646 Bytes
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
803
804
805
806
807
808
809
810
811
812
813
814
//! Video Intent Scoring Module v2
//!
//! Lightweight, CPU-efficient intent scoring using:
//! - Jaro-Winkler similarity for better text matching
//! - TF-IDF-like term weighting
//! - Pattern-based intent detection
//! - Heuristic clickbait detection
//!
//! No external ML dependencies - pure Rust implementation

use serde::{Deserialize, Serialize};

/// Video intent categories
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum VideoIntent {
    /// Educational/tutorial content
    Tutorial,
    /// Product/service review
    Review,
    /// News or current events
    News,
    /// Entertainment (music, comedy, etc.)
    Entertainment,
    /// Documentation or conference talk
    Documentation,
    /// Commercial/promotional
    Commercial,
    /// Unknown or mixed
    Unknown,
}

/// Video quality signals
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VideoQualitySignals {
    /// Has detailed description (>100 chars)
    pub has_description: bool,
    /// Has tags/categories
    pub has_tags: bool,
    /// Channel has verified badge or many subscribers
    pub authoritative_source: bool,
    /// Video has appropriate duration for topic
    pub appropriate_duration: bool,
    /// Title matches content (no clickbait)
    pub title_honest: bool,
    /// Has chapters/timestamps
    pub has_chapters: bool,
}

/// Video intent scoring result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoIntentScore {
    /// Overall intent score (0-1)
    pub intent_score: f32,
    /// Relevance to query (0-1)
    pub relevance_score: f32,
    /// Commercial intent (0-1, lower is better for educational)
    pub commercial_score: f32,
    /// Spam/clickbait likelihood (0-1, lower is better)
    pub spam_score: f32,
    /// Detected intent category
    pub intent_category: VideoIntent,
    /// Quality signals
    pub quality_signals: VideoQualitySignals,
    /// Overall quality gate (passes minimum thresholds)
    pub quality_gate: bool,
}

impl Default for VideoIntentScore {
    fn default() -> Self {
        Self {
            intent_score: 0.5,
            relevance_score: 0.5,
            commercial_score: 0.5,
            spam_score: 0.5,
            intent_category: VideoIntent::Unknown,
            quality_signals: VideoQualitySignals::default(),
            quality_gate: false,
        }
    }
}

/// Video intent scorer with optimized algorithms
pub struct VideoIntentScorer {
    /// Query terms for relevance matching
    query_terms: Vec<String>,
    /// Query term weights (TF-IDF-like)
    term_weights: Vec<f32>,
}

impl VideoIntentScorer {
    pub fn new(query: &str) -> Self {
        let terms: Vec<String> = query
            .to_lowercase()
            .split_whitespace()
            .filter(|w| w.len() > 2)
            .map(|s| s.to_string())
            .collect();

        // Calculate term weights (inverse document frequency approximation)
        // Common words get lower weight, specific words get higher weight
        let common_words = [
            "the", "and", "for", "with", "that", "this", "from", "have", "been", "was",
        ];
        let term_weights: Vec<f32> = terms
            .iter()
            .map(|term| {
                if common_words.contains(&term.as_str()) {
                    0.5
                } else if term.len() > 6 {
                    1.5 // Longer, more specific terms
                } else {
                    1.0
                }
            })
            .collect();

        Self {
            query_terms: terms,
            term_weights,
        }
    }

    /// Score a video based on its metadata
    pub fn score(
        &self,
        title: &str,
        description: Option<&str>,
        channel: Option<&str>,
        duration_secs: Option<u32>,
        view_count: Option<u64>,
    ) -> VideoIntentScore {
        let mut score = VideoIntentScore::default();
        let desc = description.unwrap_or("");

        // Detect intent category
        score.intent_category = self.detect_intent(title, desc);

        // Calculate relevance using Jaro-Winkler + term matching
        score.relevance_score = self.calculate_relevance(title, desc);

        // Calculate commercial score
        score.commercial_score = self.calculate_commercial(title, desc, channel.unwrap_or(""));

        // Calculate spam score
        score.spam_score = self.calculate_spam(title, desc);

        // Calculate intent score (combination of relevance and intent match)
        score.intent_score = self.calculate_intent_score(&score);

        // Analyze quality signals
        score.quality_signals = self.analyze_quality_signals(
            title,
            desc,
            channel.unwrap_or(""),
            duration_secs,
            view_count,
        );

        // Determine if video passes quality gate
        score.quality_gate = self.passes_quality_gate(&score);

        score
    }

    /// Detect video intent category from title and description
    fn detect_intent(&self, title: &str, description: &str) -> VideoIntent {
        let text = format!("{} {}", title.to_lowercase(), description.to_lowercase());

        // Weighted keyword scoring for better accuracy
        let intent_keywords: Vec<(&[&str], VideoIntent, f32)> = vec![
            // Tutorial (high weight)
            (
                &[
                    "tutorial",
                    "how to",
                    "guide",
                    "learn",
                    "course",
                    "beginner",
                    "introduction",
                    "basics",
                    "step by step",
                    "walkthrough",
                    "explained",
                    "full course",
                    "complete guide",
                    "from scratch",
                    "getting started",
                    "quick start",
                    "for beginners",
                    "master",
                    "deep dive",
                ][..],
                VideoIntent::Tutorial,
                2.0,
            ),
            // Review
            (
                &[
                    "review",
                    "unboxing",
                    "vs",
                    "comparison",
                    "best",
                    "top 10",
                    "worth it",
                    "honest review",
                    "pros and cons",
                    "tested",
                    "benchmark",
                    "performance",
                    "after using",
                    "long term review",
                ][..],
                VideoIntent::Review,
                1.8,
            ),
            // Documentation/Talk
            (
                &[
                    "documentation",
                    "conference",
                    "keynote",
                    "talk",
                    "presentation",
                    "session",
                    "workshop",
                    "seminar",
                    "lecture",
                    "university",
                    "research",
                ][..],
                VideoIntent::Documentation,
                1.5,
            ),
            // News
            (
                &[
                    "breaking",
                    "news",
                    "update",
                    "announced",
                    "released",
                    "just in",
                    "today",
                    "latest",
                    "new",
                    "coming soon",
                    "just released",
                ][..],
                VideoIntent::News,
                1.5,
            ),
            // Entertainment
            (
                &[
                    "funny",
                    "comedy",
                    "music video",
                    "official video",
                    "lyrics",
                    "dance",
                    "prank",
                    "challenge",
                    "reaction",
                    "vlog",
                    "entertainment",
                    "meme",
                ][..],
                VideoIntent::Entertainment,
                1.3,
            ),
            // Commercial (detect but don't boost)
            (
                &[
                    "buy now",
                    "discount",
                    "sale",
                    "promo",
                    "sponsor",
                    "affiliate",
                    "link in description",
                    "use code",
                    "limited time",
                ][..],
                VideoIntent::Commercial,
                1.0,
            ),
        ];

        let mut best_intent = VideoIntent::Unknown;
        let mut best_score = 0.0f32;

        for (keywords, intent, weight) in intent_keywords {
            let mut intent_score = 0.0f32;
            for keyword in keywords {
                if text.contains(keyword) {
                    // Bonus for title position
                    if title.to_lowercase().contains(keyword) {
                        intent_score += weight * 1.5;
                    } else {
                        intent_score += weight;
                    }
                }
            }

            if intent_score > best_score {
                best_score = intent_score;
                best_intent = intent;
            }
        }

        // Boost tutorial if query has tutorial intent
        if best_score < 1.0 {
            let query_lower = format!("{:?}", self.query_terms.join(" ")).to_lowercase();
            if (query_lower.contains("tutorial")
                || query_lower.contains("how to")
                || query_lower.contains("learn"))
                && (title.to_lowercase().contains("tutorial")
                    || title.to_lowercase().contains("course"))
            {
                return VideoIntent::Tutorial;
            }
        }

        best_intent
    }

    /// Calculate relevance using Jaro-Winkler + weighted term matching
    fn calculate_relevance(&self, title: &str, description: &str) -> f32 {
        let title_lower = title.to_lowercase();
        let desc_lower = description.to_lowercase();

        if self.query_terms.is_empty() {
            return 0.5;
        }

        let mut total_score = 0.0f32;
        let mut total_weight = 0.0f32;

        for (i, term) in self.query_terms.iter().enumerate() {
            let weight = self.term_weights[i];
            total_weight += weight;

            // Exact match in title (highest score)
            if title_lower.contains(term) {
                total_score += weight * 1.0;
                continue;
            }

            // Jaro-Winkler similarity for fuzzy matching
            let best_title_sim = title_lower
                .split_whitespace()
                .map(|word| jaro_winkler(term, word))
                .fold(0.0f32, f32::max);

            let best_desc_sim = desc_lower
                .split_whitespace()
                .map(|word| jaro_winkler(term, word))
                .fold(0.0f32, f32::max);

            // Threshold for considering it a match
            if best_title_sim > 0.85 {
                total_score += weight * 0.9;
            } else if best_desc_sim > 0.85 {
                total_score += weight * 0.6;
            } else if best_title_sim > 0.7 {
                total_score += weight * 0.5;
            } else if best_desc_sim > 0.7 {
                total_score += weight * 0.3;
            }
        }

        // Base score from weighted term matches
        let mut score = if total_weight > 0.0 {
            total_score / total_weight
        } else {
            0.0
        };

        // Bonus for exact phrase match in title
        let query_phrase = self.query_terms.join(" ");
        if title_lower.contains(&query_phrase) {
            score = (score + 0.3).min(1.0);
        }

        // Bonus for all terms present
        let matched_terms = self
            .query_terms
            .iter()
            .filter(|t| title_lower.contains(*t) || desc_lower.contains(*t))
            .count();

        if matched_terms == self.query_terms.len() {
            score = (score + 0.2).min(1.0);
        }

        score
    }

    /// Calculate commercial intent score
    fn calculate_commercial(&self, title: &str, description: &str, channel: &str) -> f32 {
        let text = format!(
            "{} {} {}",
            title.to_lowercase(),
            description.to_lowercase(),
            channel.to_lowercase()
        );
        let mut score = 0.0f32;

        // Promotional patterns with weights
        let promo_patterns: Vec<(&str, f32)> = vec![
            ("buy now", 0.2),
            ("shop now", 0.2),
            ("discount", 0.15),
            ("sale", 0.15),
            ("promo code", 0.2),
            ("affiliate link", 0.25),
            ("sponsored", 0.3),
            ("use my link", 0.25),
            ("get % off", 0.2),
            ("free trial", 0.15),
            ("sign up", 0.1),
            ("click here", 0.15),
            ("limited time", 0.15),
            ("exclusive offer", 0.2),
            ("deal", 0.1),
            ("coupon", 0.15),
        ];

        for (pattern, weight) in &promo_patterns {
            if text.contains(pattern) {
                score += weight;
            }
        }

        // URL-heavy descriptions (often promotional)
        let url_count = text.matches("http").count();
        if url_count > 5 {
            score += 0.2;
        } else if url_count > 3 {
            score += 0.1;
        }

        // Official channels are less likely to be spam
        if title.to_lowercase().contains("official") || channel.to_lowercase().contains("official")
        {
            score -= 0.1;
        }

        score.clamp(0.0, 1.0)
    }

    /// Calculate spam/clickbait score using heuristic patterns
    fn calculate_spam(&self, title: &str, description: &str) -> f32 {
        let mut score = 0.0f32;
        let title_lower = title.to_lowercase();

        // Clickbait patterns with severity weights
        let clickbait_patterns: Vec<(&str, f32)> = vec![
            ("you won't believe", 0.3),
            ("shocking", 0.2),
            ("amazing", 0.15),
            ("incredible", 0.15),
            ("this changed everything", 0.25),
            ("goes viral", 0.2),
            ("everyone is talking", 0.2),
            ("must watch", 0.15),
            ("mind blowing", 0.25),
            ("life changing", 0.25),
            ("they don't want you to know", 0.3),
            ("one weird trick", 0.35),
            ("number ", 0.05),
            ("reasons why", 0.1),
        ];

        for (pattern, weight) in &clickbait_patterns {
            if title_lower.contains(pattern) {
                score += weight;
            }
        }

        // ALL CAPS title (spam signal) - only if significant length
        let alpha_chars: String = title.chars().filter(|c| c.is_alphabetic()).collect();
        if alpha_chars.len() > 10 && alpha_chars.to_uppercase() == alpha_chars {
            score += 0.2;
        }

        // Excessive punctuation
        let exclaim_count = title.matches('!').count();
        let question_count = title.matches('?').count();
        if exclaim_count > 2 {
            score += 0.1 * exclaim_count.min(3) as f32;
        }
        if question_count > 2 {
            score += 0.05 * question_count.min(3) as f32;
        }

        // Excessive emojis (Unicode range check)
        let emoji_count = title
            .chars()
            .filter(|c| *c as u32 > 0x1F000 || (*c as u32 >= 0x2600 && *c as u32 <= 0x27BF))
            .count();
        if emoji_count > 3 {
            score += 0.15;
        }

        // Very short description (low effort)
        if description.len() < 50 && !description.is_empty() {
            score += 0.1;
        }

        // Empty description
        if description.is_empty() {
            score += 0.05;
        }

        score.clamp(0.0, 1.0)
    }

    /// Calculate overall intent score
    fn calculate_intent_score(&self, score: &VideoIntentScore) -> f32 {
        // Weight relevance heavily, penalize commercial and spam
        let base = score.relevance_score * 0.6;
        let commercial_penalty = score.commercial_score * 0.2;
        let spam_penalty = score.spam_score * 0.2;

        let intent_score = base - commercial_penalty - spam_penalty + 0.3;
        intent_score.clamp(0.0, 1.0)
    }

    /// Analyze quality signals
    fn analyze_quality_signals(
        &self,
        title: &str,
        description: &str,
        channel: &str,
        duration_secs: Option<u32>,
        view_count: Option<u64>,
    ) -> VideoQualitySignals {
        VideoQualitySignals {
            has_description: description.len() > 100,
            has_tags: description.contains('#') || description.to_lowercase().contains("tags:"),
            authoritative_source: self.is_authoritative_source(channel, view_count),
            appropriate_duration: self.is_appropriate_duration(title, duration_secs),
            title_honest: self.is_title_honest(title),
            has_chapters: description.contains("0:00")
                || description.to_lowercase().contains("chapters")
                || description.contains("timestamp"),
        }
    }

    /// Check if source is authoritative
    fn is_authoritative_source(&self, channel: &str, view_count: Option<u64>) -> bool {
        // Known authoritative channels
        let authoritative_channels = [
            "freecodecamp",
            "simplilearn",
            "edureka",
            "coursera",
            "udemy",
            "mit",
            "stanford",
            "harvard",
            "nasa",
            "national geographic",
            "veritasium",
            "3blue1brown",
            "computerphile",
            "fireship",
            "google developers",
            "microsoft developer",
            "aws",
            "azure",
        ];

        let channel_lower = channel.to_lowercase();
        if authoritative_channels
            .iter()
            .any(|c| channel_lower.contains(c))
        {
            return true;
        }

        // High view count indicates popularity
        if let Some(views) = view_count {
            if views > 100_000 {
                return true;
            }
        }

        false
    }

    /// Check if duration is appropriate for the content type
    fn is_appropriate_duration(&self, title: &str, duration_secs: Option<u32>) -> bool {
        let Some(duration) = duration_secs else {
            return false;
        };

        let title_lower = title.to_lowercase();

        // Tutorial should be longer
        if title_lower.contains("tutorial")
            || title_lower.contains("course")
            || title_lower.contains("full")
        {
            return duration >= 300; // At least 5 minutes
        }

        // Quick tips should be shorter
        if title_lower.contains("quick")
            || title_lower.contains("tips")
            || title_lower.contains("short")
        {
            return (60..=600).contains(&duration); // 1-10 minutes
        }

        // Default: reasonable video length
        (60..=14400).contains(&duration) // 1 minute to 4 hours
    }

    /// Check if title appears honest (not clickbait)
    fn is_title_honest(&self, title: &str) -> bool {
        let title_lower = title.to_lowercase();

        // Honest title indicators
        let honest_patterns = [
            "introduction to",
            "getting started",
            "basics of",
            "how to",
            "tutorial",
            "guide to",
            "explained",
            "complete",
            "comprehensive",
            "step by step",
        ];

        // Clickbait indicators
        let clickbait_patterns = [
            "you won't believe",
            "shocking",
            "secret",
            "they don't want",
            "one weird trick",
            "miracle",
            "instant",
            "amazing",
        ];

        let honest_count = honest_patterns
            .iter()
            .filter(|p| title_lower.contains(*p))
            .count();
        let clickbait_count = clickbait_patterns
            .iter()
            .filter(|p| title_lower.contains(*p))
            .count();

        honest_count > clickbait_count
    }

    /// Check if video passes quality gate
    fn passes_quality_gate(&self, score: &VideoIntentScore) -> bool {
        // Minimum thresholds
        let min_intent = 0.3;
        let min_relevance = 0.25;
        let max_spam = 0.7;

        score.intent_score >= min_intent
            && score.relevance_score >= min_relevance
            && score.spam_score <= max_spam
    }
}

/// Jaro-Winkler similarity implementation
/// Returns a score between 0.0 and 1.0
/// Optimized for short strings (titles, terms)
fn jaro_winkler(s1: &str, s2: &str) -> f32 {
    if s1.is_empty() && s2.is_empty() {
        return 1.0;
    }
    if s1.is_empty() || s2.is_empty() {
        return 0.0;
    }
    if s1 == s2 {
        return 1.0;
    }

    let s1_chars: Vec<char> = s1.chars().collect();
    let s2_chars: Vec<char> = s2.chars().collect();

    let len1 = s1_chars.len();
    let len2 = s2_chars.len();

    if len1 == 0 || len2 == 0 {
        return 0.0;
    }

    // Calculate match window
    let match_distance = (len1.max(len2) / 2).saturating_sub(1);

    // Find matches
    let mut s1_matches = vec![false; len1];
    let mut s2_matches = vec![false; len2];
    let mut matches = 0;

    for i in 0..len1 {
        let start = i.saturating_sub(match_distance);
        let end = (i + match_distance + 1).min(len2);

        for j in start..end {
            if s2_matches[j] || s1_chars[i] != s2_chars[j] {
                continue;
            }
            s1_matches[i] = true;
            s2_matches[j] = true;
            matches += 1;
            break;
        }
    }

    if matches == 0 {
        return 0.0;
    }

    // Calculate transpositions
    let mut transpositions = 0;
    let mut j = 0;

    for i in 0..len1 {
        if !s1_matches[i] {
            continue;
        }
        while !s2_matches[j] {
            j += 1;
        }
        if s1_chars[i] != s2_chars[j] {
            transpositions += 1;
        }
        j += 1;
    }

    // Jaro score
    let jaro = (matches as f32 / len1 as f32
        + matches as f32 / len2 as f32
        + (matches - transpositions / 2) as f32 / matches as f32)
        / 3.0;

    // Winkler modification (boost for common prefix)
    let prefix_len = s1_chars
        .iter()
        .zip(s2_chars.iter())
        .take(4)
        .take_while(|(a, b)| a == b)
        .count();

    let winkler = jaro + (prefix_len as f32 * 0.1 * (1.0 - jaro));

    winkler.min(1.0)
}

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

    #[test]
    fn test_jaro_winkler() {
        assert!((jaro_winkler("tutorial", "tutorial") - 1.0).abs() < 0.01);
        assert!(jaro_winkler("tutorial", "tutorials") > 0.9);
        assert!(jaro_winkler("python", "pythn") > 0.8);
        assert!(jaro_winkler("python", "java") < 0.5);
    }

    #[test]
    fn test_detect_tutorial_intent() {
        let scorer = VideoIntentScorer::new("python tutorial");
        let intent = scorer.detect_intent(
            "Python Tutorial for Beginners - Full Course",
            "Learn Python programming from scratch in this complete tutorial.",
        );
        assert_eq!(intent, VideoIntent::Tutorial);
    }

    #[test]
    fn test_detect_review_intent() {
        let scorer = VideoIntentScorer::new("laptop review");
        let intent = scorer.detect_intent(
            "MacBook Pro M3 Review - Is it worth it?",
            "Honest review of the new MacBook Pro with M3 chip. Pros and cons tested.",
        );
        assert_eq!(intent, VideoIntent::Review);
    }

    #[test]
    fn test_relevance_scoring() {
        let scorer = VideoIntentScorer::new("python programming");
        let relevance = scorer.calculate_relevance(
            "Python Programming Tutorial",
            "Learn Python programming from basics",
        );
        assert!(relevance > 0.7);
    }

    #[test]
    fn test_spam_detection() {
        let scorer = VideoIntentScorer::new("make money");
        let spam = scorer.calculate_spam("🔥 YOU WON'T BELIEVE THIS!!! 😱 Make $1000/day!!!", "");
        assert!(spam > 0.5);
    }
}