pmat 2.93.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
//! Team onboarding materials and tutorials for unified quality system
//!
//! Provides interactive tutorials, onboarding guides, and training materials

use crate::unified_quality::{QualityMode, QualityPhilosophy};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Team onboarding system for progressive quality adoption
#[allow(dead_code)]
pub struct TeamOnboarding {
    /// Current onboarding sessions
    sessions: HashMap<TeamId, OnboardingSession>,

    /// Tutorial materials
    tutorials: TutorialLibrary,

    /// Configuration
    config: OnboardingConfig,
}

/// Team identifier
pub type TeamId = String;

/// Onboarding session state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnboardingSession {
    /// Team information
    pub team_id: TeamId,

    /// Current phase in onboarding
    pub current_phase: OnboardingPhase,

    /// Completed tutorials
    pub completed_tutorials: Vec<String>,

    /// Quality mode progression
    pub quality_mode: QualityMode,

    /// Start date
    pub started_at: std::time::SystemTime,

    /// Progress tracking
    pub progress: OnboardingProgress,

    /// Team preferences
    pub preferences: TeamPreferences,
}

/// Onboarding phases (Progressive adoption)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum OnboardingPhase {
    /// Introduction to concepts
    Introduction,

    /// Setting up monitoring
    MonitoringSetup,

    /// Understanding metrics
    MetricsLearning,

    /// Enforcement setup
    EnforcementConfig,

    /// Automation configuration
    AutomationSetup,

    /// Advanced features
    AdvancedFeatures,

    /// Graduation to production
    ProductionReady,
}

/// Progress tracking for onboarding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnboardingProgress {
    /// Tutorials completed
    pub tutorials_completed: u32,

    /// Total tutorials available
    pub tutorials_total: u32,

    /// Hands-on exercises completed
    pub exercises_completed: u32,

    /// Quality improvements demonstrated
    pub quality_improvements: u32,

    /// Days since start
    pub days_active: u32,

    /// Engagement score
    pub engagement_score: f64,
}

/// Team preferences and settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamPreferences {
    /// Preferred programming languages
    pub languages: Vec<String>,

    /// Learning style preference
    pub learning_style: LearningStyle,

    /// Notification preferences
    pub notifications: NotificationPreference,

    /// Quality philosophy alignment
    pub philosophy: QualityPhilosophy,

    /// Team size and composition
    pub team_info: TeamInfo,
}

/// Learning style preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LearningStyle {
    /// Hands-on, practical approach
    Practical,

    /// Theoretical understanding first
    Theoretical,

    /// Mixed approach
    Balanced,

    /// Self-paced exploration
    Exploratory,
}

/// Notification preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationPreference {
    /// Daily progress notifications
    pub daily_updates: bool,

    /// Weekly summary reports
    pub weekly_summaries: bool,

    /// Achievement notifications
    pub achievements: bool,

    /// Quality improvement celebrations
    pub celebrations: bool,
}

/// Team information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamInfo {
    /// Team size
    pub size: u32,

    /// Experience level
    pub experience_level: ExperienceLevel,

    /// Primary project type
    pub project_type: ProjectType,

    /// Quality maturity level
    pub quality_maturity: QualityMaturity,
}

/// Experience level
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExperienceLevel {
    Junior,
    Intermediate,
    Senior,
    Mixed,
}

/// Project type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProjectType {
    WebApplication,
    SystemsSoftware,
    DataScience,
    Mobile,
    Library,
    Microservices,
    Monolith,
}

/// Quality maturity level
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum QualityMaturity {
    /// No formal quality processes
    None,

    /// Basic testing in place
    Basic,

    /// CI/CD with some quality gates
    Intermediate,

    /// Comprehensive quality culture
    Advanced,
}

/// Tutorial library
#[derive(Debug, Clone)]
pub struct TutorialLibrary {
    /// Available tutorials by phase
    tutorials: HashMap<OnboardingPhase, Vec<Tutorial>>,
}

