netspeed-cli 0.10.3

Command-line interface for testing internet bandwidth using speedtest.net
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
//! User profiles/roles that customize output based on use case.
//!
//! Each profile adjusts:
//! - Metric scoring weights (what matters most)
//! - Usage check targets (relevant benchmarks)
//! - Output section visibility
//! - Rating thresholds

use serde::{Deserialize, Serialize};

/// Pre-defined user profiles.
///
/// # Example
///
/// ```
/// use netspeed_cli::profiles::UserProfile;
///
/// // Parse from a string name
/// assert_eq!(UserProfile::from_name("gamer"), Some(UserProfile::Gamer));
/// assert_eq!(UserProfile::from_name("streamer"), Some(UserProfile::Streamer));
/// assert_eq!(UserProfile::from_name("invalid"), None);
///
/// // Round-trip: name() → from_name()
/// assert_eq!(UserProfile::from_name(UserProfile::RemoteWorker.name()), Some(UserProfile::RemoteWorker));
///
/// // Default is PowerUser
/// assert_eq!(UserProfile::default(), UserProfile::PowerUser);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum UserProfile {
    /// Tech-savvy users who want all metrics and detailed analysis.
    #[default]
    PowerUser,
    /// Online gamers focused on latency, jitter, and bufferbloat.
    Gamer,
    /// Content consumers (Netflix, `YouTube`, etc.) focused on download speed.
    Streamer,
    /// Work-from-home professionals focused on upload and stability.
    RemoteWorker,
    /// Basic users who want a simple pass/fail assessment.
    Casual,
}

