range_date 0.2.4

A powerful Rust crate for handling date periods with embedded data and comprehensive date range operations.
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
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
use chrono::{Datelike, Duration, Months, NaiveDate};
use serde::{Deserialize, Deserializer, Serialize};

use crate::leap_year;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DatePeriod {
    /// Represents a yearly period with a specific year.
    Year(u32),
    /// Represents a quarterly period with a specific year and quarter (1-4).
    Quarter(u32, u32),
    /// Represents a monthly period with a specific year and month (1-12).
    Month(u32, u32),
    /// Represents a daily period with a specific year and day of the year (1-366).
    Daily(u32, u32),
}

impl Serialize for DatePeriod {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        serializer.serialize_str(&format!("{}", self))
    }
}

impl<'de> Deserialize<'de> for DatePeriod {
    fn deserialize<D>(deserializer: D) -> std::result::Result<DatePeriod, D::Error>
    where
        D: Deserializer<'de>,
    {
        use std::str::FromStr;
        let s = String::deserialize(deserializer)?;
        DatePeriod::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl std::str::FromStr for DatePeriod {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl std::fmt::Display for DatePeriod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DatePeriod::Year(year) => write!(f, "{}Y", year),
            DatePeriod::Quarter(year, quarter) => write!(f, "{}Q{}", year, quarter),
            DatePeriod::Month(year, month) => write!(f, "{}M{}", year, month),
            DatePeriod::Daily(year, day) => write!(f, "{}D{}", year, day),
        }
    }
}

impl DatePeriod {
    /// Create a new yearly period
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let year = DatePeriod::year(2024);
    /// assert_eq!(year.to_string(), "2024Y");
    /// ```
    pub fn year(year: u32) -> Self {
        DatePeriod::Year(year)
    }

    /// Create a new quarterly period with validation
    /// Quarter must be between 1 and 4
    ///
    /// # Errors
    ///
    /// Returns an error if `quarter` is not in the range `1..=4`.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let quarter = DatePeriod::quarter(2024, 2).unwrap();
    /// assert_eq!(quarter.to_string(), "2024Q2");
    /// ```
    pub fn quarter(year: u32, quarter: u32) -> anyhow::Result<Self> {
        if !(1..=4).contains(&quarter) {
            return Err(anyhow::anyhow!(
                "Quarter must be between 1 and 4, got: {}",
                quarter
            ));
        }
        Ok(DatePeriod::Quarter(year, quarter))
    }

    /// Create a new monthly period with validation
    /// Month must be between 1 and 12
    ///
    /// # Errors
    ///
    /// Returns an error if `month` is not in the range `1..=12`.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let month = DatePeriod::month(2024, 5).unwrap();
    /// assert_eq!(month.to_string(), "2024M5");
    /// ```
    pub fn month(year: u32, month: u32) -> anyhow::Result<Self> {
        if !(1..=12).contains(&month) {
            return Err(anyhow::anyhow!(
                "Month must be between 1 and 12, got: {}",
                month
            ));
        }
        Ok(DatePeriod::Month(year, month))
    }

    /// Create a new daily period with validation
    /// Day must be between 1 and 366 (accounting for leap years)
    ///
    /// # Errors
    ///
    /// Returns an error if `day` is `0` or exceeds the number of days in `year`
    /// (365 for common years, 366 for leap years).
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let daily = DatePeriod::daily(2024, 136).unwrap();
    /// assert_eq!(daily.to_string(), "2024D136");
    /// ```
    pub fn daily(year: u32, day: u32) -> anyhow::Result<Self> {
        if day == 0 {
            return Err(anyhow::anyhow!("Day must be greater than 0"));
        }

        let max_days = if leap_year(year as i32) { 366 } else { 365 };
        if day > max_days {
            return Err(anyhow::anyhow!(
                "Day {} is invalid for year {} (max: {})",
                day,
                year,
                max_days
            ));
        }
        Ok(DatePeriod::Daily(year, day))
    }

    /// Parse a `DatePeriod` from a string representation like `"2024Q2"`
    /// Format: `YYYYT[#]` where `T` is period type (Y/Q/M/D) and `#` is the index (optional for Y)
    ///
    /// # Errors
    ///
    /// Returns an error if the input is shorter than five characters, the year
    /// or index cannot be parsed, the period type is unknown, or the resulting
    /// period fails validation (e.g. invalid quarter/month/day).
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::parse("2024Q2").unwrap();
    /// assert_eq!(period.to_string(), "2024Q2");
    /// ```
    pub fn parse(s: &str) -> anyhow::Result<Self> {
        let s = s.trim();
        if s.len() < 5 {
            return Err(anyhow::anyhow!("Invalid format, expected YYYYT[#]: {}", s));
        }

        let year: u32 = s[0..4]
            .parse()
            .map_err(|_| anyhow::anyhow!("Invalid year in: {}", s))?;
        let period_type = &s[4..5];

        match period_type {
            "Y" => {
                // Year format is just "2024Y" - no index needed
                if s.len() != 5 {
                    return Err(anyhow::anyhow!("Year format should be YYYYY: {}", s));
                }
                Ok(Self::year(year))
            }
            "Q" | "M" | "D" => {
                if s.len() <= 5 {
                    return Err(anyhow::anyhow!("Missing index for {}: {}", period_type, s));
                }
                let index: u32 = s[5..]
                    .parse()
                    .map_err(|_| anyhow::anyhow!("Invalid index in: {}", s))?;

                match period_type {
                    "Q" => Self::quarter(year, index),
                    "M" => Self::month(year, index),
                    "D" => Self::daily(year, index),
                    _ => unreachable!(),
                }
            }
            _ => Err(anyhow::anyhow!(
                "Invalid period type '{}' in: {}",
                period_type,
                s
            )),
        }
    }

    /// Convert a `NaiveDate` to a yearly `DatePeriod`
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let date = NaiveDate::from_ymd_opt(2024, 5, 15).unwrap();
    /// let year = DatePeriod::from_date_as_year(date);
    /// assert_eq!(year.to_string(), "2024Y");
    /// ```
    pub fn from_date_as_year(date: NaiveDate) -> Self {
        Self::year(date.year() as u32)
    }

    /// Convert a `NaiveDate` to a quarterly `DatePeriod`
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let date = NaiveDate::from_ymd_opt(2024, 5, 15).unwrap();
    /// let quarter = DatePeriod::from_date_as_quarter(date);
    /// assert_eq!(quarter.to_string(), "2024Q2");
    /// ```
    pub fn from_date_as_quarter(date: NaiveDate) -> Self {
        let year = date.year() as u32;
        let month = date.month();
        let quarter = match month {
            1..=3 => 1,
            4..=6 => 2,
            7..=9 => 3,
            10..=12 => 4,
            _ => unreachable!(),
        };
        DatePeriod::Quarter(year, quarter)
    }

