Skip to main content

oxirs_chat/
message_analytics.rs

1//! Message analytics module for OxiRS Chat
2//!
3//! This module provides analytics capabilities for chat messages including:
4//! - Intent classification
5//! - Sentiment analysis  
6//! - Complexity scoring
7//! - Confidence tracking
8//! - Success metrics
9//! - User satisfaction measurement
10
11use crate::types::Message;
12use anyhow::Result;
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15
16/// Message analytics result
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct MessageAnalytics {
19    pub intent_classification: IntentClassification,
20    pub sentiment_analysis: SentimentAnalysis,
21    pub complexity_score: ComplexityScore,
22    pub confidence_tracking: ConfidenceTracking,
23    pub success_metrics: SuccessMetrics,
24    pub quality_assessment: QualityAssessment,
25}
26
27/// Intent classification results
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct IntentClassification {
30    pub primary_intent: Intent,
31    pub secondary_intents: Vec<Intent>,
32    pub confidence: f32,
33    pub intent_scores: HashMap<String, f32>,
34}
35
36/// Intent types for user messages
37#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub enum Intent {
39    Query,         // User asking a question
40    Exploration,   // User exploring data
41    Learning,      // User learning about concepts
42    Verification,  // User verifying information
43    Comparison,    // User comparing entities
44    Aggregation,   // User requesting summaries/aggregation
45    Navigation,    // User navigating through data
46    Configuration, // User configuring system
47    Feedback,      // User providing feedback
48    Clarification, // User asking for clarification
49    Unknown,       // Intent cannot be determined
50}
51
52/// Sentiment analysis results
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct SentimentAnalysis {
55    pub overall_sentiment: Sentiment,
56    pub sentiment_score: f32, // -1.0 (negative) to 1.0 (positive)
57    pub emotion_indicators: Vec<EmotionIndicator>,
58    pub confidence: f32,
59}
60
61/// Sentiment types
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub enum Sentiment {
64    Positive,
65    Neutral,
66    Negative,
67    Mixed,
68}
69
70/// Emotion indicators
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct EmotionIndicator {
73    pub emotion: Emotion,
74    pub intensity: f32, // 0.0 to 1.0
75    pub indicators: Vec<String>,
76}
77
78/// Emotion types
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub enum Emotion {
81    Frustration,
82    Satisfaction,
83    Curiosity,
84    Confusion,
85    Excitement,
86    Impatience,
87    Appreciation,
88}
89
90/// Complexity scoring
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct ComplexityScore {
93    pub overall_complexity: ComplexityLevel,
94    pub complexity_score: f32, // 0.0 (simple) to 1.0 (complex)
95    pub complexity_factors: Vec<ComplexityFactor>,
96    pub readability_score: f32,
97}
98
99/// Complexity levels
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub enum ComplexityLevel {
102    Simple,
103    Moderate,
104    Complex,
105    VeryComplex,
106}
107
108/// Factors contributing to complexity
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct ComplexityFactor {
111    pub factor_type: ComplexityFactorType,
112    pub contribution: f32,
113    pub description: String,
114}
115
116/// Types of complexity factors
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub enum ComplexityFactorType {
119    VocabularyComplexity,
120    SyntacticComplexity,
121    ConceptualComplexity,
122    QueryComplexity,
123    DomainSpecificity,
124    AmbiguityLevel,
125}
126
127/// Confidence tracking for responses
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct ConfidenceTracking {
130    pub overall_confidence: f32,
131    pub confidence_components: Vec<ConfidenceComponent>,
132    pub uncertainty_indicators: Vec<UncertaintyIndicator>,
133    pub confidence_trend: ConfidenceTrend,
134}
135
136/// Components contributing to confidence
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct ConfidenceComponent {
139    pub component_type: ConfidenceComponentType,
140    pub score: f32,
141    pub weight: f32,
142    pub explanation: String,
143}
144
145/// Types of confidence components
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub enum ConfidenceComponentType {
148    DataQuality,
149    SourceReliability,
150    QueryCoverage,
151    ContextCompleteness,
152    MethodReliability,
153    PreviousSuccess,
154}
155
156/// Uncertainty indicators
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct UncertaintyIndicator {
159    pub indicator_type: UncertaintyType,
160    pub severity: f32,
161    pub description: String,
162    pub mitigation_suggestions: Vec<String>,
163}
164
165/// Types of uncertainty
166#[derive(Debug, Clone, Serialize, Deserialize)]
167pub enum UncertaintyType {
168    DataIncomplete,
169    AmbiguousQuery,
170    ConflictingInformation,
171    OutdatedInformation,
172    LowSampleSize,
173    MethodLimitations,
174}
175
176/// Confidence trend over conversation
177#[derive(Debug, Clone, Serialize, Deserialize)]
178pub enum ConfidenceTrend {
179    Increasing,
180    Stable,
181    Decreasing,
182    Fluctuating,
183}
184
185/// Success metrics for responses
186#[derive(Debug, Clone, Serialize, Deserialize)]
187pub struct SuccessMetrics {
188    pub task_completion_rate: f32,
189    pub user_satisfaction_predicted: f32,
190    pub response_relevance: f32,
191    pub response_completeness: f32,
192    pub response_accuracy: f32,
193    pub follow_up_indicators: Vec<FollowUpIndicator>,
194}
195
196/// Indicators of likely follow-up questions
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct FollowUpIndicator {
199    pub indicator_type: FollowUpType,
200    pub likelihood: f32,
201    pub suggested_questions: Vec<String>,
202}
203
204/// Types of follow-up questions
205#[derive(Debug, Clone, Serialize, Deserialize)]
206pub enum FollowUpType {
207    Clarification,
208    Elaboration,
209    RelatedQuery,
210    Verification,
211    Comparison,
212    NextStep,
213}
214
215/// Quality assessment of messages
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct QualityAssessment {
218    pub clarity_score: f32,
219    pub helpfulness_score: f32,
220    pub accuracy_score: f32,
221    pub completeness_score: f32,
222    pub relevance_score: f32,
223    pub quality_issues: Vec<QualityIssue>,
224}
225
226/// Quality issues identified
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct QualityIssue {
229    pub issue_type: QualityIssueType,
230    pub severity: QualityIssueSeverity,
231    pub description: String,
232    pub suggestions: Vec<String>,
233}
234
235/// Types of quality issues
236#[derive(Debug, Clone, Serialize, Deserialize)]
237pub enum QualityIssueType {
238    Ambiguity,
239    Incompleteness,
240    Inconsistency,
241    IrrelevantInformation,
242    TechnicalJargon,
243    MissingContext,
244    PoorStructure,
245}
246
247/// Severity of quality issues
248#[derive(Debug, Clone, Serialize, Deserialize)]
249pub enum QualityIssueSeverity {
250    Low,
251    Medium,
252    High,
253    Critical,
254}
255
256/// Message analytics engine
257pub struct MessageAnalyticsEngine {
258    intent_classifier: IntentClassifier,
259    sentiment_analyzer: SentimentAnalyzer,
260    complexity_scorer: ComplexityScorer,
261    confidence_tracker: ConfidenceTracker,
262    success_evaluator: SuccessEvaluator,
263    quality_assessor: QualityAssessor,
264}
265
266impl MessageAnalyticsEngine {
267    /// Create a new message analytics engine
268    pub fn new() -> Self {
269        Self {
270            intent_classifier: IntentClassifier::new(),
271            sentiment_analyzer: SentimentAnalyzer::new(),
272            complexity_scorer: ComplexityScorer::new(),
273            confidence_tracker: ConfidenceTracker::new(),
274            success_evaluator: SuccessEvaluator::new(),
275            quality_assessor: QualityAssessor::new(),
276        }
277    }
278
279    /// Analyze a message and return comprehensive analytics
280    pub async fn analyze_message(
281        &self,
282        message: &Message,
283        context: &[Message],
284        response: Option<&Message>,
285    ) -> Result<MessageAnalytics> {
286        let intent_classification = self.intent_classifier.classify(message, context).await?;
287        let sentiment_analysis = self.sentiment_analyzer.analyze(message).await?;
288        let complexity_score = self.complexity_scorer.score(message).await?;
289        let confidence_tracking = self.confidence_tracker.track(message, response).await?;
290        let success_metrics = self
291            .success_evaluator
292            .evaluate(message, response, context)
293            .await?;
294        let quality_assessment = self.quality_assessor.assess(message, response).await?;
295
296        Ok(MessageAnalytics {
297            intent_classification,
298            sentiment_analysis,
299            complexity_score,
300            confidence_tracking,
301            success_metrics,
302            quality_assessment,
303        })
304    }
305
306    /// Analyze conversation trends
307    pub async fn analyze_conversation_trends(
308        &self,
309        messages: &[Message],
310    ) -> Result<ConversationTrends> {
311        let mut intent_distribution = HashMap::new();
312        let mut sentiment_progression = Vec::new();
313        let mut complexity_progression = Vec::new();
314        let mut satisfaction_trend = Vec::new();
315
316        for message in messages {
317            let analytics = self.analyze_message(message, &[], None).await?;
318
319            // Track intent distribution
320            let intent_str = format!("{:?}", analytics.intent_classification.primary_intent);
321            *intent_distribution.entry(intent_str).or_insert(0) += 1;
322
323            // Track sentiment progression
324            sentiment_progression.push(analytics.sentiment_analysis.sentiment_score);
325
326            // Track complexity progression
327            complexity_progression.push(analytics.complexity_score.complexity_score);
328
329            // Track satisfaction progression
330            satisfaction_trend.push(analytics.success_metrics.user_satisfaction_predicted);
331        }
332
333        Ok(ConversationTrends {
334            intent_distribution,
335            sentiment_progression,
336            complexity_progression,
337            satisfaction_trend,
338            engagement_metrics: self.calculate_engagement_metrics(messages).await?,
339        })
340    }
341
342    /// Calculate engagement metrics
343    async fn calculate_engagement_metrics(
344        &self,
345        messages: &[Message],
346    ) -> Result<EngagementMetrics> {
347        let total_messages = messages.len();
348        let avg_message_length = messages
349            .iter()
350            .map(|m| m.content.to_text().len())
351            .sum::<usize>() as f32
352            / total_messages as f32;
353
354        let conversation_duration = if messages.len() > 1 {
355            let start = messages
356                .first()
357                .expect("collection validated to be non-empty")
358                .timestamp;
359            let end = messages
360                .last()
361                .expect("collection validated to be non-empty")
362                .timestamp;
363            end.signed_duration_since(start).num_minutes() as f32
364        } else {
365            0.0
366        };
367
368        let response_rate = messages
369            .iter()
370            .filter(|m| matches!(m.role, crate::types::MessageRole::Assistant))
371            .count() as f32
372            / total_messages as f32;
373
374        Ok(EngagementMetrics {
375            total_messages: total_messages as u32,
376            avg_message_length,
377            conversation_duration_minutes: conversation_duration,
378            response_rate,
379            interaction_depth: self.calculate_interaction_depth(messages),
380            topic_coherence: self.calculate_topic_coherence(messages).await?,
381        })
382    }
383
384    fn calculate_interaction_depth(&self, messages: &[Message]) -> f32 {
385        // Simple heuristic: measure how deep the conversation goes
386        // by looking at follow-up patterns and question complexity
387        let follow_up_count = messages
388            .windows(2)
389            .filter(|pair| {
390                matches!(pair[0].role, crate::types::MessageRole::Assistant)
391                    && matches!(pair[1].role, crate::types::MessageRole::User)
392            })
393            .count();
394
395        follow_up_count as f32 / messages.len().max(1) as f32
396    }
397
398    async fn calculate_topic_coherence(&self, messages: &[Message]) -> Result<f32> {
399        // Simplified topic coherence calculation
400        // In practice, this would use topic modeling
401        if messages.len() < 2 {
402            return Ok(1.0);
403        }
404
405        let mut coherence_scores = Vec::new();
406        for window in messages.windows(2) {
407            let similarity = self
408                .calculate_semantic_similarity(
409                    window[0].content.to_text(),
410                    window[1].content.to_text(),
411                )
412                .await?;
413            coherence_scores.push(similarity);
414        }
415
416        Ok(coherence_scores.iter().sum::<f32>() / coherence_scores.len() as f32)
417    }
418
419    async fn calculate_semantic_similarity(&self, text1: &str, text2: &str) -> Result<f32> {
420        // Mock implementation - would use actual embeddings/similarity
421        let common_words = self.get_common_words(text1, text2);
422        let total_words = self.get_unique_words(text1).len() + self.get_unique_words(text2).len();
423
424        if total_words == 0 {
425            Ok(0.0)
426        } else {
427            Ok(2.0 * common_words as f32 / total_words as f32)
428        }
429    }
430
431    fn get_common_words(&self, text1: &str, text2: &str) -> usize {
432        let words1: std::collections::HashSet<&str> = text1.split_whitespace().collect();
433        let words2: std::collections::HashSet<&str> = text2.split_whitespace().collect();
434        words1.intersection(&words2).count()
435    }
436
437    fn get_unique_words<'a>(&self, text: &'a str) -> std::collections::HashSet<&'a str> {
438        text.split_whitespace().collect()
439    }
440}
441
442/// Conversation trends analysis
443#[derive(Debug, Clone, Serialize, Deserialize)]
444pub struct ConversationTrends {
445    pub intent_distribution: HashMap<String, u32>,
446    pub sentiment_progression: Vec<f32>,
447    pub complexity_progression: Vec<f32>,
448    pub satisfaction_trend: Vec<f32>,
449    pub engagement_metrics: EngagementMetrics,
450}
451
452/// Engagement metrics
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct EngagementMetrics {
455    pub total_messages: u32,
456    pub avg_message_length: f32,
457    pub conversation_duration_minutes: f32,
458    pub response_rate: f32,
459    pub interaction_depth: f32,
460    pub topic_coherence: f32,
461}
462
463// Individual component implementations
464
465/// Intent classifier
466pub struct IntentClassifier {
467    intent_patterns: HashMap<Intent, Vec<String>>,
468}
469
470impl Default for IntentClassifier {
471    fn default() -> Self {
472        Self::new()
473    }
474}
475
476impl IntentClassifier {
477    pub fn new() -> Self {
478        let mut intent_patterns = HashMap::new();
479
480        intent_patterns.insert(
481            Intent::Query,
482            vec![
483                "what".to_string(),
484                "how".to_string(),
485                "why".to_string(),
486                "when".to_string(),
487                "where".to_string(),
488                "which".to_string(),
489            ],
490        );
491
492        intent_patterns.insert(
493            Intent::Exploration,
494            vec![
495                "show me".to_string(),
496                "explore".to_string(),
497                "browse".to_string(),
498                "navigate".to_string(),
499                "discover".to_string(),
500            ],
501        );
502
503        intent_patterns.insert(
504            Intent::Learning,
505            vec![
506                "learn".to_string(),
507                "understand".to_string(),
508                "explain".to_string(),
509                "teach me".to_string(),
510                "how does".to_string(),
511            ],
512        );
513
514        Self { intent_patterns }
515    }
516
517    pub async fn classify(
518        &self,
519        message: &Message,
520        _context: &[Message],
521    ) -> Result<IntentClassification> {
522        let text = message.content.to_text().to_lowercase();
523        let mut intent_scores = HashMap::new();
524
525        // Simple pattern matching for intent classification
526        for (intent, patterns) in &self.intent_patterns {
527            let mut score = 0.0;
528            for pattern in patterns {
529                if text.contains(pattern) {
530                    score += 1.0;
531                }
532            }
533            score /= patterns.len() as f32;
534            intent_scores.insert(format!("{intent:?}"), score);
535        }
536
537        // Find primary intent
538        let primary_intent = intent_scores
539            .iter()
540            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
541            .map(|(intent, _)| match intent.as_str() {
542                "Query" => Intent::Query,
543                "Exploration" => Intent::Exploration,
544                "Learning" => Intent::Learning,
545                _ => Intent::Unknown,
546            })
547            .unwrap_or(Intent::Unknown);
548
549        let confidence = intent_scores
550            .values()
551            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
552            .unwrap_or(&0.0);
553
554        Ok(IntentClassification {
555            primary_intent,
556            secondary_intents: vec![], // Would be populated with secondary intents
557            confidence: *confidence,
558            intent_scores,
559        })
560    }
561}
562
563/// Sentiment analyzer
564pub struct SentimentAnalyzer {
565    positive_words: Vec<String>,
566    negative_words: Vec<String>,
567}
568
569impl Default for SentimentAnalyzer {
570    fn default() -> Self {
571        Self::new()
572    }
573}
574
575impl SentimentAnalyzer {
576    pub fn new() -> Self {
577        Self {
578            positive_words: vec![
579                "good".to_string(),
580                "great".to_string(),
581                "excellent".to_string(),
582                "helpful".to_string(),
583                "useful".to_string(),
584                "thanks".to_string(),
585            ],
586            negative_words: vec![
587                "bad".to_string(),
588                "terrible".to_string(),
589                "useless".to_string(),
590                "frustrated".to_string(),
591                "confused".to_string(),
592                "wrong".to_string(),
593            ],
594        }
595    }
596
597    pub async fn analyze(&self, message: &Message) -> Result<SentimentAnalysis> {
598        let text = message.content.to_text().to_lowercase();
599        let words: Vec<&str> = text.split_whitespace().collect();
600
601        let mut positive_count = 0;
602        let mut negative_count = 0;
603
604        for word in &words {
605            if self.positive_words.contains(&word.to_string()) {
606                positive_count += 1;
607            }
608            if self.negative_words.contains(&word.to_string()) {
609                negative_count += 1;
610            }
611        }
612
613        let sentiment_score = if words.is_empty() {
614            0.0
615        } else {
616            (positive_count as f32 - negative_count as f32) / words.len() as f32
617        };
618
619        let overall_sentiment = match sentiment_score {
620            s if s > 0.1 => Sentiment::Positive,
621            s if s < -0.1 => Sentiment::Negative,
622            _ => Sentiment::Neutral,
623        };
624
625        Ok(SentimentAnalysis {
626            overall_sentiment,
627            sentiment_score,
628            emotion_indicators: vec![], // Would be populated with emotion analysis
629            confidence: 0.7,            // Mock confidence
630        })
631    }
632}
633
634/// Complexity scorer
635pub struct ComplexityScorer;
636
637impl Default for ComplexityScorer {
638    fn default() -> Self {
639        Self::new()
640    }
641}
642
643impl ComplexityScorer {
644    pub fn new() -> Self {
645        Self
646    }
647
648    pub async fn score(&self, message: &Message) -> Result<ComplexityScore> {
649        let text = message.content.to_text();
650        let word_count = text.split_whitespace().count();
651        let sentence_count = text.split(['.', '!', '?']).count();
652        let avg_sentence_length = if sentence_count > 0 {
653            word_count as f32 / sentence_count as f32
654        } else {
655            0.0
656        };
657
658        // Simple complexity scoring based on length and structure
659        let complexity_score = (avg_sentence_length / 20.0).min(1.0);
660
661        let overall_complexity = match complexity_score {
662            s if s < 0.3 => ComplexityLevel::Simple,
663            s if s < 0.6 => ComplexityLevel::Moderate,
664            s if s < 0.8 => ComplexityLevel::Complex,
665            _ => ComplexityLevel::VeryComplex,
666        };
667
668        Ok(ComplexityScore {
669            overall_complexity,
670            complexity_score,
671            complexity_factors: vec![], // Would be populated with detailed factors
672            readability_score: 1.0 - complexity_score, // Inverse relationship
673        })
674    }
675}
676
677/// Confidence tracker
678pub struct ConfidenceTracker;
679
680impl Default for ConfidenceTracker {
681    fn default() -> Self {
682        Self::new()
683    }
684}
685
686impl ConfidenceTracker {
687    pub fn new() -> Self {
688        Self
689    }
690
691    pub async fn track(
692        &self,
693        _message: &Message,
694        response: Option<&Message>,
695    ) -> Result<ConfidenceTracking> {
696        let overall_confidence = if response.is_some() {
697            0.8 // Higher confidence if there's a response
698        } else {
699            0.5 // Lower confidence for standalone messages
700        };
701
702        Ok(ConfidenceTracking {
703            overall_confidence,
704            confidence_components: vec![], // Would be populated with detailed components
705            uncertainty_indicators: vec![], // Would be populated with uncertainty analysis
706            confidence_trend: ConfidenceTrend::Stable,
707        })
708    }
709}
710
711/// Success evaluator
712pub struct SuccessEvaluator;
713
714impl Default for SuccessEvaluator {
715    fn default() -> Self {
716        Self::new()
717    }
718}
719
720impl SuccessEvaluator {
721    pub fn new() -> Self {
722        Self
723    }
724
725    pub async fn evaluate(
726        &self,
727        _message: &Message,
728        response: Option<&Message>,
729        _context: &[Message],
730    ) -> Result<SuccessMetrics> {
731        let task_completion_rate = if response.is_some() { 0.9 } else { 0.0 };
732
733        Ok(SuccessMetrics {
734            task_completion_rate,
735            user_satisfaction_predicted: 0.75,
736            response_relevance: 0.8,
737            response_completeness: 0.7,
738            response_accuracy: 0.85,
739            follow_up_indicators: vec![], // Would be populated with follow-up analysis
740        })
741    }
742}
743
744/// Quality assessor
745pub struct QualityAssessor;
746
747impl Default for QualityAssessor {
748    fn default() -> Self {
749        Self::new()
750    }
751}
752
753impl QualityAssessor {
754    pub fn new() -> Self {
755        Self
756    }
757
758    pub async fn assess(
759        &self,
760        message: &Message,
761        _response: Option<&Message>,
762    ) -> Result<QualityAssessment> {
763        let text = message.content.to_text();
764        let clarity_score = if text.len() > 10 { 0.8 } else { 0.4 };
765
766        Ok(QualityAssessment {
767            clarity_score,
768            helpfulness_score: 0.7,
769            accuracy_score: 0.8,
770            completeness_score: 0.75,
771            relevance_score: 0.85,
772            quality_issues: vec![], // Would be populated with quality analysis
773        })
774    }
775}
776
777impl Default for MessageAnalyticsEngine {
778    fn default() -> Self {
779        Self::new()
780    }
781}
782
783#[cfg(test)]
784mod tests {
785    use super::*;
786    use crate::types::{MessageContent, MessageRole};
787
788    #[tokio::test]
789    async fn test_message_analytics_engine() {
790        let engine = MessageAnalyticsEngine::new();
791
792        let message = Message {
793            id: "test".to_string(),
794            role: MessageRole::User,
795            content: MessageContent::Text("What is the capital of France?".to_string()),
796            timestamp: chrono::Utc::now(),
797            metadata: None,
798            thread_id: None,
799            parent_message_id: None,
800            token_count: None,
801            reactions: Vec::new(),
802            attachments: Vec::new(),
803            rich_elements: Vec::new(),
804        };
805
806        let analytics = engine
807            .analyze_message(&message, &[], None)
808            .await
809            .expect("should succeed");
810
811        assert!(matches!(
812            analytics.intent_classification.primary_intent,
813            Intent::Query
814        ));
815        assert!(analytics.sentiment_analysis.sentiment_score >= -1.0);
816        assert!(analytics.sentiment_analysis.sentiment_score <= 1.0);
817        assert!(analytics.complexity_score.complexity_score >= 0.0);
818        assert!(analytics.complexity_score.complexity_score <= 1.0);
819    }
820
821    #[tokio::test]
822    async fn test_intent_classification() {
823        let classifier = IntentClassifier::new();
824
825        let message = Message {
826            id: "test".to_string(),
827            role: MessageRole::User,
828            content: MessageContent::Text("How does this work?".to_string()),
829            timestamp: chrono::Utc::now(),
830            metadata: None,
831            thread_id: None,
832            parent_message_id: None,
833            token_count: None,
834            reactions: Vec::new(),
835            attachments: Vec::new(),
836            rich_elements: Vec::new(),
837        };
838
839        let classification = classifier
840            .classify(&message, &[])
841            .await
842            .expect("should succeed");
843
844        assert!(matches!(
845            classification.primary_intent,
846            Intent::Query | Intent::Learning
847        ));
848        assert!(classification.confidence > 0.0);
849    }
850
851    #[tokio::test]
852    async fn test_sentiment_analysis() {
853        let analyzer = SentimentAnalyzer::new();
854
855        let positive_message = Message {
856            id: "test".to_string(),
857            role: MessageRole::User,
858            content: MessageContent::Text("This is great and very helpful!".to_string()),
859            timestamp: chrono::Utc::now(),
860            metadata: None,
861            thread_id: None,
862            parent_message_id: None,
863            token_count: None,
864            reactions: Vec::new(),
865            attachments: Vec::new(),
866            rich_elements: Vec::new(),
867        };
868
869        let sentiment = analyzer
870            .analyze(&positive_message)
871            .await
872            .expect("should succeed");
873
874        assert!(matches!(sentiment.overall_sentiment, Sentiment::Positive));
875        assert!(sentiment.sentiment_score > 0.0);
876    }
877}