monocle 1.2.0

A commandline application to search, parse, and process BGP information in public sources.
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
//! Common utility functions for lens modules
//!
//! This module provides shared utility functions used across multiple lenses,
//! particularly for formatting output in tables and deserializing query parameters.

use serde::de::{self, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use std::fmt;
use std::str::FromStr;

// =============================================================================
// Serde Deserializers for Query Parameters
// =============================================================================

/// Deserialize a string or vec of strings into a Vec<String>
///
/// This allows query parameters to accept either `param=value` or `param=v1&param=v2`
pub fn string_or_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    struct StringOrVec;

    impl<'de> Visitor<'de> for StringOrVec {
        type Value = Vec<String>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a string or array of strings")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(vec![value.to_string()])
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(vec![value])
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut vec = Vec::new();
            while let Some(value) = seq.next_element()? {
                vec.push(value);
            }
            Ok(vec)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Vec::new())
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Vec::new())
        }
    }

    deserializer.deserialize_any(StringOrVec)
}

/// Deserialize a u32 or vec of u32s into a Vec<u32>
///
/// This allows query parameters to accept either `asn=12345` or `asn=12345&asn=67890`
/// Also handles string representations of numbers from query parameters.
pub fn u32_or_vec<'de, D>(deserializer: D) -> Result<Vec<u32>, D::Error>
where
    D: Deserializer<'de>,
{
    struct U32OrVec;

    impl<'de> Visitor<'de> for U32OrVec {
        type Value = Vec<u32>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a u32, string representing u32, or array of u32s")
        }

        fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(vec![value as u32])
        }

        fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if value < 0 {
                return Err(de::Error::custom("ASN cannot be negative"));
            }
            Ok(vec![value as u32])
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            value
                .parse::<u32>()
                .map(|v| vec![v])
                .map_err(|_| de::Error::custom(format!("Invalid ASN: {}", value)))
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            self.visit_str(&value)
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut vec = Vec::new();
            while let Some(value) = seq.next_element::<serde_json::Value>()? {
                let num = match value {
                    serde_json::Value::Number(n) => n
                        .as_u64()
                        .map(|v| v as u32)
                        .ok_or_else(|| de::Error::custom("Invalid number"))?,
                    serde_json::Value::String(s) => s
                        .parse::<u32>()
                        .map_err(|_| de::Error::custom(format!("Invalid ASN: {}", s)))?,
                    _ => return Err(de::Error::custom("Expected number or string")),
                };
                vec.push(num);
            }
            Ok(vec)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Vec::new())
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Vec::new())
        }
    }

    deserializer.deserialize_any(U32OrVec)
}

/// Deserialize a u32 from string or number
///
/// This allows query parameters to accept `asn=12345` as a string
pub fn u32_from_str<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
    D: Deserializer<'de>,
{
    struct U32FromStr;

    impl<'de> Visitor<'de> for U32FromStr {
        type Value = u32;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a u32 or string representing u32")
        }

        fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(value as u32)
        }

        fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if value < 0 {
                return Err(de::Error::custom("ASN cannot be negative"));
            }
            Ok(value as u32)
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            value
                .parse::<u32>()
                .map_err(|_| de::Error::custom(format!("Invalid ASN: {}", value)))
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            self.visit_str(&value)
        }
    }

    deserializer.deserialize_any(U32FromStr)
}

/// Deserialize an optional u32 from string or number
///
/// This allows query parameters to accept `asn=12345` as a string
pub fn option_u32_from_str<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
    D: Deserializer<'de>,
{
    struct OptionU32FromStr;

    impl<'de> Visitor<'de> for OptionU32FromStr {
        type Value = Option<u32>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a u32, string representing u32, or null")
        }

        fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Some(value as u32))
        }

        fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if value < 0 {
                return Err(de::Error::custom("ASN cannot be negative"));
            }
            Ok(Some(value as u32))
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if value.is_empty() {
                return Ok(None);
            }
            value
                .parse::<u32>()
                .map(Some)
                .map_err(|_| de::Error::custom(format!("Invalid ASN: {}", value)))
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            self.visit_str(&value)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_some<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error>
        where
            D2: Deserializer<'de>,
        {
            deserializer.deserialize_any(OptionU32FromStr)
        }
    }

    deserializer.deserialize_any(OptionU32FromStr)
}