    /// Convert a `NaiveDate` to a monthly `DatePeriod`
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let date = NaiveDate::from_ymd_opt(2024, 5, 15).unwrap();
    /// let month = DatePeriod::from_date_as_month(date);
    /// assert_eq!(month.to_string(), "2024M5");
    /// ```
    pub fn from_date_as_month(date: NaiveDate) -> Self {
        DatePeriod::Month(date.year() as u32, date.month())
    }

    /// Convert a `NaiveDate` to a daily `DatePeriod`
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let date = NaiveDate::from_ymd_opt(2024, 5, 15).unwrap();
    /// let daily = DatePeriod::from_date_as_daily(date);
    /// assert_eq!(daily.to_string(), "2024D136");
    /// ```
    pub fn from_date_as_daily(date: NaiveDate) -> Self {
        DatePeriod::Daily(date.year() as u32, date.ordinal())
    }

    /// Generate all yearly periods between two dates (inclusive)
    /// Returns an empty vector if start > end
    ///
    /// # Errors
    ///
    /// This function currently returns `Ok` in all cases; the `Result` return
    /// type is retained for API symmetry with the other `between_date_as_*`
    /// helpers which may propagate errors from period arithmetic.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let start = NaiveDate::from_ymd_opt(2023, 6, 15).unwrap();
    /// let end = NaiveDate::from_ymd_opt(2025, 3, 10).unwrap();
    /// let years = DatePeriod::between_date_as_year(start, end).unwrap();
    /// assert_eq!(years.len(), 3);
    /// assert_eq!(years[0].to_string(), "2023Y");
    /// ```
    pub fn between_date_as_year(
        start: NaiveDate,
        end: NaiveDate,
    ) -> anyhow::Result<Vec<DatePeriod>> {
        if start > end {
            return Ok(vec![]);
        }
        let start_year = start.year() as u32;
        let end_year = end.year() as u32;
        Ok((start_year..=end_year).map(DatePeriod::year).collect())
    }

    /// Generate all quarterly periods between two dates (inclusive)
    /// Returns an empty vector if start > end
    ///
    /// # Errors
    ///
    /// Returns an error if advancing the quarterly period via [`DatePeriod::succ`]
    /// fails while iterating from `start` to `end`.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let start = NaiveDate::from_ymd_opt(2024, 4, 1).unwrap();
    /// let end = NaiveDate::from_ymd_opt(2024, 9, 30).unwrap();
    /// let quarters = DatePeriod::between_date_as_quarter(start, end).unwrap();
    /// assert_eq!(quarters.len(), 2);
    /// assert_eq!(quarters[0].to_string(), "2024Q2");
    /// ```
    pub fn between_date_as_quarter(
        start: NaiveDate,
        end: NaiveDate,
    ) -> anyhow::Result<Vec<DatePeriod>> {
        if start > end {
            return Ok(vec![]);
        }
        let mut result = vec![];
        let mut current = DatePeriod::from_date_as_quarter(start);
        let end_quarter = DatePeriod::from_date_as_quarter(end);
        while current <= end_quarter {
            result.push(current.clone());
            current = current.succ()?;
        }
        Ok(result)
    }

    /// Generate all monthly periods between two dates (inclusive)
    /// Returns an empty vector if start > end
    ///
    /// # Errors
    ///
    /// Returns an error if advancing the monthly period via [`DatePeriod::succ`]
    /// fails while iterating from `start` to `end`.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let start = NaiveDate::from_ymd_opt(2024, 2, 1).unwrap();
    /// let end = NaiveDate::from_ymd_opt(2024, 4, 30).unwrap();
    /// let months = DatePeriod::between_date_as_month(start, end).unwrap();
    /// assert_eq!(months.len(), 3);
    /// assert_eq!(months[0].to_string(), "2024M2");
    /// ```
    pub fn between_date_as_month(
        start: NaiveDate,
        end: NaiveDate,
    ) -> anyhow::Result<Vec<DatePeriod>> {
        if start > end {
            return Ok(vec![]);
        }
        let mut result = vec![];
        let mut current = DatePeriod::from_date_as_month(start);
        let end_month = DatePeriod::from_date_as_month(end);
        while current <= end_month {
            result.push(current.clone());
            current = current.succ()?;
        }
        Ok(result)
    }

    /// Generate all daily periods between two dates (inclusive)
    /// Returns an empty vector if start > end
    ///
    /// # Errors
    ///
    /// Returns an error if advancing the daily period via [`DatePeriod::succ`]
    /// fails while iterating from `start` to `end`.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let start = NaiveDate::from_ymd_opt(2024, 2, 1).unwrap();
    /// let end = NaiveDate::from_ymd_opt(2024, 2, 3).unwrap();
    /// let days = DatePeriod::between_date_as_daily(start, end).unwrap();
    /// assert_eq!(days.len(), 3);
    /// assert_eq!(days[0].to_string(), "2024D32");
    /// ```
    pub fn between_date_as_daily(
        start: NaiveDate,
        end: NaiveDate,
    ) -> anyhow::Result<Vec<DatePeriod>> {
        if start > end {
            return Ok(vec![]);
        }
        let mut result = vec![];
        let mut current = DatePeriod::from_date_as_daily(start);
        let end_daily = DatePeriod::from_date_as_daily(end);
        while current <= end_daily {
            result.push(current.clone());
            current = current.succ()?;
        }
        Ok(result)
    }

    /// Get the first day of this period
    ///
    /// Returns the first date of the period. Since `DatePeriod` instances should only
    /// be created through validated constructors, this should always succeed.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying year/month/day combination cannot be
    /// represented as a [`NaiveDate`] (for example, a year that overflows
    /// `i32`).
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// let first_day = period.get_first_day().unwrap();
    /// assert_eq!(first_day, NaiveDate::from_ymd_opt(2024, 2, 1).unwrap());
    /// ```
    pub fn get_first_day(&self) -> anyhow::Result<NaiveDate> {
        match self {
            DatePeriod::Year(year) => NaiveDate::from_ymd_opt(*year as i32, 1, 1)
                .ok_or_else(|| anyhow::anyhow!("Invalid year for date creation: {}", year)),
            DatePeriod::Quarter(year, quarter) => {
                let month = (quarter - 1) * 3 + 1;
                NaiveDate::from_ymd_opt(*year as i32, month, 1).ok_or_else(|| {
                    anyhow::anyhow!("Invalid quarter date: year {}, quarter {}", year, quarter)
                })
            }
            DatePeriod::Month(year, month) => NaiveDate::from_ymd_opt(*year as i32, *month, 1)
                .ok_or_else(|| {
                    anyhow::anyhow!("Invalid month date: year {}, month {}", year, month)
                }),
            DatePeriod::Daily(year, day) => NaiveDate::from_yo_opt(*year as i32, *day)
                .ok_or_else(|| anyhow::anyhow!("Invalid daily date: year {}, day {}", year, day)),
        }
    }

