nautilus-core 0.56.0

Core functionality for the Nautilus trading engine
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
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! A `UnixNanos` type for working with timestamps in nanoseconds since the UNIX epoch.
//!
//! This module provides a strongly-typed representation of timestamps as nanoseconds
//! since the UNIX epoch (January 1, 1970, 00:00:00 UTC). The `UnixNanos` type offers
//! conversion utilities, arithmetic operations, and comparison methods.
//!
//! # Features
//!
//! - Zero-cost abstraction with appropriate operator implementations.
//! - Conversion to/from `DateTime<Utc>`.
//! - RFC 3339 string formatting.
//! - Duration calculations.
//! - Flexible parsing and serialization.
//!
//! # Parsing and Serialization
#![expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap
)]
//!
//! `UnixNanos` can be created from and serialized to various formats:
//!
//! * Integer values are interpreted as nanoseconds since the UNIX epoch.
//! * Floating-point values are interpreted as seconds since the UNIX epoch (converted to nanoseconds
//!   using truncation, not rounding, for consistency with [`secs_to_nanos`](crate::datetime::secs_to_nanos)).
//! * String values may be:
//!   - A numeric string (interpreted as nanoseconds).
//!   - A floating-point string (interpreted as seconds, converted to nanoseconds).
//!   - An RFC 3339 formatted timestamp (ISO 8601 with timezone).
//!   - A simple date string in YYYY-MM-DD format (interpreted as midnight UTC on that date).
//!
//! # Limitations
//!
//! * Negative timestamps are invalid and will result in an error.
//! * Arithmetic operations will panic on overflow/underflow rather than wrapping.
//! * The `as_i64()` method and `DateTime<Utc>` conversions will panic for timestamps
//!   beyond approximately year 2262 (when nanoseconds exceed `i64::MAX`).

use std::{
    cmp::Ordering,
    fmt::Display,
    ops::{Add, AddAssign, Deref, Sub, SubAssign},
    str::FromStr,
    time::SystemTime,
};

use chrono::{DateTime, NaiveDate, Utc};
use serde::{
    Deserialize, Deserializer, Serialize,
    de::{self, Visitor},
};

use crate::datetime::{NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND};

/// Represents a duration in nanoseconds.
pub type DurationNanos = u64;

/// Represents a timestamp in nanoseconds since the UNIX epoch.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct UnixNanos(u64);

impl UnixNanos {
    /// Creates a new [`UnixNanos`] instance.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Creates a new [`UnixNanos`] instance with the maximum valid value.
    #[must_use]
    pub const fn max() -> Self {
        Self(u64::MAX)
    }

    /// Returns `true` if the value of this instance is zero.
    #[must_use]
    pub const fn is_zero(&self) -> bool {
        self.0 == 0
    }

    /// Returns the underlying value as `u64`.
    #[must_use]
    pub const fn as_u64(&self) -> u64 {
        self.0
    }

    /// Creates a new [`UnixNanos`] from a millisecond timestamp.
    ///
    /// # Panics
    ///
    /// Panics if the result overflows `u64`.
    #[must_use]
    pub const fn from_millis(millis: u64) -> Self {
        match millis.checked_mul(NANOSECONDS_IN_MILLISECOND) {
            Some(nanos) => Self(nanos),
            None => panic!("UnixNanos overflow in from_millis"),
        }
    }

    /// Creates a new [`UnixNanos`] from a microsecond timestamp.
    ///
    /// # Panics
    ///
    /// Panics if the result overflows `u64`.
    #[must_use]
    pub const fn from_micros(micros: u64) -> Self {
        match micros.checked_mul(NANOSECONDS_IN_MICROSECOND) {
            Some(nanos) => Self(nanos),
            None => panic!("UnixNanos overflow in from_micros"),
        }
    }

    /// Returns the underlying value as `i64`.
    ///
    /// # Panics
    ///
    /// Panics if the value exceeds `i64::MAX` (approximately year 2262).
    #[must_use]
    pub const fn as_i64(&self) -> i64 {
        assert!(
            self.0 <= i64::MAX as u64,
            "UnixNanos value exceeds i64::MAX"
        );
        self.0 as i64
    }

    /// Returns the underlying value as `f64`.
    #[must_use]
    pub const fn as_f64(&self) -> f64 {
        self.0 as f64
    }

    /// Converts the underlying value to a datetime (UTC).
    ///
    /// # Panics
    ///
    /// Panics if the value exceeds `i64::MAX` (approximately year 2262).
    #[must_use]
    pub const fn to_datetime_utc(&self) -> DateTime<Utc> {
        DateTime::from_timestamp_nanos(self.as_i64())
    }

    /// Converts the underlying value to an ISO 8601 (RFC 3339) string.
    #[must_use]
    pub fn to_rfc3339(&self) -> String {
        self.to_datetime_utc().to_rfc3339()
    }

    /// Calculates the duration in nanoseconds since another [`UnixNanos`] instance.
    ///
    /// Returns `Some(duration)` if `self` is later than `other`, otherwise `None` if `other` is
    /// greater than `self` (indicating a negative duration is not possible with `DurationNanos`).
    #[must_use]
    pub const fn duration_since(&self, other: &Self) -> Option<DurationNanos> {
        self.0.checked_sub(other.0)
    }