/// Deserialize a boolean from string or bool
///
/// This allows query parameters to accept `param=true` or `param=false` as strings
pub fn bool_from_str<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    struct BoolFromStr;

    impl<'de> Visitor<'de> for BoolFromStr {
        type Value = bool;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a boolean or string representing a boolean")
        }

        fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(value)
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            match value.to_lowercase().as_str() {
                "true" | "1" | "yes" | "on" => Ok(true),
                "false" | "0" | "no" | "off" | "" => Ok(false),
                _ => Err(de::Error::custom(format!(
                    "Invalid boolean value: {}",
                    value
                ))),
            }
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            self.visit_str(&value)
        }

        fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(value != 0)
        }

        fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(value != 0)
        }
    }

    deserializer.deserialize_any(BoolFromStr)
}

// =============================================================================
// Data Refresh Status
// =============================================================================

/// Reason why data needs to be refreshed
///
/// This enum provides specific information about why a data refresh is needed,
/// allowing for more informative user messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshReason {
    /// Data tables don't exist or are empty
    Empty,
    /// Data exists but has expired based on TTL
    Outdated,
}

impl RefreshReason {
    /// Get a human-readable description of the refresh reason
    pub fn description(&self) -> &'static str {
        match self {
            Self::Empty => "data is empty",
            Self::Outdated => "data is outdated",
        }
    }
}

impl std::fmt::Display for RefreshReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description())
    }
}

// =============================================================================
// Cache TTL Configuration
// =============================================================================

use std::time::Duration;

/// Default TTL for all caches (7 days in seconds)
pub const DEFAULT_CACHE_TTL_SECS: u64 = 7 * 24 * 60 * 60;

/// Configuration for cache time-to-live (TTL) settings
///
/// This struct encapsulates TTL values for all data sources, providing a clean
/// interface for configuring cache expiration across the application.
///
/// # Example
///
/// ```rust
/// use monocle::utils::CacheTtlConfig;
/// use std::time::Duration;
///
/// // Use default 7-day TTL for all sources
/// let config = CacheTtlConfig::default();
///
/// // Custom TTLs
/// let config = CacheTtlConfig::new()
///     .with_asinfo(Duration::from_secs(3600))  // 1 hour
///     .with_rpki(Duration::from_secs(86400));  // 1 day
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheTtlConfig {
    /// TTL for ASInfo data (AS names, organizations, PeeringDB)
    pub asinfo: Duration,
    /// TTL for AS2Rel data (AS relationships)
    pub as2rel: Duration,
    /// TTL for RPKI data (ROAs, ASPAs)
    pub rpki: Duration,
    /// TTL for Pfx2as data (prefix-to-ASN mappings)
    pub pfx2as: Duration,
}

impl Default for CacheTtlConfig {
    fn default() -> Self {
        let default_ttl = Duration::from_secs(DEFAULT_CACHE_TTL_SECS);
        Self {
            asinfo: default_ttl,
            as2rel: default_ttl,
            rpki: default_ttl,
            pfx2as: default_ttl,
        }
    }
}

impl CacheTtlConfig {
    /// Create a new CacheTtlConfig with default 7-day TTL for all sources
    pub fn new() -> Self {
        Self::default()
    }

    /// Set all TTLs to the same value
    pub fn with_all(mut self, ttl: Duration) -> Self {
        self.asinfo = ttl;
        self.as2rel = ttl;
        self.rpki = ttl;
        self.pfx2as = ttl;
        self
    }

    /// Set the ASInfo TTL
    pub fn with_asinfo(mut self, ttl: Duration) -> Self {
        self.asinfo = ttl;
        self
    }

    /// Set the AS2Rel TTL
    pub fn with_as2rel(mut self, ttl: Duration) -> Self {
        self.as2rel = ttl;
        self
    }

    /// Set the RPKI TTL
    pub fn with_rpki(mut self, ttl: Duration) -> Self {
        self.rpki = ttl;
        self
    }