impl UserProfile {
    /// Get profile from string name (case-insensitive).
    ///
    /// Returns `Some(UserProfile)` for valid names (including aliases like
    /// `"poweruser"` and `"remote"`), or `None` for unrecognized names.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Canonical names
    /// assert_eq!(UserProfile::from_name("power-user"), Some(UserProfile::PowerUser));
    /// assert_eq!(UserProfile::from_name("gamer"), Some(UserProfile::Gamer));
    /// assert_eq!(UserProfile::from_name("streamer"), Some(UserProfile::Streamer));
    /// assert_eq!(UserProfile::from_name("remote-worker"), Some(UserProfile::RemoteWorker));
    /// assert_eq!(UserProfile::from_name("casual"), Some(UserProfile::Casual));
    ///
    /// // Aliases
    /// assert_eq!(UserProfile::from_name("poweruser"), Some(UserProfile::PowerUser));
    /// assert_eq!(UserProfile::from_name("remote"), Some(UserProfile::RemoteWorker));
    ///
    /// // Case-insensitive
    /// assert_eq!(UserProfile::from_name("GAMER"), Some(UserProfile::Gamer));
    /// assert_eq!(UserProfile::from_name("Casual"), Some(UserProfile::Casual));
    ///
    /// // Invalid names return None
    /// assert_eq!(UserProfile::from_name("admin"), None);
    /// ```
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        Self::is_valid_name(name).then_some(Self::from_name_unchecked(name))
    }

    /// Check if a profile name is valid without returning the profile.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Canonical names are valid
    /// assert!(UserProfile::is_valid_name("power-user"));
    /// assert!(UserProfile::is_valid_name("gamer"));
    ///
    /// // Aliases are also valid
    /// assert!(UserProfile::is_valid_name("poweruser"));
    /// assert!(UserProfile::is_valid_name("remote"));
    ///
    /// // Case-insensitive
    /// assert!(UserProfile::is_valid_name("GAMER"));
    ///
    /// // Invalid names
    /// assert!(!UserProfile::is_valid_name("admin"));
    /// assert!(!UserProfile::is_valid_name(""));
    /// ```
    #[must_use]
    pub fn is_valid_name(name: &str) -> bool {
        matches!(
            name.to_lowercase().as_str(),
            "power-user"
                | "poweruser"
                | "gamer"
                | "streamer"
                | "remote-worker"
                | "remoteworker"
                | "remote"
                | "casual"
        )
    }

    /// Internal: convert validated name to profile (assumes valid input).
    fn from_name_unchecked(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "power-user" | "poweruser" => Self::PowerUser,
            "gamer" => Self::Gamer,
            "streamer" => Self::Streamer,
            "remote-worker" | "remoteworker" | "remote" => Self::RemoteWorker,
            "casual" => Self::Casual,
            _ => Self::PowerUser, // Safe default
        }
    }

    /// Validate this profile name and return error message if invalid.
    ///
    /// Returns `Ok(())` if valid, `Err(msg)` with the list of valid options if invalid.
    /// Use this for config-file validation where you need an error message;
    /// use [`from_name()`](UserProfile::from_name) if you just need the `UserProfile` value.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Valid names pass validation
    /// assert!(UserProfile::validate("power-user").is_ok());
    /// assert!(UserProfile::validate("gamer").is_ok());
    /// assert!(UserProfile::validate("streamer").is_ok());
    /// assert!(UserProfile::validate("remote-worker").is_ok());
    /// assert!(UserProfile::validate("casual").is_ok());
    ///
    /// // Invalid names produce a descriptive error
    /// let err = UserProfile::validate("admin").unwrap_err();
    /// assert!(err.contains("Invalid profile"));
    /// assert!(err.contains("admin"));
    /// assert!(err.contains("gamer"));  // lists valid options
    /// ```
    pub fn validate(name: &str) -> Result<(), String> {
        if Self::is_valid_name(name) {
            Ok(())
        } else {
            Err(format!(
                "Invalid profile '{}'. Valid options: {}",
                name,
                Self::VALID_NAMES.join(", ")
            ))
        }
    }

    /// Type identifier for error messages (DIP: shared validation pattern).
    pub const TYPE_NAME: &'static str = "profile";

    /// List of valid profile names for error messages.
    pub const VALID_NAMES: &'static [&'static str] =
        &["power-user", "gamer", "streamer", "remote-worker", "casual"];

    /// CLI-friendly name for the profile.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert_eq!(UserProfile::PowerUser.name(), "power-user");
    /// assert_eq!(UserProfile::Gamer.name(), "gamer");
    /// assert_eq!(UserProfile::Streamer.name(), "streamer");
    /// assert_eq!(UserProfile::RemoteWorker.name(), "remote-worker");
    /// assert_eq!(UserProfile::Casual.name(), "casual");
    /// ```
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::PowerUser => "power-user",
            Self::Gamer => "gamer",
            Self::Streamer => "streamer",
            Self::RemoteWorker => "remote-worker",
            Self::Casual => "casual",
        }
    }

    /// Display name with emoji for headers.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert_eq!(UserProfile::PowerUser.display_name(), "⚙️ Power User");
    /// assert_eq!(UserProfile::Gamer.display_name(), "🎮 Gamer");
    /// assert_eq!(UserProfile::Streamer.display_name(), "📺 Streamer");
    /// assert_eq!(UserProfile::RemoteWorker.display_name(), "💼 Remote Worker");
    /// assert_eq!(UserProfile::Casual.display_name(), "👤 Casual");
    /// ```
    #[must_use]
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::PowerUser => "⚙️ Power User",
            Self::Gamer => "🎮 Gamer",
            Self::Streamer => "📺 Streamer",
            Self::RemoteWorker => "💼 Remote Worker",
            Self::Casual => "👤 Casual",
        }
    }

    /// Description for help text.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Each description highlights the profile's focus
    /// assert!(UserProfile::Gamer.description().contains("Latency"));
    /// assert!(UserProfile::Gamer.description().contains("jitter"));
    ///
    /// assert!(UserProfile::Streamer.description().contains("Download"));
    /// assert!(UserProfile::Streamer.description().contains("streaming"));
    ///
    /// assert!(UserProfile::RemoteWorker.description().contains("Upload"));
    /// assert!(UserProfile::RemoteWorker.description().contains("video calls"));
    ///
    /// assert!(UserProfile::Casual.description().contains("pass/fail"));
    ///
    /// assert!(UserProfile::PowerUser.description().contains("All metrics"));
    /// ```
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::PowerUser => "All metrics, historical trends, percentiles, stability analysis",
            Self::Gamer => "Latency, jitter, bufferbloat — optimized for gaming performance",
            Self::Streamer => "Download speed, consistency — optimized for streaming quality",
            Self::RemoteWorker => {
                "Upload speed, stability — optimized for video calls and cloud work"
            }
            Self::Casual => "Simple pass/fail with overall rating only",
        }
    }

    /// Scoring weights for overall connection rating (ping, jitter, download, upload).
    ///
    /// Returns `(ping_weight, jitter_weight, download_weight, upload_weight)`.
    /// Weights always sum to ~1.0, but the distribution reflects each profile's
    /// priorities.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Gamer prioritizes latency and jitter
    /// let (ping, jitter, dl, ul) = UserProfile::Gamer.scoring_weights();
    /// assert!(ping > dl, "gamer weights ping over download");
    /// assert!(jitter > ul, "gamer weights jitter over upload");
    ///
    /// // Streamer prioritizes download speed
    /// let (_, _, dl, _) = UserProfile::Streamer.scoring_weights();
    /// assert!(dl >= 0.5, "streamer weights download highest");
    ///
    /// // RemoteWorker prioritizes upload speed
    /// let (_, _, _, ul) = UserProfile::RemoteWorker.scoring_weights();
    /// assert!(ul >= 0.35, "remote-worker weights upload highest");
    ///
    /// // All profiles' weights sum to ~1.0
    /// for profile in [UserProfile::PowerUser, UserProfile::Gamer,
    ///                UserProfile::Streamer, UserProfile::RemoteWorker,
    ///                UserProfile::Casual] {
    ///     let (p, j, d, u) = profile.scoring_weights();
    ///     assert!((p + j + d + u - 1.0).abs() < 0.01,
    ///             "weights must sum to ~1.0 for {profile:?}");
    /// }
    /// ```
    #[must_use]
    pub fn scoring_weights(&self) -> (f64, f64, f64, f64) {
        match self {
            Self::PowerUser => (0.25, 0.20, 0.30, 0.25), // Balanced
            Self::Gamer => (0.40, 0.30, 0.15, 0.15),     // Latency-focused
            Self::Streamer => (0.15, 0.15, 0.55, 0.15),  // Download-focused
            Self::RemoteWorker => (0.20, 0.15, 0.25, 0.40), // Upload-focused
            Self::Casual => (0.25, 0.15, 0.35, 0.25),    // Simplified balanced
        }
    }

    /// Speed rating thresholds for "Excellent" (in Mbps).
    ///
    /// Lower values = easier to achieve. PowerUser demands the highest
    /// bandwidth; Casual is satisfied with the least.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // PowerUser requires 500 Mbps for "Excellent"
    /// assert_eq!(UserProfile::PowerUser.excellent_speed_threshold(), 500.0);
    ///
    /// // Gamer and RemoteWorker need only 100 Mbps (latency matters more)
    /// assert_eq!(UserProfile::Gamer.excellent_speed_threshold(), 100.0);
    /// assert_eq!(UserProfile::RemoteWorker.excellent_speed_threshold(), 100.0);
    ///
    /// // Streamer needs 200 Mbps (4K streaming headroom)
    /// assert_eq!(UserProfile::Streamer.excellent_speed_threshold(), 200.0);
    ///
    /// // Casual is happy with 50 Mbps
    /// assert_eq!(UserProfile::Casual.excellent_speed_threshold(), 50.0);
    /// ```
    #[must_use]
    pub fn excellent_speed_threshold(&self) -> f64 {
        match self {
            Self::PowerUser => 500.0,
            Self::Gamer | Self::RemoteWorker => 100.0, // Gamers/remote workers don't need massive bandwidth
            Self::Streamer => 200.0, // 4K streaming needs ~50 Mbps, 200 gives headroom
            Self::Casual => 50.0,
        }
    }

    /// Ping rating thresholds for "Excellent" (in ms).
    ///
    /// Lower values = harder to achieve. Gamer demands ultra-low latency;
    /// Casual/Streamer tolerate higher ping.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Gamer needs ≤5 ms for "Excellent" ping
    /// assert_eq!(UserProfile::Gamer.excellent_ping_threshold(), 5.0);
    ///
    /// // PowerUser needs ≤10 ms
    /// assert_eq!(UserProfile::PowerUser.excellent_ping_threshold(), 10.0);
    ///
    /// // RemoteWorker tolerates ≤20 ms
    /// assert_eq!(UserProfile::RemoteWorker.excellent_ping_threshold(), 20.0);
    ///
    /// // Streamer and Casual are fine with ≤30 ms
    /// assert_eq!(UserProfile::Streamer.excellent_ping_threshold(), 30.0);
    /// assert_eq!(UserProfile::Casual.excellent_ping_threshold(), 30.0);
    /// ```
    #[must_use]
    pub fn excellent_ping_threshold(&self) -> f64 {
        match self {
            Self::PowerUser => 10.0,
            Self::Gamer => 5.0, // Gamers need ultra-low latency
            Self::RemoteWorker => 20.0,
            Self::Streamer | Self::Casual => 30.0, // Streaming buffers / casual users tolerate higher ping
        }
    }

    /// Jitter rating thresholds for "Excellent" (in ms).
    ///
    /// Lower values = harder to achieve. Gamer needs the most consistent
    /// latency; Casual/Streamer tolerate more variation.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// // Gamer needs ≤1 ms jitter for "Excellent"
    /// assert_eq!(UserProfile::Gamer.excellent_jitter_threshold(), 1.0);
    ///
    /// // PowerUser needs ≤2 ms
    /// assert_eq!(UserProfile::PowerUser.excellent_jitter_threshold(), 2.0);
    ///
    /// // RemoteWorker tolerates ≤3 ms
    /// assert_eq!(UserProfile::RemoteWorker.excellent_jitter_threshold(), 3.0);
    ///
    /// // Streamer and Casual are fine with ≤5 ms
    /// assert_eq!(UserProfile::Streamer.excellent_jitter_threshold(), 5.0);
    /// assert_eq!(UserProfile::Casual.excellent_jitter_threshold(), 5.0);
    /// ```
    #[must_use]
    pub fn excellent_jitter_threshold(&self) -> f64 {
        match self {
            Self::PowerUser => 2.0,
            Self::Gamer => 1.0, // Gamers need consistent latency
            Self::RemoteWorker => 3.0,
            Self::Streamer | Self::Casual => 5.0,
        }
    }

    /// Whether to show detailed latency section.
    ///
    /// All profiles except [`Casual`](UserProfile::Casual) show latency details.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_latency_details());
    /// assert!(UserProfile::Gamer.show_latency_details());
    /// assert!(!UserProfile::Casual.show_latency_details()); // minimal output
    /// ```
    #[must_use]
    pub fn show_latency_details(&self) -> bool {
        !matches!(self, Self::Casual)
    }

    /// Whether to show bufferbloat grade.
    ///
    /// Only [`PowerUser`](UserProfile::PowerUser) and [`Gamer`](UserProfile::Gamer)
    /// care about bufferbloat.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_bufferbloat());
    /// assert!(UserProfile::Gamer.show_bufferbloat());
    /// assert!(!UserProfile::Streamer.show_bufferbloat());
    /// assert!(!UserProfile::Casual.show_bufferbloat());
    /// ```
    #[must_use]
    pub fn show_bufferbloat(&self) -> bool {
        matches!(self, Self::PowerUser | Self::Gamer)
    }

    /// Whether to show stability analysis (CV%).
    ///
    /// [`PowerUser`](UserProfile::PowerUser) and [`RemoteWorker`](UserProfile::RemoteWorker)
    /// need consistent connections for their use cases.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_stability());
    /// assert!(UserProfile::RemoteWorker.show_stability());
    /// assert!(!UserProfile::Gamer.show_stability());
    /// assert!(!UserProfile::Casual.show_stability());
    /// ```
    #[must_use]
    pub fn show_stability(&self) -> bool {
        matches!(self, Self::PowerUser | Self::RemoteWorker)
    }

    /// Whether to show latency percentiles.
    ///
    /// Only [`PowerUser`](UserProfile::PowerUser) sees percentile detail.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_percentiles());
    /// assert!(!UserProfile::Gamer.show_percentiles());
    /// assert!(!UserProfile::Casual.show_percentiles());
    /// ```
    #[must_use]
    pub fn show_percentiles(&self) -> bool {
        matches!(self, Self::PowerUser)
    }

    /// Whether to show usage check targets.
    ///
    /// All profiles except [`Casual`](UserProfile::Casual) show usage checks.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_usage_check());
    /// assert!(UserProfile::Gamer.show_usage_check());
    /// assert!(!UserProfile::Casual.show_usage_check()); // minimal output
    /// ```
    #[must_use]
    pub fn show_usage_check(&self) -> bool {
        !matches!(self, Self::Casual)
    }

    /// Whether to show download time estimates.
    ///
    /// [`PowerUser`](UserProfile::PowerUser) wants all metrics;
    /// [`Casual`](UserProfile::Casual) benefits from practical time estimates.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_estimates());
    /// assert!(UserProfile::Casual.show_estimates());
    /// assert!(!UserProfile::Gamer.show_estimates());
    /// assert!(!UserProfile::Streamer.show_estimates());
    /// ```
    #[must_use]
    pub fn show_estimates(&self) -> bool {
        matches!(self, Self::PowerUser | Self::Casual)
    }

    /// Whether to show historical comparison.
    ///
    /// [`PowerUser`](UserProfile::PowerUser) tracks trends;
    /// [`RemoteWorker`](UserProfile::RemoteWorker) monitors connection reliability over time.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_history());
    /// assert!(UserProfile::RemoteWorker.show_history());
    /// assert!(!UserProfile::Gamer.show_history());
    /// assert!(!UserProfile::Casual.show_history());
    /// ```
    #[must_use]
    pub fn show_history(&self) -> bool {
        matches!(self, Self::PowerUser | Self::RemoteWorker)
    }

    /// Whether to show UL/DL ratio.
    ///
    /// [`PowerUser`](UserProfile::PowerUser) wants all metrics;
    /// [`RemoteWorker`](UserProfile::RemoteWorker) cares about upload relative to download.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_ul_dl_ratio());
    /// assert!(UserProfile::RemoteWorker.show_ul_dl_ratio());
    /// assert!(!UserProfile::Streamer.show_ul_dl_ratio());
    /// assert!(!UserProfile::Casual.show_ul_dl_ratio());
    /// ```
    #[must_use]
    pub fn show_ul_dl_ratio(&self) -> bool {
        matches!(self, Self::PowerUser | Self::RemoteWorker)
    }

    /// Whether to show peak speeds.
    ///
    /// All profiles except [`Casual`](UserProfile::Casual) show peak speeds.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_peaks());
    /// assert!(UserProfile::Gamer.show_peaks());
    /// assert!(!UserProfile::Casual.show_peaks()); // minimal output
    /// ```
    #[must_use]
    pub fn show_peaks(&self) -> bool {
        !matches!(self, Self::Casual)
    }

    /// Whether to show latency under load.
    ///
    /// [`PowerUser`](UserProfile::PowerUser) wants all metrics;
    /// [`Gamer`](UserProfile::Gamer) needs to know if loaded latency spikes.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::UserProfile;
    ///
    /// assert!(UserProfile::PowerUser.show_latency_under_load());
    /// assert!(UserProfile::Gamer.show_latency_under_load());
    /// assert!(!UserProfile::Streamer.show_latency_under_load());
    /// assert!(!UserProfile::Casual.show_latency_under_load());
    /// ```
    #[must_use]
    pub fn show_latency_under_load(&self) -> bool {
        matches!(self, Self::PowerUser | Self::Gamer)
    }
}