/// Individual tutorial
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tutorial {
    /// Unique identifier
    pub id: String,

    /// Human-readable name
    pub name: String,

    /// Description
    pub description: String,

    /// Estimated duration (minutes)
    pub duration_minutes: u32,

    /// Prerequisites
    pub prerequisites: Vec<String>,

    /// Learning objectives
    pub objectives: Vec<String>,

    /// Interactive content
    pub content: TutorialContent,

    /// Hands-on exercises
    pub exercises: Vec<Exercise>,

    /// Success criteria
    pub success_criteria: Vec<String>,
}

/// Tutorial content types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TutorialContent {
    /// Interactive demo
    Demo {
        title: String,
        description: String,
        commands: Vec<String>,
        expected_outputs: Vec<String>,
    },

    /// Guided walkthrough
    Walkthrough { steps: Vec<WalkthroughStep> },

    /// Video content
    Video {
        title: String,
        url: String,
        transcript: Option<String>,
    },

    /// Documentation
    Documentation {
        title: String,
        content: String,
        examples: Vec<String>,
    },
}

/// Walkthrough step
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalkthroughStep {
    /// Step number
    pub step: u32,

    /// Title
    pub title: String,

    /// Instructions
    pub instructions: String,

    /// Commands to run
    pub commands: Vec<String>,

    /// Expected results
    pub expected_results: String,

    /// Tips and troubleshooting
    pub tips: Vec<String>,
}

/// Hands-on exercise
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Exercise {
    /// Exercise name
    pub name: String,

    /// Instructions
    pub instructions: String,

    /// Starting code/files
    pub starting_files: HashMap<String, String>,

    /// Expected outcome
    pub expected_outcome: String,

    /// Validation criteria
    pub validation: Vec<String>,

    /// Hints for completion
    pub hints: Vec<String>,
}

/// Onboarding configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnboardingConfig {
    /// Enable interactive tutorials
    pub interactive_mode: bool,

    /// Personalization enabled
    pub personalization: bool,

    /// Progress tracking enabled
    pub track_progress: bool,

    /// Gamification features
    pub gamification: GamificationConfig,
}

/// Gamification configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GamificationConfig {
    /// Enable achievements
    pub achievements: bool,

    /// Progress badges
    pub badges: bool,

    /// Leaderboards
    pub leaderboards: bool,

    /// Point system
    pub points: bool,
}

impl TeamOnboarding {
    /// Create new onboarding system
    #[must_use] 
    pub fn new(config: OnboardingConfig) -> Self {
        Self {
            sessions: HashMap::new(),
            tutorials: TutorialLibrary::new(),
            config,
        }
    }

    /// Start onboarding for a new team
    pub fn start_onboarding(
        &mut self,
        team_id: TeamId,
        preferences: TeamPreferences,
    ) -> Result<OnboardingSession> {
        let session = OnboardingSession {
            team_id: team_id.clone(),
            current_phase: OnboardingPhase::Introduction,
            completed_tutorials: Vec::new(),
            quality_mode: QualityMode::Observe,
            started_at: std::time::SystemTime::now(),
            progress: OnboardingProgress {
                tutorials_completed: 0,
                tutorials_total: self.tutorials.count_tutorials(),
                exercises_completed: 0,
                quality_improvements: 0,
                days_active: 0,
                engagement_score: 0.0,
            },
            preferences,
        };

        self.sessions.insert(team_id, session.clone());
        Ok(session)
    }