    /// Set the Pfx2as TTL
    pub fn with_pfx2as(mut self, ttl: Duration) -> Self {
        self.pfx2as = ttl;
        self
    }

    /// Create from individual Duration values
    pub fn from_durations(
        asinfo: Duration,
        as2rel: Duration,
        rpki: Duration,
        pfx2as: Duration,
    ) -> Self {
        Self {
            asinfo,
            as2rel,
            rpki,
            pfx2as,
        }
    }

    /// Create from seconds values
    pub fn from_secs(asinfo: u64, as2rel: u64, rpki: u64, pfx2as: u64) -> Self {
        Self {
            asinfo: Duration::from_secs(asinfo),
            as2rel: Duration::from_secs(as2rel),
            rpki: Duration::from_secs(rpki),
            pfx2as: Duration::from_secs(pfx2as),
        }
    }
}

// =============================================================================
// Output Format and Display Utilities
// =============================================================================

/// Default maximum length for name display in tables
pub const DEFAULT_NAME_MAX_LEN: usize = 20;

/// Unified output format for all lens commands
///
/// This enum provides a consistent set of output formats that can be used
/// across all monocle commands. Commands that don't support a particular
/// format should return an error.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum OutputFormat {
    /// Pretty table with borders (default)
    #[default]
    Table,
    /// Markdown table format
    Markdown,
    /// Compact JSON (single line per object)
    Json,
    /// Pretty-printed JSON with indentation
    JsonPretty,
    /// JSON Lines format (one JSON object per line, for streaming)
    JsonLine,
    /// Pipe-separated values with header
    Psv,
}

impl OutputFormat {
    /// Check if this is a JSON variant
    pub fn is_json(&self) -> bool {
        matches!(self, Self::Json | Self::JsonPretty | Self::JsonLine)
    }

    /// Check if this is a table variant
    pub fn is_table(&self) -> bool {
        matches!(self, Self::Table | Self::Markdown)
    }

    /// Get a list of all format names for help text
    pub fn all_names() -> &'static [&'static str] {
        &[
            "table",
            "markdown",
            "json",
            "json-pretty",
            "json-line",
            "psv",
        ]
    }
}

impl fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Table => write!(f, "table"),
            Self::Markdown => write!(f, "markdown"),
            Self::Json => write!(f, "json"),
            Self::JsonPretty => write!(f, "json-pretty"),
            Self::JsonLine => write!(f, "json-line"),
            Self::Psv => write!(f, "psv"),
        }
    }
}

// =============================================================================
// Ordering Utilities for BGP Elements
// =============================================================================

/// Fields available for ordering BGP element output
///
/// This enum provides the list of fields that can be used for sorting
/// BGP elements in the output of parse and search commands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", clap(rename_all = "snake_case"))]
pub enum OrderByField {
    /// Order by timestamp (default)
    #[default]
    Timestamp,
    /// Order by network prefix
    Prefix,
    /// Order by peer IP address
    PeerIp,
    /// Order by peer AS number
    PeerAsn,
    /// Order by AS path (string comparison)
    AsPath,
    /// Order by next hop IP address
    NextHop,
}

impl OrderByField {
    /// Get a list of all field names for help text
    pub fn all_names() -> &'static [&'static str] {
        &[
            "timestamp",
            "prefix",
            "peer_ip",
            "peer_asn",
            "as_path",
            "next_hop",
        ]
    }
}

impl fmt::Display for OrderByField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Timestamp => write!(f, "timestamp"),
            Self::Prefix => write!(f, "prefix"),
            Self::PeerIp => write!(f, "peer_ip"),
            Self::PeerAsn => write!(f, "peer_asn"),
            Self::AsPath => write!(f, "as_path"),
            Self::NextHop => write!(f, "next_hop"),
        }
    }
}

impl FromStr for OrderByField {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "timestamp" | "ts" | "time" => Ok(Self::Timestamp),
            "prefix" | "pfx" => Ok(Self::Prefix),
            "peer_ip" | "peerip" | "peer-ip" => Ok(Self::PeerIp),
            "peer_asn" | "peerasn" | "peer-asn" => Ok(Self::PeerAsn),
            "as_path" | "aspath" | "as-path" | "path" => Ok(Self::AsPath),
            "next_hop" | "nexthop" | "next-hop" | "nh" => Ok(Self::NextHop),
            _ => Err(format!(
                "Unknown order-by field '{}'. Valid fields: {}",
                s,
                Self::all_names().join(", ")
            )),
        }
    }
}