/// Profile-specific usage check targets.
///
/// Each target represents a real-world use case (e.g., "4K streaming", "video calls")
/// with the minimum bandwidth required to support it.
///
/// # Example
///
/// ```
/// use netspeed_cli::profiles::{UserProfile, profile_usage_targets};
///
/// let targets = profile_usage_targets(UserProfile::Gamer);
/// assert!(!targets.is_empty());
///
/// // Each target has a name, required bandwidth, and icon
/// let first = &targets[0];
/// assert!(!first.name.is_empty());
/// assert!(first.required_mbps > 0.0);
/// assert!(!first.icon.is_empty());
/// ```
pub struct UsageTarget {
    /// Human-readable name of the use case (e.g., `"4K streaming"`, `"Video calls (1080p)"`).
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::{UserProfile, profile_usage_targets};
    ///
    /// let targets = profile_usage_targets(UserProfile::Streamer);
    /// let four_k = targets.iter().find(|t| t.name.contains("4K")).unwrap();
    /// assert_eq!(four_k.name, "4K streaming");
    ///
    /// let casual = profile_usage_targets(UserProfile::Casual);
    /// assert_eq!(casual[0].name, "Web browsing");
    /// ```
    pub name: &'static str,

    /// Minimum bandwidth in Mbps required for a good experience.
    ///
    /// Always positive. Higher values indicate more demanding use cases.
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::{UserProfile, profile_usage_targets};
    ///
    /// // 4K streaming needs at least 25 Mbps
    /// let streamer = profile_usage_targets(UserProfile::Streamer);
    /// let four_k = streamer.iter().find(|t| t.name.contains("4K")).unwrap();
    /// assert_eq!(four_k.required_mbps, 25.0);
    ///
    /// // Web browsing is lightweight — only 1 Mbps
    /// let casual = profile_usage_targets(UserProfile::Casual);
    /// assert_eq!(casual[0].required_mbps, 1.0);
    ///
    /// // Voice chat is extremely lightweight
    /// let gamer = profile_usage_targets(UserProfile::Gamer);
    /// let voice = gamer.iter().find(|t| t.name.contains("Voice")).unwrap();
    /// assert!(voice.required_mbps < 1.0);
    /// ```
    pub required_mbps: f64,