    fn parse_string(s: &str) -> Result<Self, String> {
        const MAX_NS_F64: f64 = u64::MAX as f64;

        // Try parsing as an integer (nanoseconds)
        if let Ok(int_value) = s.parse::<u64>() {
            return Ok(Self(int_value));
        }

        // If the string is composed solely of digits but didn't fit in a u64 we
        // treat that as an overflow error rather than attempting to interpret
        // it as seconds in floating-point form. This avoids the surprising
        // situation where a caller provides nanoseconds but gets an out-of-
        // range float interpretation instead.
        if s.chars().all(|c| c.is_ascii_digit()) {
            return Err("Unix timestamp is out of range".into());
        }

        // Try parsing as a floating point number (seconds)
        if let Ok(float_value) = s.parse::<f64>() {
            if !float_value.is_finite() {
                return Err("Unix timestamp must be finite".into());
            }

            if float_value < 0.0 {
                return Err("Unix timestamp cannot be negative".into());
            }

            // Convert seconds to nanoseconds while checking for overflow
            // We perform the multiplication in `f64`, then validate the
            // result fits inside `u64` *before* rounding / casting.
            let nanos_f64 = float_value * 1_000_000_000.0;

            if nanos_f64 > MAX_NS_F64 {
                return Err("Unix timestamp is out of range".into());
            }

            let nanos = nanos_f64.trunc() as u64;
            return Ok(Self(nanos));
        }

        // Try parsing as an RFC 3339 timestamp
        if let Ok(datetime) = DateTime::parse_from_rfc3339(s) {
            let nanos = datetime
                .timestamp_nanos_opt()
                .ok_or_else(|| "Timestamp out of range".to_string())?;

            if nanos < 0 {
                return Err("Unix timestamp cannot be negative".into());
            }

            // Checked that nanos >= 0, so cast to u64 is safe
            return Ok(Self(nanos as u64));
        }

        // Try parsing as a simple date string (YYYY-MM-DD format)
        if let Ok(datetime) = NaiveDate::parse_from_str(s, "%Y-%m-%d")
            // SAFETY: unwrap() is safe here because and_hms_opt(0, 0, 0) always succeeds
            // for valid dates (midnight is always a valid time)
            .map(|date| date.and_hms_opt(0, 0, 0).unwrap())
            .map(|naive_dt| DateTime::<Utc>::from_naive_utc_and_offset(naive_dt, Utc))
        {
            let nanos = datetime
                .timestamp_nanos_opt()
                .ok_or_else(|| "Timestamp out of range".to_string())?;

            if nanos < 0 {
                return Err("Unix timestamp cannot be negative".into());
            }
            return Ok(Self(nanos as u64));
        }

        Err(format!("Invalid format: {s}"))
    }

    /// Returns `Some(self + rhs)` or `None` if the addition would overflow
    #[must_use]
    pub fn checked_add<T: Into<u64>>(self, rhs: T) -> Option<Self> {
        self.0.checked_add(rhs.into()).map(Self)
    }

    /// Returns `Some(self - rhs)` or `None` if the subtraction would underflow
    #[must_use]
    pub fn checked_sub<T: Into<u64>>(self, rhs: T) -> Option<Self> {
        self.0.checked_sub(rhs.into()).map(Self)
    }

    /// Saturating addition – if overflow occurs the value is clamped to `u64::MAX`.
    #[must_use]
    pub fn saturating_add_ns<T: Into<u64>>(self, rhs: T) -> Self {
        Self(self.0.saturating_add(rhs.into()))
    }

    /// Saturating subtraction – if underflow occurs the value is clamped to `0`.
    #[must_use]
    pub fn saturating_sub_ns<T: Into<u64>>(self, rhs: T) -> Self {
        Self(self.0.saturating_sub(rhs.into()))
    }
}

impl Deref for UnixNanos {
    type Target = u64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PartialEq<u64> for UnixNanos {
    fn eq(&self, other: &u64) -> bool {
        self.0 == *other
    }
}

impl PartialOrd<u64> for UnixNanos {
    fn partial_cmp(&self, other: &u64) -> Option<Ordering> {
        self.0.partial_cmp(other)
    }
}

impl PartialEq<Option<u64>> for UnixNanos {
    fn eq(&self, other: &Option<u64>) -> bool {
        match other {
            Some(value) => self.0 == *value,
            None => false,
        }
    }
}

impl PartialOrd<Option<u64>> for UnixNanos {
    fn partial_cmp(&self, other: &Option<u64>) -> Option<Ordering> {
        match other {
            Some(value) => self.0.partial_cmp(value),
            None => Some(Ordering::Greater),
        }
    }
}

impl PartialEq<UnixNanos> for u64 {
    fn eq(&self, other: &UnixNanos) -> bool {
        *self == other.0
    }
}

impl PartialOrd<UnixNanos> for u64 {
    fn partial_cmp(&self, other: &UnixNanos) -> Option<Ordering> {
        self.partial_cmp(&other.0)
    }
}

impl From<u64> for UnixNanos {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl From<UnixNanos> for u64 {
    fn from(value: UnixNanos) -> Self {
        value.0
    }
}

/// Converts a string slice to [`UnixNanos`].
///
/// # Panics
///
/// This implementation will panic if the string cannot be parsed into a valid [`UnixNanos`].
/// This is intentional fail-fast behavior where invalid timestamps indicate a critical
/// logic error that should halt execution rather than silently propagate incorrect data.
///
/// For error handling without panicking, use [`str::parse::<UnixNanos>()`] which returns
/// a [`Result`].
impl From<&str> for UnixNanos {
    fn from(value: &str) -> Self {
        value
            .parse()
            .unwrap_or_else(|e| panic!("Failed to parse string '{value}' into UnixNanos: {e}. Use str::parse() for non-panicking error handling."))
    }
}

/// Converts a [`String`] to [`UnixNanos`].
///
/// # Panics
///
/// This implementation will panic if the string cannot be parsed into a valid [`UnixNanos`].
/// This is intentional fail-fast behavior where invalid timestamps indicate a critical
/// logic error that should halt execution rather than silently propagate incorrect data.
///
/// For error handling without panicking, use [`str::parse::<UnixNanos>()`] which returns
/// a [`Result`].
impl From<String> for UnixNanos {
    fn from(value: String) -> Self {
        value
            .parse()
            .unwrap_or_else(|e| panic!("Failed to parse string '{value}' into UnixNanos: {e}. Use str::parse() for non-panicking error handling."))
    }
}

impl From<DateTime<Utc>> for UnixNanos {
    fn from(value: DateTime<Utc>) -> Self {
        let nanos = value
            .timestamp_nanos_opt()
            .expect("DateTime timestamp out of range for UnixNanos");

        assert!(nanos >= 0, "DateTime timestamp cannot be negative: {nanos}");

        Self::from(nanos as u64)
    }
}

impl From<SystemTime> for UnixNanos {
    fn from(value: SystemTime) -> Self {
        let duration = value
            .duration_since(std::time::UNIX_EPOCH)
            .expect("SystemTime before UNIX EPOCH");

        let nanos = duration.as_nanos();
        assert!(
            nanos <= u128::from(u64::MAX),
            "SystemTime overflowed u64 nanoseconds"
        );

        Self::from(nanos as u64)
    }
}

impl FromStr for UnixNanos {
    type Err = Box<dyn std::error::Error>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_string(s).map_err(std::convert::Into::into)
    }
}

/// Adds two [`UnixNanos`] values.
///
/// # Panics
///
/// Panics on overflow. This is intentional fail-fast behavior: overflow in timestamp
/// arithmetic indicates a logic error in calculations that would corrupt data.
/// Use [`UnixNanos::checked_add()`] or [`UnixNanos::saturating_add_ns()`] if you need
/// explicit overflow handling.
impl Add for UnixNanos {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(
            self.0
                .checked_add(rhs.0)
                .expect("UnixNanos overflow in addition - invalid timestamp calculation"),
        )
    }
}