/// Direction for ordering output
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum OrderDirection {
    /// Ascending order (smallest/oldest first)
    #[default]
    Asc,
    /// Descending order (largest/newest first)
    Desc,
}

impl fmt::Display for OrderDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Asc => write!(f, "asc"),
            Self::Desc => write!(f, "desc"),
        }
    }
}

impl FromStr for OrderDirection {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "asc" | "ascending" | "a" => Ok(Self::Asc),
            "desc" | "descending" | "d" => Ok(Self::Desc),
            _ => Err(format!(
                "Unknown order direction '{}'. Valid values: asc, desc",
                s
            )),
        }
    }
}

// =============================================================================
// Timestamp Format for BGP Elements
// =============================================================================

/// Format for timestamp output in parse and search commands
///
/// This enum controls how timestamps are displayed in non-JSON output formats
/// (table, psv, markdown). JSON output always uses Unix timestamps as numbers
/// for backward compatibility.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum TimestampFormat {
    /// Unix timestamp (integer or float) - default for backward compatibility
    #[default]
    Unix,
    /// RFC3339/ISO 8601 format (e.g., "2023-10-11T15:00:00Z")
    Rfc3339,
}

impl TimestampFormat {
    /// Get a list of all format names for help text
    pub fn all_names() -> &'static [&'static str] {
        &["unix", "rfc3339"]
    }

    /// Format a Unix timestamp (f64) according to this format
    pub fn format_timestamp(&self, timestamp: f64) -> String {
        match self {
            Self::Unix => timestamp.to_string(),
            Self::Rfc3339 => {
                let secs = timestamp as i64;
                let nsecs = ((timestamp.fract().abs()) * 1_000_000_000.0) as u32;
                chrono::DateTime::from_timestamp(secs, nsecs)
                    .map(|dt| dt.to_rfc3339())
                    .unwrap_or_else(|| timestamp.to_string())
            }
        }
    }
}

impl fmt::Display for TimestampFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unix => write!(f, "unix"),
            Self::Rfc3339 => write!(f, "rfc3339"),
        }
    }
}

impl FromStr for TimestampFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "unix" | "timestamp" | "ts" => Ok(Self::Unix),
            "rfc3339" | "iso8601" | "iso" => Ok(Self::Rfc3339),
            _ => Err(format!(
                "Unknown timestamp format '{}'. Valid formats: {}",
                s,
                Self::all_names().join(", ")
            )),
        }
    }
}

impl FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "table" | "pretty" => Ok(Self::Table),
            "markdown" | "md" => Ok(Self::Markdown),
            "json" => Ok(Self::Json),
            "json-pretty" | "jsonpretty" => Ok(Self::JsonPretty),
            "json-line" | "jsonline" | "jsonl" | "ndjson" => Ok(Self::JsonLine),
            "psv" | "pipe" => Ok(Self::Psv),
            _ => Err(format!(
                "Unknown output format '{}'. Valid formats: {}",
                s,
                Self::all_names().join(", ")
            )),
        }
    }
}