    /// Emoji icon for visual display in the usage check section.
    ///
    /// Always a single emoji character (e.g., `"📺"`, `"📹"`, `"☁️"`).
    ///
    /// # Example
    ///
    /// ```
    /// use netspeed_cli::profiles::{UserProfile, profile_usage_targets};
    ///
    /// let streamer = profile_usage_targets(UserProfile::Streamer);
    /// let four_k = streamer.iter().find(|t| t.name.contains("4K")).unwrap();
    /// assert_eq!(four_k.icon, "🎬");
    ///
    /// let casual = profile_usage_targets(UserProfile::Casual);
    /// assert_eq!(casual[0].icon, "🌐"); // Web browsing
    ///
    /// // All targets have non-empty icons
    /// for profile in [UserProfile::PowerUser, UserProfile::Gamer,
    ///                UserProfile::Streamer, UserProfile::RemoteWorker,
    ///                UserProfile::Casual] {
    ///     for target in &profile_usage_targets(profile) {
    ///         assert!(!target.icon.is_empty(),
    ///                 "icon must not be empty for {}", target.name);
    ///     }
    /// }
    /// ```
    pub icon: &'static str,
}

/// Get usage check targets for a profile.
///
/// Returns a list of [`UsageTarget`] entries relevant to the profile's use case.
/// Each profile has different targets reflecting its priorities.
///
/// # Example
///
/// ```
/// use netspeed_cli::profiles::{UserProfile, profile_usage_targets};
///
/// // Gamer targets include voice chat and cloud gaming
/// let gamer = profile_usage_targets(UserProfile::Gamer);
/// assert!(gamer.len() >= 3);
/// assert!(gamer.iter().any(|t| t.name.contains("gaming")));
///
/// // Streamer targets include streaming quality levels
/// let streamer = profile_usage_targets(UserProfile::Streamer);
/// assert!(streamer.iter().any(|t| t.name.contains("4K")));
///
/// // RemoteWorker targets include video calls and file uploads
/// let remote = profile_usage_targets(UserProfile::RemoteWorker);
/// assert!(remote.iter().any(|t| t.name.contains("Video calls")));
///
/// // Casual has the fewest targets
/// let casual = profile_usage_targets(UserProfile::Casual);
/// assert!(casual.len() < gamer.len());
///
/// // All profiles have at least one target
/// for profile in [UserProfile::PowerUser, UserProfile::Gamer,
///                UserProfile::Streamer, UserProfile::RemoteWorker,
///                UserProfile::Casual] {
///     assert!(!profile_usage_targets(profile).is_empty());
/// }
/// ```
#[must_use]
pub fn profile_usage_targets(profile: UserProfile) -> Vec<UsageTarget> {
    match profile {
        UserProfile::Gamer => vec![
            UsageTarget {
                name: "Online gaming (1080p)",
                required_mbps: 3.0,
                icon: "🎮",
            },
            UsageTarget {
                name: "Game downloads (50 GB)",
                required_mbps: 100.0,
                icon: "💿",
            },
            UsageTarget {
                name: "Game updates (5 GB)",
                required_mbps: 50.0,
                icon: "🔄",
            },
            UsageTarget {
                name: "Cloud gaming (Stadia)",
                required_mbps: 35.0,
                icon: "☁️",
            },
            UsageTarget {
                name: "Voice chat (Discord)",
                required_mbps: 0.1,
                icon: "🎙️",
            },
        ],
        UserProfile::Streamer => vec![
            UsageTarget {
                name: "SD streaming (480p)",
                required_mbps: 3.0,
                icon: "📺",
            },
            UsageTarget {
                name: "HD streaming (1080p)",
                required_mbps: 5.0,
                icon: "📺",
            },
            UsageTarget {
                name: "4K streaming",
                required_mbps: 25.0,
                icon: "🎬",
            },
            UsageTarget {
                name: "8K streaming",
                required_mbps: 80.0,
                icon: "🎬",
            },
            UsageTarget {
                name: "Multiple streams (3x)",
                required_mbps: 75.0,
                icon: "📺",
            },
        ],
        UserProfile::RemoteWorker => vec![
            UsageTarget {
                name: "Video calls (1080p)",
                required_mbps: 3.0,
                icon: "📹",
            },
            UsageTarget {
                name: "Video calls (4K)",
                required_mbps: 8.0,
                icon: "📹",
            },
            UsageTarget {
                name: "Screen sharing",
                required_mbps: 5.0,
                icon: "🖥️",
            },
            UsageTarget {
                name: "Large file upload",
                required_mbps: 50.0,
                icon: "📤",
            },
            UsageTarget {
                name: "Cloud backup",
                required_mbps: 20.0,
                icon: "☁️",
            },
        ],
        UserProfile::PowerUser => vec![
            UsageTarget {
                name: "Video calls (1080p)",
                required_mbps: 3.0,
                icon: "📹",
            },
            UsageTarget {
                name: "HD streaming",
                required_mbps: 5.0,
                icon: "📺",
            },
            UsageTarget {
                name: "4K streaming",
                required_mbps: 25.0,
                icon: "🎬",
            },
            UsageTarget {
                name: "Cloud gaming",
                required_mbps: 35.0,
                icon: "☁️",
            },
            UsageTarget {
                name: "Large file transfers",
                required_mbps: 100.0,
                icon: "📤",
            },
        ],
        UserProfile::Casual => vec![
            UsageTarget {
                name: "Web browsing",
                required_mbps: 1.0,
                icon: "🌐",
            },
            UsageTarget {
                name: "Email",
                required_mbps: 0.5,
                icon: "📧",
            },
            UsageTarget {
                name: "SD video",
                required_mbps: 3.0,
                icon: "📺",
            },
        ],
    }
}

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

    #[test]
    fn test_is_valid_name() {
        assert!(UserProfile::is_valid_name("gamer"));
        assert!(UserProfile::is_valid_name("GAMER"));
        assert!(UserProfile::is_valid_name("power-user"));
        // Aliases
        assert!(UserProfile::is_valid_name("remote")); // alias for remote-worker
        assert!(UserProfile::is_valid_name("poweruser")); // alias without hyphen
        assert!(!UserProfile::is_valid_name("invalid"));
    }

    #[test]
    fn test_validate_valid() {
        assert!(UserProfile::validate("gamer").is_ok());
        assert!(UserProfile::validate("streamer").is_ok());
        assert!(UserProfile::validate("casual").is_ok());
    }

    #[test]
    fn test_validate_invalid() {
        let result = UserProfile::validate("invalid");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("Invalid profile"));
        assert!(err.contains("valid"));
    }

    #[test]
    fn test_profile_from_name() {
        assert!(UserProfile::from_name("gamer").is_some());
        assert!(UserProfile::from_name("GAMER").is_some());
        assert!(UserProfile::from_name("streamer").is_some());
        assert!(UserProfile::from_name("remote-worker").is_some());
        assert!(UserProfile::from_name("power-user").is_some());
        assert!(UserProfile::from_name("casual").is_some());
        assert!(UserProfile::from_name("invalid").is_none());
    }

    #[test]
    fn test_profile_name_roundtrip() {
        for profile in [
            UserProfile::PowerUser,
            UserProfile::Gamer,
            UserProfile::Streamer,
            UserProfile::RemoteWorker,
            UserProfile::Casual,
        ] {
            assert_eq!(UserProfile::from_name(profile.name()), Some(profile));
        }
    }

    #[test]
    fn test_scoring_weights_sum() {
        for profile in [
            UserProfile::PowerUser,
            UserProfile::Gamer,
            UserProfile::Streamer,
            UserProfile::RemoteWorker,
            UserProfile::Casual,
        ] {
            let (ping_w, jitter_w, dl_w, ul_w) = profile.scoring_weights();
            assert!(
                (ping_w + jitter_w + dl_w + ul_w - 1.0).abs() < 0.01,
                "Weights should sum to ~1.0 for {profile:?}"
            );
        }
    }

    #[test]
    fn test_gamer_profile_priorities() {
        let gamer = UserProfile::Gamer;
        let (ping_w, jitter_w, dl_w, ul_w) = gamer.scoring_weights();
        assert!(
            ping_w > dl_w,
            "Gamer: ping should weight more than download"
        );
        assert!(
            jitter_w > ul_w,
            "Gamer: jitter should weight more than upload"
        );
        assert!((gamer.excellent_ping_threshold() - 5.0).abs() < f64::EPSILON);
        assert!(gamer.show_bufferbloat());
    }

    #[test]
    fn test_streamer_profile_priorities() {
        let streamer = UserProfile::Streamer;
        let (_, _, dl_w, _) = streamer.scoring_weights();
        assert!(dl_w >= 0.5, "Streamer: download should have highest weight");
        assert!(streamer.show_usage_check());
    }

    #[test]
    fn test_remote_worker_profile_priorities() {
        let remote_worker = UserProfile::RemoteWorker;
        let (_, _, _, ul_w) = remote_worker.scoring_weights();
        assert!(ul_w >= 0.35, "RemoteWorker: upload should have high weight");
        assert!(remote_worker.show_stability());
        assert!(remote_worker.show_ul_dl_ratio());
    }

    #[test]
    fn test_casual_profile_minimal() {
        let casual = UserProfile::Casual;
        assert!(!casual.show_latency_details());
        assert!(!casual.show_bufferbloat());
        assert!(!casual.show_stability());
        assert!(!casual.show_percentiles());
        assert!(!casual.show_history());
        assert!(casual.show_estimates());
    }

    #[test]
    fn test_power_user_shows_all() {
        let power_user = UserProfile::PowerUser;
        assert!(power_user.show_latency_details());
        assert!(power_user.show_bufferbloat());
        assert!(power_user.show_stability());
        assert!(power_user.show_percentiles());
        assert!(power_user.show_history());
    }

    #[test]
    fn test_profile_usage_targets_not_empty() {
        for profile in [
            UserProfile::PowerUser,
            UserProfile::Gamer,
            UserProfile::Streamer,
            UserProfile::RemoteWorker,
            UserProfile::Casual,
        ] {
            let targets = profile_usage_targets(profile);
            assert!(!targets.is_empty(), "{profile:?} should have usage targets");
        }
    }
}