/// Subtracts one [`UnixNanos`] from another.
///
/// # Panics
///
/// Panics on underflow. This is intentional fail-fast behavior: underflow in timestamp
/// arithmetic indicates a logic error in calculations that would corrupt data.
/// Use [`UnixNanos::checked_sub()`] or [`UnixNanos::saturating_sub_ns()`] if you need
/// explicit underflow handling.
impl Sub for UnixNanos {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Self(
            self.0
                .checked_sub(rhs.0)
                .expect("UnixNanos underflow in subtraction - invalid timestamp calculation"),
        )
    }
}

/// Adds a `u64` nanosecond value to [`UnixNanos`].
///
/// # Panics
///
/// Panics on overflow. This is intentional fail-fast behavior for timestamp arithmetic.
/// Use [`UnixNanos::checked_add()`] for explicit overflow handling.
impl Add<u64> for UnixNanos {
    type Output = Self;

    fn add(self, rhs: u64) -> Self::Output {
        Self(
            self.0
                .checked_add(rhs)
                .expect("UnixNanos overflow in addition"),
        )
    }
}

/// Subtracts a `u64` nanosecond value from [`UnixNanos`].
///
/// # Panics
///
/// Panics on underflow. This is intentional fail-fast behavior for timestamp arithmetic.
/// Use [`UnixNanos::checked_sub()`] for explicit underflow handling.
impl Sub<u64> for UnixNanos {
    type Output = Self;

    fn sub(self, rhs: u64) -> Self::Output {
        Self(
            self.0
                .checked_sub(rhs)
                .expect("UnixNanos underflow in subtraction"),
        )
    }
}

/// Add-assigns a value to [`UnixNanos`].
///
/// # Panics
///
/// Panics on overflow. This is intentional fail-fast behavior for timestamp arithmetic.
impl<T: Into<u64>> AddAssign<T> for UnixNanos {
    fn add_assign(&mut self, other: T) {
        let other_u64 = other.into();
        self.0 = self
            .0
            .checked_add(other_u64)
            .expect("UnixNanos overflow in add_assign");
    }
}

/// Sub-assigns a value from [`UnixNanos`].
///
/// # Panics
///
/// Panics on underflow. This is intentional fail-fast behavior for timestamp arithmetic.
impl<T: Into<u64>> SubAssign<T> for UnixNanos {
    fn sub_assign(&mut self, other: T) {
        let other_u64 = other.into();
        self.0 = self
            .0
            .checked_sub(other_u64)
            .expect("UnixNanos underflow in sub_assign");
    }
}

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

impl From<UnixNanos> for DateTime<Utc> {
    fn from(value: UnixNanos) -> Self {
        value.to_datetime_utc()
    }
}

impl<'de> Deserialize<'de> for UnixNanos {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct UnixNanosVisitor;