    /// Get personalized tutorial recommendations
    pub fn get_recommendations(&self, team_id: &TeamId) -> Result<Vec<Tutorial>> {
        let session = self
            .sessions
            .get(team_id)
            .ok_or_else(|| anyhow::anyhow!("Team not found: {team_id}"))?;

        let phase_tutorials = self
            .tutorials
            .get_tutorials_for_phase(&session.current_phase);
        let mut recommendations = Vec::new();

        for tutorial in phase_tutorials {
            // Filter based on completed tutorials
            if !session.completed_tutorials.contains(&tutorial.id) {
                // Check prerequisites
                let prerequisites_met = tutorial
                    .prerequisites
                    .iter()
                    .all(|prereq| session.completed_tutorials.contains(prereq));

                if prerequisites_met {
                    recommendations.push(tutorial);
                }
            }
        }

        // Sort by relevance to team preferences
        recommendations.sort_by(|a, b| {
            let relevance_a = self.calculate_relevance(a, &session.preferences);
            let relevance_b = self.calculate_relevance(b, &session.preferences);
            relevance_b
                .partial_cmp(&relevance_a)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Ok(recommendations)
    }

    /// Complete a tutorial and update progress
    pub fn complete_tutorial(
        &mut self,
        team_id: &TeamId,
        tutorial_id: String,
        exercises_completed: u32,
    ) -> Result<()> {
        let needs_update = {
            let session = self
                .sessions
                .get(team_id)
                .ok_or_else(|| anyhow::anyhow!("Team not found: {team_id}"))?;
            !session.completed_tutorials.contains(&tutorial_id)
        };

        if needs_update {
            // Calculate engagement score first to avoid borrow conflicts
            let engagement_score = {
                let session = self
                    .sessions
                    .get(team_id)
                    .ok_or_else(|| anyhow::anyhow!("Team not found: {team_id}"))?;
                // Create temporary session with updated values for score calculation
                let mut temp_session = session.clone();
                temp_session.progress.tutorials_completed += 1;
                temp_session.progress.exercises_completed += exercises_completed;
                self.calculate_engagement_score(&temp_session)
            };

            let session = self
                .sessions
                .get_mut(team_id)
                .ok_or_else(|| anyhow::anyhow!("Team not found: {team_id}"))?;

            session.completed_tutorials.push(tutorial_id);
            session.progress.tutorials_completed += 1;
            session.progress.exercises_completed += exercises_completed;
            session.progress.engagement_score = engagement_score;

            // Check for phase advancement - clone needed data first
            let current_phase = session.current_phase.clone();
            let tutorials_completed = session.progress.tutorials_completed;

            // Check if advancement is needed
            let should_advance = match current_phase {
                OnboardingPhase::Introduction if tutorials_completed >= 2 => true,
                OnboardingPhase::MonitoringSetup if tutorials_completed >= 4 => true,
                OnboardingPhase::MetricsLearning if tutorials_completed >= 6 => true,
                OnboardingPhase::EnforcementConfig if tutorials_completed >= 8 => true,
                OnboardingPhase::AutomationSetup if tutorials_completed >= 10 => true,
                _ => false,
            };

            if should_advance {
                let next_phase = match current_phase {
                    OnboardingPhase::Introduction => OnboardingPhase::MonitoringSetup,
                    OnboardingPhase::MonitoringSetup => OnboardingPhase::MetricsLearning,
                    OnboardingPhase::MetricsLearning => OnboardingPhase::EnforcementConfig,
                    OnboardingPhase::EnforcementConfig => OnboardingPhase::AutomationSetup,
                    OnboardingPhase::AutomationSetup => OnboardingPhase::AdvancedFeatures,
                    OnboardingPhase::AdvancedFeatures => OnboardingPhase::ProductionReady,
                    OnboardingPhase::ProductionReady => OnboardingPhase::ProductionReady, // Stay at production ready
                };

                session.current_phase = next_phase;
            }
        }

        Ok(())
    }

    /// Generate onboarding report
    pub fn generate_progress_report(&self, team_id: &TeamId) -> Result<OnboardingReport> {
        let session = self
            .sessions
            .get(team_id)
            .ok_or_else(|| anyhow::anyhow!("Team not found: {team_id}"))?;

        let completion_percentage = (f64::from(session.progress.tutorials_completed)
            / f64::from(session.progress.tutorials_total))
            * 100.0;

        let current_phase_progress = self.calculate_phase_progress(session);
        let recommended_next_steps = self.get_recommendations(team_id)?;

        let achievements = self.calculate_achievements(session);

        Ok(OnboardingReport {
            team_id: team_id.clone(),
            current_phase: session.current_phase.clone(),
            overall_completion: completion_percentage,
            phase_progress: current_phase_progress,
            days_active: session.progress.days_active,
            engagement_score: session.progress.engagement_score,
            achievements,
            recommended_next_steps: recommended_next_steps.into_iter().take(3).collect(),
            quality_mode: session.quality_mode,
        })
    }

    /// Calculate tutorial relevance to team preferences
    fn calculate_relevance(&self, tutorial: &Tutorial, preferences: &TeamPreferences) -> f64 {
        let mut relevance: f64 = 0.0;

        // Language relevance
        if preferences.languages.iter().any(|lang| {
            tutorial
                .description
                .to_lowercase()
                .contains(&lang.to_lowercase())
        }) {
            relevance += 0.3;
        }

        // Learning style alignment
        match preferences.learning_style {
            LearningStyle::Practical => {
                if tutorial.exercises.len() > 2 {
                    relevance += 0.2;
                }
            }
            LearningStyle::Theoretical => {
                if matches!(tutorial.content, TutorialContent::Documentation { .. }) {
                    relevance += 0.2;
                }
            }
            _ => relevance += 0.1,
        }

        // Experience level adjustment
        match preferences.team_info.experience_level {
            ExperienceLevel::Junior => {
                if tutorial.duration_minutes <= 30 {
                    relevance += 0.2;
                }
            }
            ExperienceLevel::Senior => {
                if tutorial.exercises.len() > 1 {
                    relevance += 0.2;
                }
            }
            _ => relevance += 0.1,
        }

        relevance.min(1.0_f64)
    }

    /// Calculate engagement score
    fn calculate_engagement_score(&self, session: &OnboardingSession) -> f64 {
        let tutorial_ratio =
            f64::from(session.progress.tutorials_completed) / f64::from(session.progress.tutorials_total);

        let exercise_bonus = (f64::from(session.progress.exercises_completed) * 0.1).min(0.3);
        let improvement_bonus = (f64::from(session.progress.quality_improvements) * 0.05).min(0.2);

        ((tutorial_ratio + exercise_bonus + improvement_bonus) * 100.0).min(100.0)
    }

    /// Calculate current phase progress
    fn calculate_phase_progress(&self, session: &OnboardingSession) -> f64 {
        let phase_tutorials = self
            .tutorials
            .get_tutorials_for_phase(&session.current_phase);
        let completed_in_phase = phase_tutorials
            .iter()
            .filter(|t| session.completed_tutorials.contains(&t.id))
            .count();

        (completed_in_phase as f64 / phase_tutorials.len() as f64) * 100.0
    }

    /// Calculate achievements earned
    fn calculate_achievements(&self, session: &OnboardingSession) -> Vec<Achievement> {
        let mut achievements = Vec::new();

        if session.progress.tutorials_completed >= 5 {
            achievements.push(Achievement {
                id: "tutorial_enthusiast".to_string(),
                name: "Tutorial Enthusiast".to_string(),
                description: "Completed 5 tutorials".to_string(),
                earned_at: session.started_at,
            });
        }

        if session.progress.exercises_completed >= 10 {
            achievements.push(Achievement {
                id: "hands_on_learner".to_string(),
                name: "Hands-on Learner".to_string(),
                description: "Completed 10 exercises".to_string(),
                earned_at: session.started_at,
            });
        }

        if session.progress.engagement_score >= 90.0 {
            achievements.push(Achievement {
                id: "quality_champion".to_string(),
                name: "Quality Champion".to_string(),
                description: "Achieved 90% engagement score".to_string(),
                earned_at: session.started_at,
            });
        }

        achievements
    }

    /// Get next phase in progression
    #[allow(dead_code)]
    fn next_phase(&self, current: &OnboardingPhase) -> OnboardingPhase {
        match current {
            OnboardingPhase::Introduction => OnboardingPhase::MonitoringSetup,
            OnboardingPhase::MonitoringSetup => OnboardingPhase::MetricsLearning,
            OnboardingPhase::MetricsLearning => OnboardingPhase::EnforcementConfig,
            OnboardingPhase::EnforcementConfig => OnboardingPhase::AutomationSetup,
            OnboardingPhase::AutomationSetup => OnboardingPhase::AdvancedFeatures,
            OnboardingPhase::AdvancedFeatures => OnboardingPhase::ProductionReady,
            OnboardingPhase::ProductionReady => OnboardingPhase::ProductionReady, // Stay at final phase
        }
    }

    /// Get recommended quality mode for phase
    #[allow(dead_code)]
    fn recommended_quality_mode(&self, phase: &OnboardingPhase) -> QualityMode {
        match phase {
            OnboardingPhase::Introduction => QualityMode::Observe,
            OnboardingPhase::MonitoringSetup => QualityMode::Observe,
            OnboardingPhase::MetricsLearning => QualityMode::Advise,
            OnboardingPhase::EnforcementConfig => QualityMode::Guide,
            OnboardingPhase::AutomationSetup => QualityMode::Enforce,
            OnboardingPhase::AdvancedFeatures => QualityMode::Enforce,
            OnboardingPhase::ProductionReady => QualityMode::Enforce,
        }
    }
}

/// Onboarding progress report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnboardingReport {
    pub team_id: TeamId,
    pub current_phase: OnboardingPhase,
    pub overall_completion: f64,
    pub phase_progress: f64,
    pub days_active: u32,
    pub engagement_score: f64,
    pub achievements: Vec<Achievement>,
    pub recommended_next_steps: Vec<Tutorial>,
    pub quality_mode: QualityMode,
}

/// Achievement earned by team
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Achievement {
    pub id: String,
    pub name: String,
    pub description: String,
    pub earned_at: std::time::SystemTime,
}

impl Default for TutorialLibrary {
    fn default() -> Self {
        Self::new()
    }
}

impl TutorialLibrary {
    /// Create new tutorial library with built-in content
    #[must_use] 
    pub fn new() -> Self {
        let mut tutorials = HashMap::new();

        // Introduction phase tutorials
        tutorials.insert(OnboardingPhase::Introduction, vec![
            Tutorial {
                id: "quality_philosophy".to_string(),
                name: "Quality Philosophy and Benefits".to_string(),
                description: "Learn about the unified quality approach and its benefits".to_string(),
                duration_minutes: 15,
                prerequisites: vec![],
                objectives: vec![
                    "Understand quality-driven development".to_string(),
                    "Learn about error budgets".to_string(),
                    "See ROI of quality investment".to_string(),
                ],
                content: TutorialContent::Documentation {
                    title: "Quality Philosophy".to_string(),
                    content: "Quality is not just about catching bugs - it's about building sustainable, maintainable software that delivers business value.".to_string(),
                    examples: vec!["Case studies from high-performing teams".to_string()],
                },
                exercises: vec![],
                success_criteria: vec!["Complete reading".to_string(), "Pass knowledge check".to_string()],
            },
        ]);

        // Monitoring setup tutorials
        tutorials.insert(
            OnboardingPhase::MonitoringSetup,
            vec![Tutorial {
                id: "setup_monitoring".to_string(),
                name: "Setting Up Quality Monitoring".to_string(),
                description: "Configure real-time quality monitoring for your project".to_string(),
                duration_minutes: 30,
                prerequisites: vec!["quality_philosophy".to_string()],
                objectives: vec![
                    "Install and configure PMAT".to_string(),
                    "Set up file watching".to_string(),
                    "Understand monitoring outputs".to_string(),
                ],
                content: TutorialContent::Walkthrough {
                    steps: vec![WalkthroughStep {
                        step: 1,
                        title: "Install PMAT".to_string(),
                        instructions: "Install PMAT using cargo".to_string(),
                        commands: vec!["cargo install pmat".to_string()],
                        expected_results: "PMAT installed successfully".to_string(),
                        tips: vec!["Use --force to update existing installation".to_string()],
                    }],
                },
                exercises: vec![Exercise {
                    name: "Monitor Your Project".to_string(),
                    instructions: "Set up monitoring for your current project".to_string(),
                    starting_files: HashMap::new(),
                    expected_outcome: "Quality metrics displayed".to_string(),
                    validation: vec!["pmat analyze complexity".to_string()],
                    hints: vec!["Start with a small test file".to_string()],
                }],
                success_criteria: vec![
                    "Successfully run pmat commands".to_string(),
                    "See quality metrics".to_string(),
                ],
            }],
        );

        Self { tutorials }
    }