/// Truncate a string to the specified length, adding "..." if truncated
///
/// This is useful for displaying long names (organization names, AS names, etc.)
/// in table output without breaking the table layout.
///
/// # Arguments
///
/// * `name` - The string to truncate
/// * `max_len` - Maximum length of the output string (including "..." if truncated)
///
/// # Examples
///
/// ```
/// use monocle::utils::truncate_name;
///
/// // Short name - no truncation
/// assert_eq!(truncate_name("Short", 20), "Short");
///
/// // Long name - truncated with ...
/// assert_eq!(truncate_name("This is a very long name", 20), "This is a very lo...");
/// ```
pub fn truncate_name(name: &str, max_len: usize) -> String {
    if name.chars().count() <= max_len {
        name.to_string()
    } else {
        let truncated: String = name.chars().take(max_len.saturating_sub(3)).collect();
        format!("{}...", truncated)
    }
}

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

    #[test]
    fn test_truncate_name_short() {
        assert_eq!(truncate_name("Short", 20), "Short");
    }

    #[test]
    fn test_truncate_name_exact_limit() {
        assert_eq!(
            truncate_name("12345678901234567890", 20),
            "12345678901234567890"
        );
    }

    #[test]
    fn test_truncate_name_over_limit() {
        assert_eq!(
            truncate_name("This is a very long organization name", 20),
            "This is a very lo..."
        );
    }

    #[test]
    fn test_truncate_name_empty() {
        assert_eq!(truncate_name("", 20), "");
    }

    #[test]
    fn test_truncate_name_unicode() {
        // Unicode characters should be counted properly (by char, not bytes)
        // "日本語テスト名前これは長い" is 12 chars, truncated to 10 should be 7 chars + "..."
        assert_eq!(
            truncate_name("日本語テスト名前これは長い", 10),
            "日本語テスト名..."
        );
    }

    #[test]
    fn test_truncate_name_arabic() {
        // Arabic text with multi-byte characters (the original bug case)
        // "بلو سكاي تيليكوم" is 16 chars
        assert_eq!(truncate_name("بلو سكاي تيليكوم", 20), "بلو سكاي تيليكوم");
        assert_eq!(truncate_name("بلو سكاي تيليكوم", 10), "بلو سكا...");
    }

    #[test]
    fn test_truncate_name_mixed_scripts() {
        // Mixed ASCII and multi-byte characters
        assert_eq!(truncate_name("Hello世界Goodbye", 15), "Hello世界Goodbye");
        assert_eq!(truncate_name("Hello世界Goodbye", 10), "Hello世界...");
    }

    #[test]
    fn test_truncate_name_emoji() {
        // Emoji characters (4 bytes each in UTF-8)
        // "Hello 🌍🌍🌍 World" = 5 (Hello) + 1 (space) + 3 (🌍) + 1 (space) + 5 (World) = 15 chars
        assert_eq!(
            truncate_name("Hello 🌍🌍🌍 World", 15),
            "Hello 🌍🌍🌍 World"
        );
        assert_eq!(truncate_name("Hello 🌍🌍🌍 World", 10), "Hello 🌍...");
    }

    #[test]
    fn test_truncate_name_small_max() {
        // Edge case: very small max_len
        assert_eq!(truncate_name("Hello", 3), "...");
        assert_eq!(truncate_name("Hi", 3), "Hi");
    }

    #[test]
    fn test_output_format_from_str() {
        assert_eq!(
            OutputFormat::from_str("table").unwrap(),
            OutputFormat::Table
        );
        assert_eq!(
            OutputFormat::from_str("pretty").unwrap(),
            OutputFormat::Table
        );
        assert_eq!(
            OutputFormat::from_str("markdown").unwrap(),
            OutputFormat::Markdown
        );
        assert_eq!(
            OutputFormat::from_str("md").unwrap(),
            OutputFormat::Markdown
        );
        assert_eq!(OutputFormat::from_str("json").unwrap(), OutputFormat::Json);
        assert_eq!(
            OutputFormat::from_str("json-pretty").unwrap(),
            OutputFormat::JsonPretty
        );
        assert_eq!(
            OutputFormat::from_str("json-line").unwrap(),
            OutputFormat::JsonLine
        );
        assert_eq!(
            OutputFormat::from_str("jsonl").unwrap(),
            OutputFormat::JsonLine
        );
        assert_eq!(OutputFormat::from_str("psv").unwrap(), OutputFormat::Psv);
        assert!(OutputFormat::from_str("invalid").is_err());
    }

    #[test]
    fn test_output_format_display() {
        assert_eq!(OutputFormat::Table.to_string(), "table");
        assert_eq!(OutputFormat::Markdown.to_string(), "markdown");
        assert_eq!(OutputFormat::Json.to_string(), "json");
        assert_eq!(OutputFormat::JsonPretty.to_string(), "json-pretty");
        assert_eq!(OutputFormat::JsonLine.to_string(), "json-line");
        assert_eq!(OutputFormat::Psv.to_string(), "psv");
    }

    #[test]
    fn test_output_format_is_json() {
        assert!(!OutputFormat::Table.is_json());
        assert!(!OutputFormat::Markdown.is_json());
        assert!(OutputFormat::Json.is_json());
        assert!(OutputFormat::JsonPretty.is_json());
        assert!(OutputFormat::JsonLine.is_json());
        assert!(!OutputFormat::Psv.is_json());
    }

    #[test]
    fn test_output_format_is_table() {
        assert!(OutputFormat::Table.is_table());
        assert!(OutputFormat::Markdown.is_table());
        assert!(!OutputFormat::Json.is_table());
        assert!(!OutputFormat::JsonPretty.is_table());
        assert!(!OutputFormat::JsonLine.is_table());
        assert!(!OutputFormat::Psv.is_table());
    }

    #[test]
    fn test_string_or_vec_single() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "string_or_vec")]
            values: Vec<String>,
        }

        let json = r#"{"values": "hello"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.values, vec!["hello"]);
    }

    #[test]
    fn test_string_or_vec_array() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "string_or_vec")]
            values: Vec<String>,
        }

        let json = r#"{"values": ["hello", "world"]}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.values, vec!["hello", "world"]);
    }

    #[test]
    fn test_u32_or_vec_single_number() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "u32_or_vec")]
            asns: Vec<u32>,
        }

        let json = r#"{"asns": 13335}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asns, vec![13335]);
    }

    #[test]
    fn test_u32_or_vec_single_string() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "u32_or_vec")]
            asns: Vec<u32>,
        }

        let json = r#"{"asns": "13335"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asns, vec![13335]);
    }

    #[test]
    fn test_u32_or_vec_array() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "u32_or_vec")]
            asns: Vec<u32>,
        }

        let json = r#"{"asns": [13335, 15169]}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asns, vec![13335, 15169]);
    }

    #[test]
    fn test_option_u32_from_str_number() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(default, deserialize_with = "option_u32_from_str")]
            asn: Option<u32>,
        }

        let json = r#"{"asn": 13335}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asn, Some(13335));
    }

    #[test]
    fn test_option_u32_from_str_string() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(default, deserialize_with = "option_u32_from_str")]
            asn: Option<u32>,
        }

        let json = r#"{"asn": "13335"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asn, Some(13335));
    }

    #[test]
    fn test_option_u32_from_str_null() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(default, deserialize_with = "option_u32_from_str")]
            asn: Option<u32>,
        }

        let json = r#"{"asn": null}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asn, None);
    }

    #[test]
    fn test_u32_from_str_number() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "u32_from_str")]
            asn: u32,
        }

        let json = r#"{"asn": 13335}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asn, 13335);
    }

    #[test]
    fn test_u32_from_str_string() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(deserialize_with = "u32_from_str")]
            asn: u32,
        }

        let json = r#"{"asn": "13335"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert_eq!(result.asn, 13335);
    }

    #[test]
    fn test_bool_from_str_true() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(default, deserialize_with = "bool_from_str")]
            flag: bool,
        }

        let json = r#"{"flag": "true"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert!(result.flag);

        let json = r#"{"flag": true}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert!(result.flag);

        let json = r#"{"flag": "1"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert!(result.flag);
    }

    #[test]
    fn test_bool_from_str_false() {
        #[derive(Deserialize)]
        struct Test {
            #[serde(default, deserialize_with = "bool_from_str")]
            flag: bool,
        }

        let json = r#"{"flag": "false"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert!(!result.flag);

        let json = r#"{"flag": false}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert!(!result.flag);

        let json = r#"{"flag": "0"}"#;
        let result: Test = serde_json::from_str(json).unwrap();
        assert!(!result.flag);
    }

    #[test]
    fn test_order_by_field_from_str() {
        assert_eq!(
            OrderByField::from_str("timestamp").unwrap(),
            OrderByField::Timestamp
        );
        assert_eq!(
            OrderByField::from_str("ts").unwrap(),
            OrderByField::Timestamp
        );
        assert_eq!(
            OrderByField::from_str("prefix").unwrap(),
            OrderByField::Prefix
        );
        assert_eq!(
            OrderByField::from_str("peer_ip").unwrap(),
            OrderByField::PeerIp
        );
        assert_eq!(
            OrderByField::from_str("peer-ip").unwrap(),
            OrderByField::PeerIp
        );
        assert_eq!(
            OrderByField::from_str("peer_asn").unwrap(),
            OrderByField::PeerAsn
        );
        assert_eq!(
            OrderByField::from_str("as_path").unwrap(),
            OrderByField::AsPath
        );
        assert_eq!(
            OrderByField::from_str("path").unwrap(),
            OrderByField::AsPath
        );
        assert_eq!(
            OrderByField::from_str("next_hop").unwrap(),
            OrderByField::NextHop
        );
        assert_eq!(OrderByField::from_str("nh").unwrap(), OrderByField::NextHop);
        assert!(OrderByField::from_str("invalid").is_err());
    }

    #[test]
    fn test_order_by_field_display() {
        assert_eq!(OrderByField::Timestamp.to_string(), "timestamp");
        assert_eq!(OrderByField::Prefix.to_string(), "prefix");
        assert_eq!(OrderByField::PeerIp.to_string(), "peer_ip");
        assert_eq!(OrderByField::PeerAsn.to_string(), "peer_asn");
        assert_eq!(OrderByField::AsPath.to_string(), "as_path");
        assert_eq!(OrderByField::NextHop.to_string(), "next_hop");
    }

    #[test]
    fn test_order_direction_from_str() {
        assert_eq!(
            OrderDirection::from_str("asc").unwrap(),
            OrderDirection::Asc
        );
        assert_eq!(
            OrderDirection::from_str("ascending").unwrap(),
            OrderDirection::Asc
        );
        assert_eq!(
            OrderDirection::from_str("desc").unwrap(),
            OrderDirection::Desc
        );
        assert_eq!(
            OrderDirection::from_str("descending").unwrap(),
            OrderDirection::Desc
        );
        assert!(OrderDirection::from_str("invalid").is_err());
    }

    #[test]
    fn test_order_direction_display() {
        assert_eq!(OrderDirection::Asc.to_string(), "asc");
        assert_eq!(OrderDirection::Desc.to_string(), "desc");
    }

    #[test]
    fn test_timestamp_format_from_str() {
        assert_eq!(
            TimestampFormat::from_str("unix").unwrap(),
            TimestampFormat::Unix
        );
        assert_eq!(
            TimestampFormat::from_str("ts").unwrap(),
            TimestampFormat::Unix
        );
        assert_eq!(
            TimestampFormat::from_str("rfc3339").unwrap(),
            TimestampFormat::Rfc3339
        );
        assert_eq!(
            TimestampFormat::from_str("iso8601").unwrap(),
            TimestampFormat::Rfc3339
        );
        assert_eq!(
            TimestampFormat::from_str("iso").unwrap(),
            TimestampFormat::Rfc3339
        );
        assert!(TimestampFormat::from_str("invalid").is_err());
    }

    #[test]
    fn test_timestamp_format_display() {
        assert_eq!(TimestampFormat::Unix.to_string(), "unix");
        assert_eq!(TimestampFormat::Rfc3339.to_string(), "rfc3339");
    }

    #[test]
    fn test_timestamp_format_unix() {
        let format = TimestampFormat::Unix;
        assert_eq!(format.format_timestamp(1697043600.0), "1697043600");
        assert_eq!(format.format_timestamp(1697043600.5), "1697043600.5");
    }

    #[test]
    fn test_timestamp_format_rfc3339() {
        let format = TimestampFormat::Rfc3339;
        // 1697043600 = 2023-10-11T17:00:00Z (UTC)
        let result = format.format_timestamp(1697043600.0);
        assert!(result.starts_with("2023-10-11T17:00:00"));
        assert!(result.ends_with("Z") || result.contains("+00:00"));
    }

    #[test]
    fn test_timestamp_format_default() {
        assert_eq!(TimestampFormat::default(), TimestampFormat::Unix);
    }
}