    /// Get the last day of this period
    ///
    /// Returns the last date of the period.
    ///
    /// # Errors
    ///
    /// Returns an error if the period's boundary date cannot be constructed
    /// (e.g. month arithmetic overflow for quarter/month periods).
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// let last_day = period.get_last_day().unwrap();
    /// assert_eq!(last_day, NaiveDate::from_ymd_opt(2024, 2, 29).unwrap()); // 2024 is leap year
    /// ```
    pub fn get_last_day(&self) -> anyhow::Result<NaiveDate> {
        match self {
            DatePeriod::Year(year) => NaiveDate::from_ymd_opt(*year as i32, 12, 31)
                .ok_or_else(|| anyhow::anyhow!("Invalid year for last day calculation: {}", year)),
            DatePeriod::Quarter(_, _) => {
                let first_day = self.get_first_day()?;
                let added_months =
                    first_day
                        .checked_add_months(Months::new(3))
                        .ok_or_else(|| {
                            anyhow::anyhow!("Failed to add 3 months to quarter start date")
                        })?;
                let last_day = added_months.pred_opt().ok_or_else(|| {
                    anyhow::anyhow!("Failed to get predecessor date for quarter end")
                })?;
                Ok(last_day)
            }
            DatePeriod::Month(_, _) => {
                let first_day = self.get_first_day()?;
                let added_months = first_day
                    .checked_add_months(Months::new(1))
                    .ok_or_else(|| anyhow::anyhow!("Failed to add 1 month to month start date"))?;
                let last_day = added_months.pred_opt().ok_or_else(|| {
                    anyhow::anyhow!("Failed to get predecessor date for month end")
                })?;
                Ok(last_day)
            }
            DatePeriod::Daily(_, _) => self.get_first_day(), // Same as first day for daily period
        }
    }

    /// Check if this period contains the given date
    ///
    /// Returns false if there's an error calculating the date boundaries.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    /// use chrono::NaiveDate;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// let date_in_period = NaiveDate::from_ymd_opt(2024, 2, 15).unwrap();
    /// let date_outside_period = NaiveDate::from_ymd_opt(2024, 3, 1).unwrap();
    /// assert!(period.contains_date(date_in_period));
    /// assert!(!period.contains_date(date_outside_period));
    /// ```
    pub fn contains_date(&self, date: NaiveDate) -> bool {
        match (self.get_first_day(), self.get_last_day()) {
            (Ok(first), Ok(last)) => date >= first && date <= last,
            _ => false, // Return false if we can't calculate the boundaries
        }
    }

    /// Get the year component
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// assert_eq!(period.get_year(), 2024);
    /// ```
    pub fn get_year(&self) -> u32 {
        match self {
            DatePeriod::Year(year) => *year,
            DatePeriod::Quarter(year, _) => *year,
            DatePeriod::Month(year, _) => *year,
            DatePeriod::Daily(year, _) => *year,
        }
    }

    /// Get the period value (quarter number, month number, or day number)
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let year_period = DatePeriod::year(2024);
    /// assert_eq!(year_period.value(), 2024);
    ///
    /// let month_period = DatePeriod::month(2024, 2).unwrap();
    /// assert_eq!(month_period.value(), 2);
    /// ```
    pub fn value(&self) -> u32 {
        match self {
            DatePeriod::Year(year) => *year,
            DatePeriod::Quarter(_, quarter) => *quarter,
            DatePeriod::Month(_, month) => *month,
            DatePeriod::Daily(_, day) => *day,
        }
    }