    /// Get tutorials for a specific phase
    #[must_use] 
    pub fn get_tutorials_for_phase(&self, phase: &OnboardingPhase) -> Vec<Tutorial> {
        self.tutorials.get(phase).cloned().unwrap_or_default()
    }

    /// Count total tutorials
    #[must_use] 
    pub fn count_tutorials(&self) -> u32 {
        self.tutorials.values().map(|v| v.len() as u32).sum()
    }
}

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

    #[test]
    fn test_onboarding_session_creation() {
        let preferences = TeamPreferences {
            languages: vec!["rust".to_string()],
            learning_style: LearningStyle::Practical,
            notifications: NotificationPreference {
                daily_updates: true,
                weekly_summaries: true,
                achievements: true,
                celebrations: true,
            },
            philosophy: QualityPhilosophy::default(),
            team_info: TeamInfo {
                size: 5,
                experience_level: ExperienceLevel::Intermediate,
                project_type: ProjectType::WebApplication,
                quality_maturity: QualityMaturity::Basic,
            },
        };

        let config = OnboardingConfig {
            interactive_mode: true,
            personalization: true,
            track_progress: true,
            gamification: GamificationConfig {
                achievements: true,
                badges: true,
                leaderboards: false,
                points: true,
            },
        };

        let mut onboarding = TeamOnboarding::new(config);
        let session = onboarding
            .start_onboarding("team-1".to_string(), preferences)
            .unwrap();

        assert_eq!(session.team_id, "team-1");
        assert_eq!(session.current_phase, OnboardingPhase::Introduction);
        assert_eq!(session.quality_mode, QualityMode::Observe);
        assert!(session.completed_tutorials.is_empty());
    }