        impl Visitor<'_> for UnixNanosVisitor {
            type Value = UnixNanos;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("an integer, a string integer, or an RFC 3339 timestamp")
            }

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

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

            fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                const MAX_NS_F64: f64 = u64::MAX as f64;

                if !value.is_finite() {
                    return Err(E::custom(format!(
                        "Unix timestamp must be finite, was {value}"
                    )));
                }

                if value < 0.0 {
                    return Err(E::custom("Unix timestamp cannot be negative"));
                }

                // Convert from seconds to nanoseconds with overflow check
                let nanos_f64 = value * 1_000_000_000.0;
                if nanos_f64 > MAX_NS_F64 {
                    return Err(E::custom(format!(
                        "Unix timestamp {value} seconds is out of range"
                    )));
                }
                let nanos = nanos_f64.trunc() as u64;
                Ok(UnixNanos(nanos))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                UnixNanos::parse_string(value).map_err(E::custom)
            }
        }

        deserializer.deserialize_any(UnixNanosVisitor)
    }
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, TimeZone};
    use rstest::rstest;

    use super::*;

    #[rstest]
    fn test_new() {
        let nanos = UnixNanos::new(123);
        assert_eq!(nanos.as_u64(), 123);
        assert_eq!(nanos.as_i64(), 123);
    }

    #[rstest]
    fn test_max() {
        let nanos = UnixNanos::max();
        assert_eq!(nanos.as_u64(), u64::MAX);
    }

    #[rstest]
    fn test_is_zero() {
        assert!(UnixNanos::default().is_zero());
        assert!(!UnixNanos::max().is_zero());
    }

    #[rstest]
    fn test_from_u64() {
        let nanos = UnixNanos::from(123);
        assert_eq!(nanos.as_u64(), 123);
        assert_eq!(nanos.as_i64(), 123);
    }

    #[rstest]
    fn test_default() {
        let nanos = UnixNanos::default();
        assert_eq!(nanos.as_u64(), 0);
        assert_eq!(nanos.as_i64(), 0);
    }

    #[rstest]
    fn test_into_from() {
        let nanos: UnixNanos = 456.into();
        let value: u64 = nanos.into();
        assert_eq!(value, 456);
    }

    #[rstest]
    #[case(0, "1970-01-01T00:00:00+00:00")]
    #[case(1_000_000_000, "1970-01-01T00:00:01+00:00")]
    #[case(1_000_000_000_000_000_000, "2001-09-09T01:46:40+00:00")]
    #[case(1_500_000_000_000_000_000, "2017-07-14T02:40:00+00:00")]
    #[case(1_707_577_123_456_789_000, "2024-02-10T14:58:43.456789+00:00")]
    fn test_to_datetime_utc(#[case] nanos: u64, #[case] expected: &str) {
        let nanos = UnixNanos::from(nanos);
        let datetime = nanos.to_datetime_utc();
        assert_eq!(datetime.to_rfc3339(), expected);
    }

    #[rstest]
    #[case(0, "1970-01-01T00:00:00+00:00")]
    #[case(1_000_000_000, "1970-01-01T00:00:01+00:00")]
    #[case(1_000_000_000_000_000_000, "2001-09-09T01:46:40+00:00")]
    #[case(1_500_000_000_000_000_000, "2017-07-14T02:40:00+00:00")]
    #[case(1_707_577_123_456_789_000, "2024-02-10T14:58:43.456789+00:00")]
    fn test_to_rfc3339(#[case] nanos: u64, #[case] expected: &str) {
        let nanos = UnixNanos::from(nanos);
        assert_eq!(nanos.to_rfc3339(), expected);
    }

    #[rstest]
    fn test_from_str() {
        let nanos: UnixNanos = "123".parse().unwrap();
        assert_eq!(nanos.as_u64(), 123);
    }

    #[rstest]
    fn test_from_str_invalid() {
        let result = "abc".parse::<UnixNanos>();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_from_str_pre_epoch_date() {
        let err = "1969-12-31".parse::<UnixNanos>().unwrap_err();
        assert_eq!(err.to_string(), "Unix timestamp cannot be negative");
    }

    #[rstest]
    fn test_from_str_pre_epoch_rfc3339() {
        let err = "1969-12-31T23:59:59Z".parse::<UnixNanos>().unwrap_err();
        assert_eq!(err.to_string(), "Unix timestamp cannot be negative");
    }

    #[rstest]
    fn test_try_from_datetime_valid() {
        use chrono::TimeZone;
        let datetime = Utc.timestamp_opt(1_000_000_000, 0).unwrap(); // 1 billion seconds since epoch
        let nanos = UnixNanos::from(datetime);
        assert_eq!(nanos.as_u64(), 1_000_000_000_000_000_000);
    }

    #[rstest]
    fn test_from_system_time() {
        let system_time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000);
        let nanos = UnixNanos::from(system_time);
        assert_eq!(nanos.as_u64(), 1_000_000_000_000_000_000);
    }

    #[rstest]
    #[should_panic(expected = "SystemTime before UNIX EPOCH")]
    fn test_from_system_time_before_epoch() {
        let system_time = std::time::UNIX_EPOCH - std::time::Duration::from_secs(1);
        let _ = UnixNanos::from(system_time);
    }

    #[rstest]
    fn test_eq() {
        let nanos = UnixNanos::from(100);
        assert_eq!(nanos, 100);
        assert_eq!(nanos, Some(100));
        assert_ne!(nanos, 200);
        assert_ne!(nanos, Some(200));
        assert_ne!(nanos, None);
    }

    #[rstest]
    fn test_partial_cmp() {
        let nanos = UnixNanos::from(100);
        assert_eq!(nanos.partial_cmp(&100), Some(Ordering::Equal));
        assert_eq!(nanos.partial_cmp(&200), Some(Ordering::Less));
        assert_eq!(nanos.partial_cmp(&50), Some(Ordering::Greater));
        assert_eq!(nanos.partial_cmp(&None), Some(Ordering::Greater));
    }

    #[rstest]
    fn test_edge_case_max_value() {
        let nanos = UnixNanos::from(u64::MAX);
        assert_eq!(format!("{nanos}"), format!("{}", u64::MAX));
    }

    #[rstest]
    fn test_display() {
        let nanos = UnixNanos::from(123);
        assert_eq!(format!("{nanos}"), "123");
    }

    #[rstest]
    fn test_addition() {
        let nanos1 = UnixNanos::from(100);
        let nanos2 = UnixNanos::from(200);
        let result = nanos1 + nanos2;
        assert_eq!(result.as_u64(), 300);
    }

    #[rstest]
    fn test_add_assign() {
        let mut nanos = UnixNanos::from(100);
        nanos += 50_u64;
        assert_eq!(nanos.as_u64(), 150);
    }

    #[rstest]
    fn test_subtraction() {
        let nanos1 = UnixNanos::from(200);
        let nanos2 = UnixNanos::from(100);
        let result = nanos1 - nanos2;
        assert_eq!(result.as_u64(), 100);
    }

    #[rstest]
    fn test_sub_assign() {
        let mut nanos = UnixNanos::from(200);
        nanos -= 50_u64;
        assert_eq!(nanos.as_u64(), 150);
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos overflow")]
    fn test_overflow_add() {
        let nanos = UnixNanos::from(u64::MAX);
        let _ = nanos + UnixNanos::from(1); // This should panic due to overflow
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos overflow")]
    fn test_overflow_add_u64() {
        let nanos = UnixNanos::from(u64::MAX);
        let _ = nanos + 1_u64; // This should panic due to overflow
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos underflow")]
    fn test_overflow_sub() {
        let _ = UnixNanos::default() - UnixNanos::from(1); // This should panic due to underflow
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos underflow")]
    fn test_overflow_sub_u64() {
        let _ = UnixNanos::default() - 1_u64; // This should panic due to underflow
    }

    #[rstest]
    #[case(100, 50, Some(50))]
    #[case(1_000_000_000, 500_000_000, Some(500_000_000))]
    #[case(u64::MAX, u64::MAX - 1, Some(1))]
    #[case(50, 50, Some(0))]
    #[case(50, 100, None)]
    #[case(0, 1, None)]
    fn test_duration_since(
        #[case] time1: u64,
        #[case] time2: u64,
        #[case] expected: Option<DurationNanos>,
    ) {
        let nanos1 = UnixNanos::from(time1);
        let nanos2 = UnixNanos::from(time2);
        assert_eq!(nanos1.duration_since(&nanos2), expected);
    }

    #[rstest]
    fn test_duration_since_same_moment() {
        let moment = UnixNanos::from(1_707_577_123_456_789_000);
        assert_eq!(moment.duration_since(&moment), Some(0));
    }

    #[rstest]
    fn test_duration_since_chronological() {
        // Create a reference time (Feb 10, 2024)
        let earlier = Utc.with_ymd_and_hms(2024, 2, 10, 12, 0, 0).unwrap();

        // Create a time 1 hour, 30 minutes, and 45 seconds later (with nanoseconds)
        let later = earlier
            + Duration::hours(1)
            + Duration::minutes(30)
            + Duration::seconds(45)
            + Duration::nanoseconds(500_000_000);

        let earlier_nanos = UnixNanos::from(earlier);
        let later_nanos = UnixNanos::from(later);

        // Calculate expected duration in nanoseconds
        let expected_duration = 60 * 60 * 1_000_000_000 + // 1 hour
        30 * 60 * 1_000_000_000 + // 30 minutes
        45 * 1_000_000_000 + // 45 seconds
        500_000_000; // 500 million nanoseconds

        assert_eq!(
            later_nanos.duration_since(&earlier_nanos),
            Some(expected_duration)
        );
        assert_eq!(earlier_nanos.duration_since(&later_nanos), None);
    }

    #[rstest]
    fn test_duration_since_with_edge_cases() {
        // Test with maximum value
        let max = UnixNanos::from(u64::MAX);
        let smaller = UnixNanos::from(u64::MAX - 1000);

        assert_eq!(max.duration_since(&smaller), Some(1000));
        assert_eq!(smaller.duration_since(&max), None);

        // Test with minimum value
        let min = UnixNanos::default(); // Zero timestamp
        let larger = UnixNanos::from(1000);

        assert_eq!(min.duration_since(&min), Some(0));
        assert_eq!(larger.duration_since(&min), Some(1000));
        assert_eq!(min.duration_since(&larger), None);
    }

    #[rstest]
    fn test_serde_json() {
        let nanos = UnixNanos::from(123);
        let json = serde_json::to_string(&nanos).unwrap();
        let deserialized: UnixNanos = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, nanos);
    }

    #[rstest]
    fn test_serde_edge_cases() {
        let nanos = UnixNanos::from(u64::MAX);
        let json = serde_json::to_string(&nanos).unwrap();
        let deserialized: UnixNanos = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, nanos);
    }

    #[rstest]
    #[case("123", 123)] // Integer string
    #[case("1234.567", 1_234_567_000_000)] // Float string (seconds to nanos)
    #[case("2024-02-10", 1_707_523_200_000_000_000)] // Simple date (midnight UTC)
    #[case("2024-02-10T14:58:43Z", 1_707_577_123_000_000_000)] // RFC3339 without fractions
    #[case("2024-02-10T14:58:43.456789Z", 1_707_577_123_456_789_000)] // RFC3339 with fractions
    fn test_from_str_formats(#[case] input: &str, #[case] expected: u64) {
        let parsed: UnixNanos = input.parse().unwrap();
        assert_eq!(parsed.as_u64(), expected);
    }

    #[rstest]
    #[case("abc")] // Random string
    #[case("not a timestamp")] // Non-timestamp string
    #[case("2024-02-10 14:58:43")] // Space-separated format (not RFC3339)
    fn test_from_str_invalid_formats(#[case] input: &str) {
        let result = input.parse::<UnixNanos>();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_from_str_integer_overflow() {
        // One more digit than u64::MAX (20 digits) so definitely overflows
        let input = "184467440737095516160";
        let result = input.parse::<UnixNanos>();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_checked_add_overflow_returns_none() {
        let max = UnixNanos::from(u64::MAX);
        assert_eq!(max.checked_add(1_u64), None);
    }

    #[rstest]
    fn test_checked_sub_underflow_returns_none() {
        let zero = UnixNanos::default();
        assert_eq!(zero.checked_sub(1_u64), None);
    }

    #[rstest]
    fn test_saturating_add_overflow() {
        let max = UnixNanos::from(u64::MAX);
        let result = max.saturating_add_ns(1_u64);
        assert_eq!(result, UnixNanos::from(u64::MAX));
    }

    #[rstest]
    fn test_saturating_sub_underflow() {
        let zero = UnixNanos::default();
        let result = zero.saturating_sub_ns(1_u64);
        assert_eq!(result, UnixNanos::default());
    }

    #[rstest]
    fn test_from_str_float_overflow() {
        // Use scientific notation so we take the floating-point parsing path.
        let input = "2e10"; // 20 billion seconds ~ 634 years (> u64::MAX nanoseconds)
        let result = input.parse::<UnixNanos>();
        assert!(result.is_err());
    }

    #[rstest]
    fn test_deserialize_u64() {
        let json = "123456789";
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), 123_456_789);
    }

    #[rstest]
    fn test_deserialize_string_with_int() {
        let json = "\"123456789\"";
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), 123_456_789);
    }

    #[rstest]
    fn test_deserialize_float() {
        let json = "1234.567";
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), 1_234_567_000_000);
    }

    #[rstest]
    fn test_deserialize_string_with_float() {
        let json = "\"1234.567\"";
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), 1_234_567_000_000);
    }

    #[rstest]
    fn test_deserialize_float_uses_truncation() {
        // Truncation (not rounding) for consistency with secs_to_nanos() etc
        let json = "0.9999999999";
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), 999_999_999); // Truncated, not rounded to 1B
    }

    #[rstest]
    #[case("\"2024-02-10T14:58:43.456789Z\"", 1_707_577_123_456_789_000)]
    #[case("\"2024-02-10T14:58:43Z\"", 1_707_577_123_000_000_000)]
    fn test_deserialize_timestamp_strings(#[case] input: &str, #[case] expected: u64) {
        let deserialized: UnixNanos = serde_json::from_str(input).unwrap();
        assert_eq!(deserialized.as_u64(), expected);
    }

    #[rstest]
    fn test_deserialize_negative_int_fails() {
        let json = "-123456789";
        let result: Result<UnixNanos, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[rstest]
    fn test_deserialize_negative_float_fails() {
        let json = "-1234.567";
        let result: Result<UnixNanos, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[rstest]
    fn test_deserialize_nan_fails() {
        // JSON doesn't support NaN directly, test the internal deserializer
        use serde::de::{
            IntoDeserializer,
            value::{Error as ValueError, F64Deserializer},
        };
        let deserializer: F64Deserializer<ValueError> = f64::NAN.into_deserializer();
        let result: Result<UnixNanos, _> = UnixNanos::deserialize(deserializer);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be finite"));
    }

    #[rstest]
    fn test_deserialize_infinity_fails() {
        use serde::de::{
            IntoDeserializer,
            value::{Error as ValueError, F64Deserializer},
        };
        let deserializer: F64Deserializer<ValueError> = f64::INFINITY.into_deserializer();
        let result: Result<UnixNanos, _> = UnixNanos::deserialize(deserializer);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be finite"));
    }

    #[rstest]
    fn test_deserialize_negative_infinity_fails() {
        use serde::de::{
            IntoDeserializer,
            value::{Error as ValueError, F64Deserializer},
        };
        let deserializer: F64Deserializer<ValueError> = f64::NEG_INFINITY.into_deserializer();
        let result: Result<UnixNanos, _> = UnixNanos::deserialize(deserializer);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be finite"));
    }

    #[rstest]
    fn test_deserialize_overflow_float_fails() {
        // Test a float that would overflow u64 when converted to nanoseconds
        // u64::MAX is ~18.4e18, so u64::MAX / 1e9 = ~18.4e9 seconds
        let result: Result<UnixNanos, _> = serde_json::from_str("1e20");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of range"));
    }

    #[rstest]
    fn test_deserialize_invalid_string_fails() {
        let json = "\"not a timestamp\"";
        let result: Result<UnixNanos, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[rstest]
    fn test_deserialize_edge_cases() {
        // Test zero
        let json = "0";
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), 0);

        // Test large value
        let json = "18446744073709551615"; // u64::MAX
        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
        assert_eq!(deserialized.as_u64(), u64::MAX);
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos value exceeds i64::MAX")]
    fn test_as_i64_overflow_panics() {
        let nanos = UnixNanos::from(u64::MAX);
        let _ = nanos.as_i64(); // Should panic
    }

    use proptest::prelude::*;

    fn unix_nanos_strategy() -> impl Strategy<Value = UnixNanos> {
        prop_oneof![
            // Small values
            0u64..1_000_000u64,
            // Medium values (microseconds range)
            1_000_000u64..1_000_000_000_000u64,
            // Large values (nanoseconds since 1970)
            1_000_000_000_000u64..=i64::MAX as u64,
            // Values above i64::MAX (sentinel range, GTC/infinity)
            (i64::MAX as u64 + 1)..=u64::MAX,
            // Edge cases
            Just(0u64),
            Just(1u64),
            Just(1_000_000_000u64),             // 1 second in nanos
            Just(1_000_000_000_000u64),         // ~2001 timestamp
            Just(1_700_000_000_000_000_000u64), // ~2023 timestamp
            Just((i64::MAX / 2) as u64),        // Safe for doubling
            Just(i64::MAX as u64),              // i64 boundary
            Just(u64::MAX),                     // Sentinel / max value
        ]
        .prop_map(UnixNanos::from)
    }

    fn unix_nanos_pair_strategy() -> impl Strategy<Value = (UnixNanos, UnixNanos)> {
        (unix_nanos_strategy(), unix_nanos_strategy())
    }

    proptest! {
        #[rstest]
        #[expect(
            clippy::float_cmp,
            reason = "roundtrip: both sides go through the same u64->f64 cast"
        )]
        fn prop_unix_nanos_construction_roundtrip(nanos in unix_nanos_strategy()) {
            let value = nanos.as_u64();
            prop_assert_eq!(UnixNanos::from(value).as_u64(), value);
            prop_assert_eq!(nanos.as_f64(), value as f64);

            // Test i64 conversion only for values within i64 range
            if i64::try_from(value).is_ok() {
                prop_assert_eq!(nanos.as_i64(), value as i64);
            }
        }

        #[rstest]
        fn prop_unix_nanos_addition_commutative(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // Addition should be commutative when no overflow occurs
            if let (Some(sum1), Some(sum2)) = (
                nanos1.checked_add(nanos2.as_u64()),
                nanos2.checked_add(nanos1.as_u64())
            ) {
                prop_assert_eq!(sum1, sum2, "Addition should be commutative");
            }
        }

        #[rstest]
        fn prop_unix_nanos_addition_associative(
            nanos1 in unix_nanos_strategy(),
            nanos2 in unix_nanos_strategy(),
            nanos3 in unix_nanos_strategy(),
        ) {
            // Addition should be associative when no overflow occurs
            if let (Some(sum1), Some(sum2)) = (
                nanos1.as_u64().checked_add(nanos2.as_u64()),
                nanos2.as_u64().checked_add(nanos3.as_u64())
            )
                && let (Some(left), Some(right)) = (
                    sum1.checked_add(nanos3.as_u64()),
                    nanos1.as_u64().checked_add(sum2)
                ) {
                    let left_result = UnixNanos::from(left);
                    let right_result = UnixNanos::from(right);
                    prop_assert_eq!(left_result, right_result, "Addition should be associative");
                }
        }

        #[rstest]
        fn prop_unix_nanos_subtraction_inverse(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // Subtraction should be the inverse of addition when no underflow occurs
            if let Some(sum) = nanos1.checked_add(nanos2.as_u64()) {
                let diff = sum - nanos2;
                prop_assert_eq!(diff, nanos1, "Subtraction should be inverse of addition");
            }
        }

        #[rstest]
        fn prop_unix_nanos_zero_identity(nanos in unix_nanos_strategy()) {
            // Zero should be additive identity
            let zero = UnixNanos::default();
            prop_assert_eq!(nanos + zero, nanos, "Zero should be additive identity");
            prop_assert_eq!(zero + nanos, nanos, "Zero should be additive identity (commutative)");
            prop_assert!(zero.is_zero(), "Zero should be recognized as zero");
        }

        #[rstest]
        fn prop_unix_nanos_ordering_consistency(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // Ordering operations should be consistent
            let eq = nanos1 == nanos2;
            let lt = nanos1 < nanos2;
            let gt = nanos1 > nanos2;
            let le = nanos1 <= nanos2;
            let ge = nanos1 >= nanos2;

            // Exactly one of eq, lt, gt should be true
            let exclusive_count = [eq, lt, gt].iter().filter(|&&x| x).count();
            prop_assert_eq!(exclusive_count, 1, "Exactly one of ==, <, > should be true");

            // Consistency checks
            prop_assert_eq!(le, eq || lt, "<= should equal == || <");
            prop_assert_eq!(ge, eq || gt, ">= should equal == || >");
            prop_assert_eq!(lt, nanos2 > nanos1, "< should be symmetric with >");
            prop_assert_eq!(le, nanos2 >= nanos1, "<= should be symmetric with >=");
        }

        #[rstest]
        fn prop_unix_nanos_string_roundtrip(nanos in unix_nanos_strategy()) {
            // String serialization should round-trip correctly
            let string_repr = nanos.to_string();
            let parsed = UnixNanos::from_str(&string_repr);
            prop_assert!(parsed.is_ok(), "String parsing should succeed for valid UnixNanos");
            if let Ok(parsed_nanos) = parsed {
                prop_assert_eq!(parsed_nanos, nanos, "String should round-trip exactly");
            }
        }

        #[rstest]
        fn prop_unix_nanos_datetime_conversion(nanos in unix_nanos_strategy()) {
            // DateTime conversion should be consistent (only test values within i64 range)
            if i64::try_from(nanos.as_u64()).is_ok() {
                let datetime = nanos.to_datetime_utc();
                let converted_back = UnixNanos::from(datetime);
                prop_assert_eq!(converted_back, nanos, "DateTime conversion should round-trip");

                // RFC3339 string should also round-trip for valid dates
                let rfc3339 = nanos.to_rfc3339();
                if let Ok(parsed_from_rfc3339) = UnixNanos::from_str(&rfc3339) {
                    prop_assert_eq!(parsed_from_rfc3339, nanos, "RFC3339 string should round-trip");
                }
            }
        }

        #[rstest]
        fn prop_unix_nanos_duration_since(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // duration_since should be consistent with comparison and arithmetic
            let duration = nanos1.duration_since(&nanos2);

            if nanos1 >= nanos2 {
                // If nanos1 >= nanos2, duration should be Some and equal to difference
                prop_assert!(duration.is_some(), "Duration should be Some when first >= second");
                if let Some(dur) = duration {
                    prop_assert_eq!(dur, nanos1.as_u64() - nanos2.as_u64(),
                        "Duration should equal the difference");
                    prop_assert_eq!(nanos2 + dur, nanos1.as_u64(),
                        "second + duration should equal first");
                }
            } else {
                // If nanos1 < nanos2, duration should be None
                prop_assert!(duration.is_none(), "Duration should be None when first < second");
            }
        }

        #[rstest]
        fn prop_unix_nanos_checked_arithmetic(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // Checked arithmetic should be consistent with regular arithmetic when no overflow/underflow
            let checked_add = nanos1.checked_add(nanos2.as_u64());
            let checked_sub = nanos1.checked_sub(nanos2.as_u64());

            // If checked_add succeeds, regular addition should produce the same result
            if let Some(sum) = checked_add
                && nanos1.as_u64().checked_add(nanos2.as_u64()).is_some() {
                    prop_assert_eq!(sum, nanos1 + nanos2, "Checked add should match regular add when no overflow");
                }

            // If checked_sub succeeds, regular subtraction should produce the same result
            if let Some(diff) = checked_sub
                && nanos1.as_u64() >= nanos2.as_u64() {
                    prop_assert_eq!(diff, nanos1 - nanos2, "Checked sub should match regular sub when no underflow");
                }
        }

        #[rstest]
        fn prop_unix_nanos_saturating_arithmetic(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // Saturating arithmetic should never panic and produce reasonable results
            let sat_add = nanos1.saturating_add_ns(nanos2.as_u64());
            let sat_sub = nanos1.saturating_sub_ns(nanos2.as_u64());

            // Saturating add should be >= both operands
            prop_assert!(sat_add >= nanos1, "Saturating add result should be >= first operand");
            prop_assert!(sat_add.as_u64() >= nanos2.as_u64(), "Saturating add result should be >= second operand");

            // Saturating sub should be <= first operand
            prop_assert!(sat_sub <= nanos1, "Saturating sub result should be <= first operand");

            // If no overflow/underflow would occur, saturating should match checked
            if let Some(checked_sum) = nanos1.checked_add(nanos2.as_u64()) {
                prop_assert_eq!(sat_add, checked_sum, "Saturating add should match checked add when no overflow");
            } else {
                prop_assert_eq!(sat_add, UnixNanos::from(u64::MAX), "Saturating add should be MAX on overflow");
            }

            if let Some(checked_diff) = nanos1.checked_sub(nanos2.as_u64()) {
                prop_assert_eq!(sat_sub, checked_diff, "Saturating sub should match checked sub when no underflow");
            } else {
                prop_assert_eq!(sat_sub, UnixNanos::default(), "Saturating sub should be zero on underflow");
            }
        }

        #[rstest]
        fn prop_unix_nanos_assign_mirrors_op(
            (nanos1, nanos2) in unix_nanos_pair_strategy()
        ) {
            // AddAssign should produce the same result as Add
            if let Some(expected) = nanos1.checked_add(nanos2.as_u64()) {
                let mut add_result = nanos1;
                add_result += nanos2;
                prop_assert_eq!(add_result, expected, "AddAssign should mirror Add");
            }

            // SubAssign should produce the same result as Sub
            if nanos1.as_u64() >= nanos2.as_u64() {
                let expected = nanos1 - nanos2;
                let mut sub_result = nanos1;
                sub_result -= nanos2;
                prop_assert_eq!(sub_result, expected, "SubAssign should mirror Sub");
            }
        }

        #[rstest]
        fn prop_unix_nanos_serde_roundtrip(nanos in unix_nanos_strategy()) {
            let json = serde_json::to_string(&nanos).unwrap();
            let deserialized: UnixNanos = serde_json::from_str(&json).unwrap();
            prop_assert_eq!(deserialized, nanos, "Serde JSON should round-trip exactly");
        }

        #[rstest]
        fn prop_unix_nanos_f64_deserialize_never_panics(val: f64) {
            // Use IntoDeserializer to hit visit_f64 directly,
            // bypassing JSON text encoding ambiguity
            use serde::de::{IntoDeserializer, value::{Error as ValueError, F64Deserializer}};
            let deserializer: F64Deserializer<ValueError> = val.into_deserializer();
            let result = UnixNanos::deserialize(deserializer);

            if val.is_finite() && val >= 0.0 && val * 1_000_000_000.0 <= u64::MAX as f64 {
                prop_assert!(result.is_ok(), "Should succeed for valid f64: {}", val);
            } else {
                prop_assert!(result.is_err(), "Should error for invalid f64: {}", val);
            }
        }
    }

    #[rstest]
    fn test_from_millis_zero() {
        let nanos = UnixNanos::from_millis(0);
        assert_eq!(nanos.as_u64(), 0);
    }

    #[rstest]
    fn test_from_millis_one() {
        let nanos = UnixNanos::from_millis(1);
        assert_eq!(nanos.as_u64(), 1_000_000);
    }

    #[rstest]
    fn test_from_millis_one_second() {
        let nanos = UnixNanos::from_millis(1_000);
        assert_eq!(nanos.as_u64(), 1_000_000_000);
    }

    #[rstest]
    fn test_from_millis_realistic_timestamp() {
        // 2023-11-14T22:13:20Z = 1700000000000 ms
        let nanos = UnixNanos::from_millis(1_700_000_000_000);
        assert_eq!(nanos.as_u64(), 1_700_000_000_000_000_000);
        assert_eq!(
            nanos.to_datetime_utc(),
            Utc.with_ymd_and_hms(2023, 11, 14, 22, 13, 20).unwrap()
        );
    }

    #[rstest]
    fn test_from_millis_max_safe() {
        let max_ms = u64::MAX / 1_000_000;
        let nanos = UnixNanos::from_millis(max_ms);
        assert_eq!(nanos.as_u64(), max_ms * 1_000_000);
    }

    #[rstest]
    fn test_from_millis_matches_manual_conversion() {
        let ms = 1_625_474_304_765_u64;
        let expected = ms * 1_000_000;
        assert_eq!(UnixNanos::from_millis(ms).as_u64(), expected);
    }

    #[rstest]
    fn test_from_micros_zero() {
        let nanos = UnixNanos::from_micros(0);
        assert_eq!(nanos.as_u64(), 0);
    }

    #[rstest]
    fn test_from_micros_one() {
        let nanos = UnixNanos::from_micros(1);
        assert_eq!(nanos.as_u64(), 1_000);
    }

    #[rstest]
    fn test_from_micros_one_second() {
        let nanos = UnixNanos::from_micros(1_000_000);
        assert_eq!(nanos.as_u64(), 1_000_000_000);
    }

    #[rstest]
    fn test_from_micros_one_millisecond() {
        let nanos = UnixNanos::from_micros(1_000);
        assert_eq!(nanos.as_u64(), 1_000_000);
        assert_eq!(UnixNanos::from_micros(1_000), UnixNanos::from_millis(1));
    }

    #[rstest]
    fn test_from_micros_realistic_timestamp() {
        let micros = 1_700_000_000_000_000_u64;
        let nanos = UnixNanos::from_micros(micros);
        assert_eq!(nanos.as_u64(), 1_700_000_000_000_000_000);
    }

    #[rstest]
    fn test_from_micros_max_safe() {
        let max_us = u64::MAX / 1_000;
        let nanos = UnixNanos::from_micros(max_us);
        assert_eq!(nanos.as_u64(), max_us * 1_000);
    }

    #[rstest]
    fn test_from_micros_matches_manual_conversion() {
        let us = 1_000_000_123_456_u64;
        let expected = us * 1_000;
        assert_eq!(UnixNanos::from_micros(us).as_u64(), expected);
    }

    #[rstest]
    fn test_from_millis_and_micros_consistency() {
        assert_eq!(
            UnixNanos::from_millis(1_000),
            UnixNanos::from_micros(1_000_000)
        );
        assert_eq!(
            UnixNanos::from_millis(60_000),
            UnixNanos::from_micros(60_000_000)
        );
    }

    #[rstest]
    fn test_from_millis_round_trip_to_datetime() {
        let ms = 1_707_577_123_456_u64;
        let nanos = UnixNanos::from_millis(ms);
        let dt = nanos.to_datetime_utc();
        assert_eq!(dt.timestamp_millis() as u64, ms);
    }

    #[rstest]
    fn test_from_micros_preserves_sub_millisecond() {
        let micros = 1_700_000_000_000_123_u64;
        let nanos = UnixNanos::from_micros(micros);
        assert_eq!(nanos.as_u64() % 1_000_000, 123_000);
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos overflow in from_millis")]
    fn test_from_millis_overflow_panics() {
        let _ = UnixNanos::from_millis(u64::MAX / 1_000_000 + 1);
    }

    #[rstest]
    #[should_panic(expected = "UnixNanos overflow in from_micros")]
    fn test_from_micros_overflow_panics() {
        let _ = UnixNanos::from_micros(u64::MAX / 1_000 + 1);
    }
}