    /// Get the short name of the period type
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let year_period = DatePeriod::year(2024);
    /// assert_eq!(year_period.short_name(), "Y");
    ///
    /// let month_period = DatePeriod::month(2024, 2).unwrap();
    /// assert_eq!(month_period.short_name(), "M");
    /// ```
    pub fn short_name(&self) -> &'static str {
        match self {
            DatePeriod::Year(_) => "Y",
            DatePeriod::Quarter(_, _) => "Q",
            DatePeriod::Month(_, _) => "M",
            DatePeriod::Daily(_, _) => "D",
        }
    }

    /// Get the full name of the period type
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let year_period = DatePeriod::year(2024);
    /// assert_eq!(year_period.period_name(), "YEAR");
    ///
    /// let month_period = DatePeriod::month(2024, 2).unwrap();
    /// assert_eq!(month_period.period_name(), "MONTH");
    /// ```
    pub fn period_name(&self) -> &'static str {
        match self {
            DatePeriod::Year(_) => "YEAR",
            DatePeriod::Quarter(_, _) => "QUARTER",
            DatePeriod::Month(_, _) => "MONTH",
            DatePeriod::Daily(_, _) => "DAILY",
        }
    }

    /// Get the successor (next) period
    ///
    /// # Errors
    ///
    /// This function currently never fails in practice; the `Result` return
    /// type is kept for API symmetry with [`DatePeriod::pred`].
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// let next_period = period.succ().unwrap();
    /// assert_eq!(next_period.to_string(), "2024M3");
    /// ```
    pub fn succ(&self) -> anyhow::Result<DatePeriod> {
        Ok(match self {
            DatePeriod::Year(year) => DatePeriod::Year(year + 1),
            DatePeriod::Quarter(year, quarter) => {
                if *quarter < 4 {
                    DatePeriod::Quarter(*year, quarter + 1)
                } else {
                    DatePeriod::Quarter(year + 1, 1)
                }
            }
            DatePeriod::Month(year, month) => {
                if *month < 12 {
                    DatePeriod::Month(*year, month + 1)
                } else {
                    DatePeriod::Month(year + 1, 1)
                }
            }
            DatePeriod::Daily(year, day) => {
                let max_days = if leap_year(*year as i32) { 366 } else { 365 };
                if *day < max_days {
                    DatePeriod::Daily(*year, day + 1)
                } else {
                    DatePeriod::Daily(year + 1, 1)
                }
            }
        })
    }

    /// Get the predecessor (previous) period
    ///
    /// # Errors
    ///
    /// Returns an error if the period is already at the beginning of the
    /// supported range (year `0`) and has no predecessor.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// let prev_period = period.pred().unwrap();
    /// assert_eq!(prev_period.to_string(), "2024M1");
    /// ```
    pub fn pred(&self) -> anyhow::Result<DatePeriod> {
        Ok(match self {
            DatePeriod::Year(year) => {
                if *year > 0 {
                    DatePeriod::Year(year - 1)
                } else {
                    anyhow::bail!("No predecessor for year 0");
                }
            }
            DatePeriod::Quarter(year, quarter) => {
                if *quarter > 1 {
                    DatePeriod::Quarter(*year, quarter - 1)
                } else if *year > 0 {
                    DatePeriod::Quarter(year - 1, 4)
                } else {
                    anyhow::bail!("No predecessor for quarter 1 of year 0");
                }
            }
            DatePeriod::Month(year, month) => {
                if *month > 1 {
                    DatePeriod::Month(*year, month - 1)
                } else if *year > 0 {
                    DatePeriod::Month(year - 1, 12)
                } else {
                    anyhow::bail!("No predecessor for month 1 of year 0");
                }
            }
            DatePeriod::Daily(year, day) => {
                if *day > 1 {
                    DatePeriod::Daily(*year, day - 1)
                } else if *year > 0 {
                    let prev_year = year - 1;
                    let max_days_prev = if leap_year(prev_year as i32) {
                        366
                    } else {
                        365
                    };
                    DatePeriod::Daily(prev_year, max_days_prev)
                } else {
                    anyhow::bail!("No predecessor for day 1 of year 0");
                }
            }
        })
    }

    /// Decompose this period into its direct sub-periods
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let quarter = DatePeriod::quarter(2024, 1).unwrap();
    /// let months = quarter.decompose();
    /// assert_eq!(months.len(), 3);
    /// assert_eq!(months[0].to_string(), "2024M1");
    /// assert_eq!(months[2].to_string(), "2024M3");
    /// ```
    pub fn decompose(&self) -> Vec<DatePeriod> {
        match self {
            DatePeriod::Year(year) => (1..=4)
                .map(|q| match DatePeriod::quarter(*year, q) {
                    Ok(period) => period,
                    Err(_) => unreachable!("quarter should always succeed for valid q"),
                })
                .collect(),
            DatePeriod::Quarter(year, quarter) => {
                let start_month = (quarter - 1) * 3 + 1;
                (0..3)
                    .map(|i| match DatePeriod::month(*year, start_month + i) {
                        Ok(period) => period,
                        Err(_) => unreachable!("month should always succeed for valid month"),
                    })
                    .collect()
            }
            DatePeriod::Month(year, month) => {
                let first_day = match NaiveDate::from_ymd_opt(*year as i32, *month, 1) {
                    Some(date) => date,
                    None => unreachable!("from_ymd_opt should succeed for valid year and month"),
                };
                let last_day = first_day + Months::new(1) - Duration::days(1);
                (1..=last_day.day())
                    .map(|d| match DatePeriod::daily(*year, d) {
                        Ok(period) => period,
                        Err(_) => unreachable!("daily should always succeed for valid day"),
                    })
                    .collect()
            }
            DatePeriod::Daily(_, _) => vec![],
        }
    }

    /// Aggregate this period to its direct parent period
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let daily = DatePeriod::daily(2024, 32).unwrap();
    /// let month = daily.aggregate();
    /// assert_eq!(month, DatePeriod::month(2024, 2).unwrap());
    ///
    /// let quarter = DatePeriod::quarter(2024, 2).unwrap();
    /// let year = quarter.aggregate();
    /// assert_eq!(year, DatePeriod::year(2024));
    ///
    /// let year_period = DatePeriod::year(2024);
    /// let parent = year_period.aggregate();
    /// assert_eq!(parent, year_period); // Year has no parent, remains the same
    /// ```
    pub fn aggregate(&self) -> DatePeriod {
        match self {
            DatePeriod::Year(_) => self.clone(),
            DatePeriod::Quarter(year, _) => DatePeriod::year(*year),
            DatePeriod::Month(year, month) => {
                let quarter = ((month - 1) / 3) + 1;
                match DatePeriod::quarter(*year, quarter) {
                    Ok(period) => period,
                    Err(_) => unreachable!("quarter should always succeed for valid quarter"),
                }
            }
            DatePeriod::Daily(year, day) => {
                let date = match NaiveDate::from_yo_opt(*year as i32, *day) {
                    Some(d) => d,
                    None => unreachable!("from_yo_opt should succeed for valid year and day"),
                };
                match DatePeriod::month(date.year() as u32, date.month()) {
                    Ok(period) => period,
                    Err(_) => unreachable!("month should always succeed for valid month"),
                }
            }
        }
    }

    /// Get the successor n periods ahead
    ///
    /// Returns the period that is n steps ahead of the current period.
    /// If n is 0, returns the current period.
    ///
    /// # Errors
    ///
    /// This function currently never fails in practice; the `Result` return
    /// type is kept for API symmetry with [`DatePeriod::pred_n`].
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::month(2024, 2).unwrap();
    /// let next_period = period.succ_n(3).unwrap();
    /// assert_eq!(next_period.to_string(), "2024M5");
    /// ```
    pub fn succ_n(&self, n: u32) -> anyhow::Result<DatePeriod> {
        if n == 0 {
            return Ok(self.clone());
        }
        Ok(match self {
            DatePeriod::Year(year) => DatePeriod::Year(year + n),
            DatePeriod::Quarter(year, quarter) => {
                let total_quarters = (*year as u64 * 4) + (*quarter as u64 - 1) + n as u64;
                let new_year = (total_quarters / 4) as u32;
                let new_quarter = ((total_quarters % 4) + 1) as u32;
                DatePeriod::Quarter(new_year, new_quarter)
            }
            DatePeriod::Month(year, month) => {
                let total_months = (*year as u64 * 12) + (*month as u64 - 1) + n as u64;
                let new_year = (total_months / 12) as u32;
                let new_month = ((total_months % 12) + 1) as u32;
                DatePeriod::Month(new_year, new_month)
            }
            DatePeriod::Daily(year, day) => {
                let mut current_year = *year;
                let mut current_day = *day;
                let mut remaining = n;
                while remaining > 0 {
                    let max_days = if leap_year(current_year as i32) {
                        366
                    } else {
                        365
                    };
                    if current_day + remaining <= max_days {
                        current_day += remaining;
                        break;
                    } else {
                        remaining -= max_days - current_day + 1;
                        current_year += 1;
                        current_day = 1;
                    }
                }
                DatePeriod::Daily(current_year, current_day)
            }
        })
    }

    /// Get the predecessor n periods back
    ///
    /// Returns the period that is n steps back from the current period.
    /// If n is 0, returns the current period.
    /// Returns an error if going back would result in an invalid year (less than 0).
    ///
    /// # Errors
    ///
    /// Returns an error if stepping `n` periods back would underflow past year
    /// `0` (i.e. there is no representable period that far in the past).
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::month(2024, 5).unwrap();
    /// let prev_period = period.pred_n(3).unwrap();
    /// assert_eq!(prev_period.to_string(), "2024M2");
    /// ```
    pub fn pred_n(&self, n: u32) -> anyhow::Result<DatePeriod> {
        if n == 0 {
            return Ok(self.clone());
        }
        Ok(match self {
            DatePeriod::Year(year) => {
                if *year >= n {
                    DatePeriod::Year(year - n)
                } else {
                    anyhow::bail!("Cannot go back {} years from year {}", n, year);
                }
            }
            DatePeriod::Quarter(year, quarter) => {
                let total_quarters = (*year as i64 * 4) + (*quarter as i64 - 1) - n as i64;
                if total_quarters < 0 {
                    anyhow::bail!("Cannot go back {} quarters from {}", n, self);
                }
                let new_year = (total_quarters / 4) as u32;
                let new_quarter = ((total_quarters % 4) + 1) as u32;
                DatePeriod::Quarter(new_year, new_quarter)
            }
            DatePeriod::Month(year, month) => {
                let total_months = (*year as i64 * 12) + (*month as i64 - 1) - n as i64;
                if total_months < 0 {
                    anyhow::bail!("Cannot go back {} months from {}", n, self);
                }
                let new_year = (total_months / 12) as u32;
                let new_month = ((total_months % 12) + 1) as u32;
                DatePeriod::Month(new_year, new_month)
            }
            DatePeriod::Daily(year, day) => {
                let mut current_year = *year as i32;
                let mut current_day = *day as i32;
                let mut remaining = n as i32;
                while remaining > 0 {
                    if remaining < current_day {
                        current_day -= remaining;
                        remaining = 0;
                    } else {
                        remaining -= current_day;
                        current_year -= 1;
                        if current_year < 0 {
                            anyhow::bail!("Cannot go back {} days from {}", n, self);
                        }
                        current_day = if leap_year(current_year) { 366 } else { 365 };
                    }
                }
                DatePeriod::Daily(current_year as u32, current_day as u32)
            }
        })
    }

    /// Offset this period by n steps
    ///
    /// Positive n advances forward, negative n goes backward.
    /// If n is 0, returns the current period.
    ///
    /// # Errors
    ///
    /// Returns an error from the underlying [`DatePeriod::succ_n`] /
    /// [`DatePeriod::pred_n`] call — most notably when a negative offset would
    /// underflow past year `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use range_date::range_type::DatePeriod;
    ///
    /// let period = DatePeriod::month(2024, 5).unwrap();
    /// let next_period = period.offset_n(3).unwrap();
    /// assert_eq!(next_period.to_string(), "2024M8");
    ///
    /// let prev_period = period.offset_n(-3).unwrap();
    /// assert_eq!(prev_period.to_string(), "2024M2");
    /// ```
    pub fn offset_n(&self, n: i32) -> anyhow::Result<DatePeriod> {
        match n.cmp(&0) {
            std::cmp::Ordering::Equal => Ok(self.clone()),
            std::cmp::Ordering::Greater => self.succ_n(n as u32),
            std::cmp::Ordering::Less => self.pred_n((-n) as u32),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;
    use chrono::NaiveDate;
    use serde_json;

    #[test]
    fn test_constructors() {
        // Test year constructor
        let year_period = DatePeriod::year(2024);
        assert_eq!(year_period, DatePeriod::Year(2024));

        // Test quarter constructor with validation
        let quarter_period = DatePeriod::quarter(2024, 2).unwrap();
        assert_eq!(quarter_period, DatePeriod::Quarter(2024, 2));

        // Test invalid quarter
        assert!(DatePeriod::quarter(2024, 5).is_err());
        assert!(DatePeriod::quarter(2024, 0).is_err());

        // Test month constructor with validation
        let month_period = DatePeriod::month(2024, 5).unwrap();
        assert_eq!(month_period, DatePeriod::Month(2024, 5));

        // Test invalid month
        assert!(DatePeriod::month(2024, 13).is_err());
        assert!(DatePeriod::month(2024, 0).is_err());

        // Test daily constructor with validation
        let daily_period = DatePeriod::daily(2024, 136).unwrap();
        assert_eq!(daily_period, DatePeriod::Daily(2024, 136));

        // Test invalid day
        assert!(DatePeriod::daily(2024, 367).is_err()); // Even leap year max is 366
        assert!(DatePeriod::daily(2023, 366).is_err()); // Non-leap year max is 365
        assert!(DatePeriod::daily(2024, 0).is_err());
    }

    #[test]
    fn test_parse_from_string() {
        // Test valid parsing
        assert_eq!(DatePeriod::parse("2024Y").unwrap(), DatePeriod::Year(2024));
        assert_eq!(
            DatePeriod::parse("2024Q2").unwrap(),
            DatePeriod::Quarter(2024, 2)
        );
        assert_eq!(
            DatePeriod::parse("2024M5").unwrap(),
            DatePeriod::Month(2024, 5)
        );
        assert_eq!(
            DatePeriod::parse("2024D136").unwrap(),
            DatePeriod::Daily(2024, 136)
        );

        // Test invalid parsing
        assert!(DatePeriod::parse("invalid").is_err());
        assert!(DatePeriod::parse("202").is_err()); // Too short
        assert!(DatePeriod::parse("2024X1").is_err()); // Invalid period type
        assert!(DatePeriod::parse("2024Q5").is_err()); // Invalid quarter
        assert!(DatePeriod::parse("2024M13").is_err()); // Invalid month
    }

    #[test]
    fn test_from_str_trait() {
        assert_eq!(
            DatePeriod::from_str("2024Y").unwrap(),
            DatePeriod::Year(2024)
        );
        assert_eq!(
            DatePeriod::from_str("2024Q2").unwrap(),
            DatePeriod::Quarter(2024, 2)
        );
        assert_eq!(
            DatePeriod::from_str("2024M5").unwrap(),
            DatePeriod::Month(2024, 5)
        );
        assert_eq!(
            DatePeriod::from_str("2024D136").unwrap(),
            DatePeriod::Daily(2024, 136)
        );
        assert!(DatePeriod::from_str("INVALID").is_err());
    }

    #[test]
    fn test_from_naive_date() {
        let date = NaiveDate::from_ymd_opt(2024, 5, 15).unwrap();

        // Test conversion to different period types
        assert_eq!(DatePeriod::from_date_as_year(date), DatePeriod::Year(2024));
        assert_eq!(
            DatePeriod::from_date_as_quarter(date),
            DatePeriod::Quarter(2024, 2)
        );
        assert_eq!(
            DatePeriod::from_date_as_month(date),
            DatePeriod::Month(2024, 5)
        );
        assert_eq!(
            DatePeriod::from_date_as_daily(date),
            DatePeriod::Daily(2024, 136)
        ); // May 15 is 136th day
    }

    #[test]
    fn test_get_first_and_last_day() -> anyhow::Result<()> {
        // Test year
        let year_period = DatePeriod::year(2024);
        assert_eq!(
            year_period.get_first_day()?,
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap()
        );
        assert_eq!(
            year_period.get_last_day()?,
            NaiveDate::from_ymd_opt(2024, 12, 31).unwrap()
        );

        // Test quarter
        let quarter_period = DatePeriod::quarter(2024, 2).unwrap(); // Q2 = Apr-Jun
        assert_eq!(
            quarter_period.get_first_day()?,
            NaiveDate::from_ymd_opt(2024, 4, 1).unwrap()
        );
        assert_eq!(
            quarter_period.get_last_day()?,
            NaiveDate::from_ymd_opt(2024, 6, 30).unwrap()
        );

        // Test month
        let month_period = DatePeriod::month(2024, 5).unwrap(); // May
        assert_eq!(
            month_period.get_first_day()?,
            NaiveDate::from_ymd_opt(2024, 5, 1).unwrap()
        );
        assert_eq!(
            month_period.get_last_day()?,
            NaiveDate::from_ymd_opt(2024, 5, 31).unwrap()
        );

        // Test daily
        let daily_period = DatePeriod::daily(2024, 136).unwrap(); // May 15
        let expected_date = NaiveDate::from_yo_opt(2024, 136).unwrap();
        assert_eq!(daily_period.get_first_day()?, expected_date);
        assert_eq!(daily_period.get_last_day()?, expected_date);

        Ok(())
    }

    #[test]
    fn test_contains_date() {
        let quarter_period = DatePeriod::quarter(2024, 2).unwrap(); // Q2 2024

        // Should contain dates in Q2
        assert!(quarter_period.contains_date(NaiveDate::from_ymd_opt(2024, 4, 1).unwrap()));
        assert!(quarter_period.contains_date(NaiveDate::from_ymd_opt(2024, 5, 15).unwrap()));
        assert!(quarter_period.contains_date(NaiveDate::from_ymd_opt(2024, 6, 30).unwrap()));

        // Should not contain dates outside Q2
        assert!(!quarter_period.contains_date(NaiveDate::from_ymd_opt(2024, 3, 31).unwrap()));
        assert!(!quarter_period.contains_date(NaiveDate::from_ymd_opt(2024, 7, 1).unwrap()));
    }

    #[test]
    fn test_getters() {
        let quarter_period = DatePeriod::quarter(2024, 2).unwrap();
        assert_eq!(quarter_period.get_year(), 2024);
        assert_eq!(quarter_period.value(), 2);
        assert_eq!(quarter_period.short_name(), "Q");
        assert_eq!(quarter_period.period_name(), "QUARTER");

        let month_period = DatePeriod::month(2024, 5).unwrap();
        assert_eq!(month_period.get_year(), 2024);
        assert_eq!(month_period.value(), 5);
        assert_eq!(month_period.short_name(), "M");
        assert_eq!(month_period.period_name(), "MONTH");
    }

    #[test]
    fn test_to_string() {
        assert_eq!(DatePeriod::year(2024).to_string(), "2024Y");
        assert_eq!(DatePeriod::quarter(2024, 2).unwrap().to_string(), "2024Q2");
        assert_eq!(DatePeriod::month(2024, 5).unwrap().to_string(), "2024M5");
        assert_eq!(
            DatePeriod::daily(2024, 136).unwrap().to_string(),
            "2024D136"
        );
    }

    #[test]
    fn test_display_trait() {
        let quarter_period = DatePeriod::quarter(2024, 2).unwrap();
        assert_eq!(format!("{}", quarter_period), "2024Q2");
    }

    #[test]
    fn test_serialization() {
        let month_period = DatePeriod::month(2024, 5).unwrap();
        let serialized = serde_json::to_string(&month_period).unwrap();
        assert_eq!(serialized, "\"2024M5\"");

        let deserialized: DatePeriod = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, DatePeriod::Month(2024, 5));
    }

    #[test]
    fn test_leap_year_validation() {
        // Leap year - 366 days allowed
        assert!(DatePeriod::daily(2024, 366).is_ok());

        // Non-leap year - only 365 days allowed
        assert!(DatePeriod::daily(2023, 365).is_ok());
        assert!(DatePeriod::daily(2023, 366).is_err());
    }

    #[test]
    fn test_succ() {
        // Test year
        assert_eq!(
            DatePeriod::year(2024).succ().unwrap(),
            DatePeriod::Year(2025)
        );

        // Test quarter
        assert_eq!(
            DatePeriod::quarter(2024, 2).unwrap().succ().unwrap(),
            DatePeriod::Quarter(2024, 3)
        );
        assert_eq!(
            DatePeriod::quarter(2024, 4).unwrap().succ().unwrap(),
            DatePeriod::Quarter(2025, 1)
        );

        // Test month
        assert_eq!(
            DatePeriod::month(2024, 5).unwrap().succ().unwrap(),
            DatePeriod::Month(2024, 6)
        );
        assert_eq!(
            DatePeriod::month(2024, 12).unwrap().succ().unwrap(),
            DatePeriod::Month(2025, 1)
        );

        // Test daily
        assert_eq!(
            DatePeriod::daily(2024, 135).unwrap().succ().unwrap(),
            DatePeriod::Daily(2024, 136)
        );
        assert_eq!(
            DatePeriod::daily(2024, 366).unwrap().succ().unwrap(),
            DatePeriod::Daily(2025, 1)
        ); // Leap year
        assert_eq!(
            DatePeriod::daily(2023, 365).unwrap().succ().unwrap(),
            DatePeriod::Daily(2024, 1)
        ); // Non-leap
    }

    #[test]
    fn test_pred() {
        // Test year
        assert_eq!(
            DatePeriod::year(2024).pred().unwrap(),
            DatePeriod::Year(2023)
        );
        assert!(DatePeriod::year(0).pred().is_err());

        // Test quarter
        assert_eq!(
            DatePeriod::quarter(2024, 2).unwrap().pred().unwrap(),
            DatePeriod::Quarter(2024, 1)
        );
        assert_eq!(
            DatePeriod::quarter(2024, 1).unwrap().pred().unwrap(),
            DatePeriod::Quarter(2023, 4)
        );
        assert!(DatePeriod::quarter(0, 1).unwrap().pred().is_err());

        // Test month
        assert_eq!(
            DatePeriod::month(2024, 5).unwrap().pred().unwrap(),
            DatePeriod::Month(2024, 4)
        );
        assert_eq!(
            DatePeriod::month(2024, 1).unwrap().pred().unwrap(),
            DatePeriod::Month(2023, 12)
        );
        assert!(DatePeriod::month(0, 1).unwrap().pred().is_err());

        // Test daily
        assert_eq!(
            DatePeriod::daily(2024, 135).unwrap().pred().unwrap(),
            DatePeriod::Daily(2024, 134)
        );
        assert_eq!(
            DatePeriod::daily(2024, 1).unwrap().pred().unwrap(),
            DatePeriod::Daily(2023, 365)
        ); // From leap to non-leap
        assert!(DatePeriod::daily(0, 1).unwrap().pred().is_err());
    }

    #[test]
    fn test_decompose() {
        // Test year
        let year_decomposed = DatePeriod::year(2025).decompose();
        assert_eq!(year_decomposed.len(), 4);
        assert_eq!(year_decomposed[0], DatePeriod::Quarter(2025, 1));
        assert_eq!(year_decomposed[3], DatePeriod::Quarter(2025, 4));

        // Test quarter
        let quarter_decomposed = DatePeriod::quarter(2025, 4).unwrap().decompose();
        assert_eq!(quarter_decomposed.len(), 3);
        assert_eq!(quarter_decomposed[0], DatePeriod::Month(2025, 10));
        assert_eq!(quarter_decomposed[2], DatePeriod::Month(2025, 12));

        // Test month (non-leap)
        let month_decomposed = DatePeriod::month(2023, 2).unwrap().decompose();
        assert_eq!(month_decomposed.len(), 28);
        assert_eq!(month_decomposed[0], DatePeriod::Daily(2023, 1));
        assert_eq!(month_decomposed[27], DatePeriod::Daily(2023, 28));

        // Test month (leap)
        let leap_month_decomposed = DatePeriod::month(2024, 2).unwrap().decompose();
        assert_eq!(leap_month_decomposed.len(), 29);
        assert_eq!(leap_month_decomposed[28], DatePeriod::Daily(2024, 29));

        // Test daily
        let daily_decomposed = DatePeriod::daily(2024, 1).unwrap().decompose();
        assert_eq!(daily_decomposed.len(), 0);
    }

    #[test]
    fn test_aggregate() {
        // Test daily
        assert_eq!(
            DatePeriod::daily(2024, 32).unwrap().aggregate(),
            DatePeriod::Month(2024, 2)
        );

        // Test month
        assert_eq!(
            DatePeriod::month(2025, 10).unwrap().aggregate(),
            DatePeriod::Quarter(2025, 4)
        );

        // Test quarter
        assert_eq!(
            DatePeriod::quarter(2025, 4).unwrap().aggregate(),
            DatePeriod::Year(2025)
        );

        // Test year
        assert_eq!(DatePeriod::year(2025).aggregate(), DatePeriod::Year(2025));
    }

    #[test]
    fn test_between_date_as_year() {
        let start = NaiveDate::from_ymd_opt(2023, 6, 15).unwrap();
        let end = NaiveDate::from_ymd_opt(2025, 3, 10).unwrap();

        let result = DatePeriod::between_date_as_year(start, end).unwrap();
        assert_eq!(
            result,
            vec![
                DatePeriod::Year(2023),
                DatePeriod::Year(2024),
                DatePeriod::Year(2025)
            ]
        );

        // Same year
        let same = DatePeriod::between_date_as_year(start, start).unwrap();
        assert_eq!(same, vec![DatePeriod::Year(2023)]);

        // Start > end
        let result_empty = DatePeriod::between_date_as_year(end, start).unwrap();
        assert_eq!(result_empty, vec![]);
    }

    #[test]
    fn test_between_date_as_quarter() {
        let start = NaiveDate::from_ymd_opt(2024, 4, 1).unwrap(); // Q2 2024
        let end = NaiveDate::from_ymd_opt(2024, 9, 30).unwrap(); // Q3 2024

        let result = DatePeriod::between_date_as_quarter(start, end).unwrap();
        assert_eq!(
            result,
            vec![DatePeriod::Quarter(2024, 2), DatePeriod::Quarter(2024, 3)]
        );

        // Cross year
        let start_cross = NaiveDate::from_ymd_opt(2024, 10, 1).unwrap(); // Q4 2024
        let end_cross = NaiveDate::from_ymd_opt(2025, 3, 31).unwrap(); // Q1 2025
        let result_cross = DatePeriod::between_date_as_quarter(start_cross, end_cross).unwrap();
        assert_eq!(
            result_cross,
            vec![DatePeriod::Quarter(2024, 4), DatePeriod::Quarter(2025, 1)]
        );

        // Start > end
        let result_empty = DatePeriod::between_date_as_quarter(end, start).unwrap();
        assert_eq!(result_empty, vec![]);
    }

    #[test]
    fn test_between_date_as_month() {
        let start = NaiveDate::from_ymd_opt(2024, 2, 1).unwrap();
        let end = NaiveDate::from_ymd_opt(2024, 4, 30).unwrap();

        let result = DatePeriod::between_date_as_month(start, end).unwrap();
        assert_eq!(
            result,
            vec![
                DatePeriod::Month(2024, 2),
                DatePeriod::Month(2024, 3),
                DatePeriod::Month(2024, 4)
            ]
        );

        // Cross year
        let start_cross = NaiveDate::from_ymd_opt(2024, 11, 1).unwrap();
        let end_cross = NaiveDate::from_ymd_opt(2025, 1, 31).unwrap();
        let result_cross = DatePeriod::between_date_as_month(start_cross, end_cross).unwrap();
        assert_eq!(
            result_cross,
            vec![
                DatePeriod::Month(2024, 11),
                DatePeriod::Month(2024, 12),
                DatePeriod::Month(2025, 1)
            ]
        );

        // Start > end
        let result_empty = DatePeriod::between_date_as_month(end, start).unwrap();
        assert_eq!(result_empty, vec![]);
    }

    #[test]
    fn test_between_date_as_daily() {
        let start = NaiveDate::from_ymd_opt(2024, 2, 28).unwrap();
        let end = NaiveDate::from_ymd_opt(2024, 3, 2).unwrap();

        let result = DatePeriod::between_date_as_daily(start, end).unwrap();
        assert_eq!(
            result,
            vec![
                DatePeriod::Daily(2024, 59), // Feb 28
                DatePeriod::Daily(2024, 60), // Feb 29 (leap)
                DatePeriod::Daily(2024, 61), // Mar 1
                DatePeriod::Daily(2024, 62)  // Mar 2
            ]
        );

        // Same day
        let same = DatePeriod::between_date_as_daily(start, start).unwrap();
        assert_eq!(same, vec![DatePeriod::Daily(2024, 59)]);

        // Start > end
        let result_empty = DatePeriod::between_date_as_daily(end, start).unwrap();
        assert_eq!(result_empty, vec![]);
    }

    #[test]
    fn test_succ_n_and_pred_n() {
        // Test succ_n with n=0
        let period = DatePeriod::month(2024, 5).unwrap();
        assert_eq!(period.succ_n(0).unwrap(), period);

        // Test pred_n with n=0
        assert_eq!(period.pred_n(0).unwrap(), period);

        // Test succ_n for Year
        let year_period = DatePeriod::year(2024);
        assert_eq!(year_period.succ_n(1).unwrap(), DatePeriod::Year(2025));
        assert_eq!(year_period.succ_n(5).unwrap(), DatePeriod::Year(2029));

        // Test pred_n for Year
        assert_eq!(year_period.pred_n(1).unwrap(), DatePeriod::Year(2023));
        assert_eq!(year_period.pred_n(5).unwrap(), DatePeriod::Year(2019));
        assert!(DatePeriod::year(2).pred_n(5).is_err()); // Cannot go back beyond 0

        // Test succ_n for Quarter
        let quarter_period = DatePeriod::quarter(2024, 2).unwrap();
        assert_eq!(
            quarter_period.succ_n(1).unwrap(),
            DatePeriod::Quarter(2024, 3)
        );
        assert_eq!(
            quarter_period.succ_n(3).unwrap(),
            DatePeriod::Quarter(2025, 1)
        ); // Cross year
        assert_eq!(
            quarter_period.succ_n(10).unwrap(),
            DatePeriod::Quarter(2026, 4)
        );

        // Test pred_n for Quarter
        assert_eq!(
            quarter_period.pred_n(1).unwrap(),
            DatePeriod::Quarter(2024, 1)
        );
        assert_eq!(
            quarter_period.pred_n(2).unwrap(),
            DatePeriod::Quarter(2023, 4)
        ); // Cross year
        assert!(DatePeriod::quarter(0, 1).unwrap().pred_n(1).is_err()); // Year 0

        // Test succ_n for Month
        let month_period = DatePeriod::month(2024, 5).unwrap();
        assert_eq!(month_period.succ_n(1).unwrap(), DatePeriod::Month(2024, 6));
        assert_eq!(month_period.succ_n(8).unwrap(), DatePeriod::Month(2025, 1)); // Cross year
        assert_eq!(month_period.succ_n(20).unwrap(), DatePeriod::Month(2026, 1));

        // Test pred_n for Month
        assert_eq!(month_period.pred_n(1).unwrap(), DatePeriod::Month(2024, 4));
        assert_eq!(month_period.pred_n(5).unwrap(), DatePeriod::Month(2023, 12)); // Cross year
        assert!(DatePeriod::month(0, 1).unwrap().pred_n(1).is_err()); // Year 0

        // Test succ_n for Daily
        let daily_period = DatePeriod::daily(2024, 365).unwrap(); // Leap year
        assert_eq!(
            daily_period.succ_n(1).unwrap(),
            DatePeriod::Daily(2024, 366)
        );
        assert_eq!(daily_period.succ_n(2).unwrap(), DatePeriod::Daily(2025, 1)); // Cross year

        let non_leap_daily = DatePeriod::daily(2023, 365).unwrap();
        assert_eq!(
            non_leap_daily.succ_n(1).unwrap(),
            DatePeriod::Daily(2024, 1)
        );

        // Test pred_n for Daily
        let daily_period_2 = DatePeriod::daily(2024, 2).unwrap();
        assert_eq!(
            daily_period_2.pred_n(1).unwrap(),
            DatePeriod::Daily(2024, 1)
        );
        assert_eq!(
            daily_period_2.pred_n(2).unwrap(),
            DatePeriod::Daily(2023, 365)
        ); // Cross to non-leap
        assert!(DatePeriod::daily(0, 1).unwrap().pred_n(1).is_err()); // Year 0

        // Test consistency with succ/pred
        let test_period = DatePeriod::month(2024, 5).unwrap();
        assert_eq!(test_period.succ_n(1).unwrap(), test_period.succ().unwrap());
        assert_eq!(test_period.pred_n(1).unwrap(), test_period.pred().unwrap());

        // Test offset_n
        // Test n=0
        assert_eq!(test_period.offset_n(0).unwrap(), test_period);

        // Test positive offset (forward)
        assert_eq!(
            test_period.offset_n(1).unwrap(),
            test_period.succ_n(1).unwrap()
        );
        assert_eq!(test_period.offset_n(3).unwrap(), DatePeriod::Month(2024, 8));

        // Test negative offset (backward)
        assert_eq!(
            test_period.offset_n(-1).unwrap(),
            test_period.pred_n(1).unwrap()
        );
        assert_eq!(
            test_period.offset_n(-3).unwrap(),
            DatePeriod::Month(2024, 2)
        );

        // Test error cases
        assert!(DatePeriod::year(1).offset_n(-2).is_err()); // Year 0 error

        // Test consistency with succ_n and pred_n
        assert_eq!(
            test_period.offset_n(5).unwrap(),
            test_period.succ_n(5).unwrap()
        );
        assert_eq!(
            test_period.offset_n(-5).unwrap(),
            test_period.pred_n(5).unwrap()
        );
    }
}