    #[test]
    fn test_tutorial_library() {
        let library = TutorialLibrary::new();
        let intro_tutorials = library.get_tutorials_for_phase(&OnboardingPhase::Introduction);
        assert!(!intro_tutorials.is_empty());

        let total_count = library.count_tutorials();
        assert!(total_count > 0);
    }

    #[test]
    fn test_phase_progression() {
        let config = OnboardingConfig {
            interactive_mode: true,
            personalization: true,
            track_progress: true,
            gamification: GamificationConfig {
                achievements: true,
                badges: true,
                leaderboards: false,
                points: true,
            },
        };

        let onboarding = TeamOnboarding::new(config);

        assert_eq!(
            onboarding.next_phase(&OnboardingPhase::Introduction),
            OnboardingPhase::MonitoringSetup
        );

        assert_eq!(
            onboarding.next_phase(&OnboardingPhase::ProductionReady),
            OnboardingPhase::ProductionReady
        );
    }

    #[test]
    fn test_quality_mode_progression() {
        let config = OnboardingConfig {
            interactive_mode: true,
            personalization: true,
            track_progress: true,
            gamification: GamificationConfig {
                achievements: true,
                badges: true,
                leaderboards: false,
                points: true,
            },
        };

        let onboarding = TeamOnboarding::new(config);

        assert_eq!(
            onboarding.recommended_quality_mode(&OnboardingPhase::Introduction),
            QualityMode::Observe
        );

        assert_eq!(
            onboarding.recommended_quality_mode(&OnboardingPhase::EnforcementConfig),
            QualityMode::Guide
        );

        assert_eq!(
            onboarding.recommended_quality_mode(&OnboardingPhase::ProductionReady),
            QualityMode::Enforce
        );
    }

    #[test]
    fn test_learning_styles() {
        let styles = vec![
            LearningStyle::Practical,
            LearningStyle::Theoretical,
            LearningStyle::Balanced,
            LearningStyle::Exploratory,
        ];

        assert_eq!(styles.len(), 4);

        // Test serialization works
        let serialized = serde_json::to_string(&styles[0]).unwrap();
        assert!(serialized.contains("Practical"));
    }

    #[test]
    fn test_gamification_config() {
        let config = GamificationConfig {
            achievements: true,
            badges: false,
            leaderboards: true,
            points: false,
        };

        assert!(config.achievements);
        assert!(!config.badges);
        assert!(config.leaderboards);
        assert!(!config.points);
    }
}