paft-domain 0.9.0

Domain modeling primitives (instrument, exchange, period, market state) for the paft ecosystem.
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
//! Financial period primitives.
//!
//! Provides separate reporting/fiscal period labels and calendar period buckets.

use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{Error as DeError, Visitor},
};
use std::borrow::Cow;
use std::fmt;

use crate::error::DomainError;
use chrono::{Datelike, NaiveDate};
use paft_utils::Canonical;

/// Valid year component for structured financial periods.
///
/// `ReportingPeriod` accepts calendar-style four-digit years in `0..=9999`. The lower
/// bound preserves the crate's existing parser behavior for tokens like
/// `0000`; the upper bound keeps structured period display/serde canonical as
/// exactly four year digits.
///
/// Standalone serde emits the same four-digit canonical string as
/// [`std::fmt::Display`].
/// Deserialization also accepts integer years for compatibility and normalizes
/// them on the next serialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PeriodYear(u16);

impl PeriodYear {
    /// Smallest valid structured period year.
    pub const MIN: u16 = 0;

    /// Largest valid structured period year.
    pub const MAX: u16 = 9999;

    /// Builds a validated period year.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] when `year` is outside
    /// `0..=9999`.
    pub fn new(year: i32) -> Result<Self, DomainError> {
        let Ok(year_u16) = u16::try_from(year) else {
            return Err(DomainError::InvalidPeriodYear { year });
        };

        if year_u16 <= Self::MAX {
            Ok(Self(year_u16))
        } else {
            Err(DomainError::InvalidPeriodYear { year })
        }
    }

    /// Returns the year as an `i32`, matching [`chrono::Datelike::year`].
    #[must_use]
    pub const fn get(self) -> i32 {
        self.0 as i32
    }

    /// Returns the year as the compact unsigned storage type.
    #[must_use]
    pub const fn as_u16(self) -> u16 {
        self.0
    }
}

impl TryFrom<i32> for PeriodYear {
    type Error = DomainError;

    fn try_from(year: i32) -> Result<Self, Self::Error> {
        Self::new(year)
    }
}

impl TryFrom<u16> for PeriodYear {
    type Error = DomainError;

    fn try_from(year: u16) -> Result<Self, Self::Error> {
        Self::new(i32::from(year))
    }
}

impl From<PeriodYear> for i32 {
    fn from(year: PeriodYear) -> Self {
        year.get()
    }
}

impl From<PeriodYear> for u16 {
    fn from(year: PeriodYear) -> Self {
        year.as_u16()
    }
}

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

impl Serialize for PeriodYear {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for PeriodYear {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(PeriodYearVisitor)
    }
}

struct PeriodYearVisitor;

impl Visitor<'_> for PeriodYearVisitor {
    type Value = PeriodYear;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a canonical four-digit period year string or integer in 0..=9999")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        parse_period_year_code(value).map_err(DeError::custom)
    }

    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        period_year_from_i64(value).map_err(DeError::custom)
    }

    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        period_year_from_u64(value).map_err(DeError::custom)
    }
}

fn parse_period_year_code(value: &str) -> Result<PeriodYear, DomainError> {
    let bytes = value.as_bytes();
    if bytes.len() != 4 || !bytes.iter().all(u8::is_ascii_digit) {
        return Err(DomainError::InvalidPeriodFormat {
            format: value.to_string(),
        });
    }

    let year = i32::from(bytes[0] - b'0') * 1_000
        + i32::from(bytes[1] - b'0') * 100
        + i32::from(bytes[2] - b'0') * 10
        + i32::from(bytes[3] - b'0');

    PeriodYear::new(year)
}

fn period_year_from_i64(value: i64) -> Result<PeriodYear, DomainError> {
    let Ok(year) = i32::try_from(value) else {
        return Err(DomainError::InvalidPeriodFormat {
            format: value.to_string(),
        });
    };

    PeriodYear::new(year)
}

fn period_year_from_u64(value: u64) -> Result<PeriodYear, DomainError> {
    let Ok(year) = i32::try_from(value) else {
        return Err(DomainError::InvalidPeriodFormat {
            format: value.to_string(),
        });
    };

    PeriodYear::new(year)
}

fn parse_period_date_code(value: &str) -> Result<PeriodDate, DomainError> {
    let invalid = || DomainError::InvalidPeriodFormat {
        format: value.to_string(),
    };

    let bytes = value.as_bytes();
    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
        return Err(invalid());
    }

    let Some(year) = read_4_digits(bytes, 0) else {
        return Err(invalid());
    };

    if !bytes[5..7].iter().all(u8::is_ascii_digit) || !bytes[8..10].iter().all(u8::is_ascii_digit) {
        return Err(invalid());
    }

    let month = u32::from(bytes[5] - b'0') * 10 + u32::from(bytes[6] - b'0');
    let day = u32::from(bytes[8] - b'0') * 10 + u32::from(bytes[9] - b'0');
    let date = NaiveDate::from_ymd_opt(year, month, day).ok_or_else(invalid)?;
    PeriodDate::new(date)
}

fn parse_quarter_of_year_code(value: &str) -> Result<QuarterOfYear, DomainError> {
    let bytes = value.as_bytes();
    if bytes.len() != 1 || !bytes[0].is_ascii_digit() {
        return Err(DomainError::InvalidPeriodFormat {
            format: value.to_string(),
        });
    }

    QuarterOfYear::new(bytes[0] - b'0')
}

fn quarter_of_year_from_i64(value: i64) -> Result<QuarterOfYear, DomainError> {
    let Ok(quarter) = u8::try_from(value) else {
        return Err(DomainError::InvalidPeriodFormat {
            format: value.to_string(),
        });
    };

    QuarterOfYear::new(quarter)
}

fn quarter_of_year_from_u64(value: u64) -> Result<QuarterOfYear, DomainError> {
    let Ok(quarter) = u8::try_from(value) else {
        return Err(DomainError::InvalidPeriodFormat {
            format: value.to_string(),
        });
    };

    QuarterOfYear::new(quarter)
}

/// Valid date component for structured financial periods.
///
/// The wrapped [`NaiveDate`] always has a year in `0..=9999`, matching
/// [`PeriodYear`] and the four-digit canonical `YYYY-MM-DD` period format.
///
/// Standalone serde emits the same canonical `YYYY-MM-DD` string as
/// [`std::fmt::Display`] and deserializes that canonical form.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PeriodDate(NaiveDate);

impl PeriodDate {
    /// Builds a validated period date.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] when the date's year is
    /// outside `0..=9999`.
    pub fn new(date: NaiveDate) -> Result<Self, DomainError> {
        PeriodYear::new(date.year())?;
        Ok(Self(date))
    }

    /// Returns the wrapped date.
    #[must_use]
    pub const fn get(self) -> NaiveDate {
        self.0
    }
}

impl TryFrom<NaiveDate> for PeriodDate {
    type Error = DomainError;

    fn try_from(date: NaiveDate) -> Result<Self, Self::Error> {
        Self::new(date)
    }
}

impl From<PeriodDate> for NaiveDate {
    fn from(date: PeriodDate) -> Self {
        date.get()
    }
}

impl fmt::Display for PeriodDate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.format("%Y-%m-%d"))
    }
}

impl Serialize for PeriodDate {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for PeriodDate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        parse_period_date_code(&raw).map_err(DeError::custom)
    }
}

/// Valid quarter-of-year component for structured financial periods.
///
/// Standalone serde emits the same canonical string as [`std::fmt::Display`].
/// Deserialization also accepts integer quarters for compatibility and
/// normalizes them on the next serialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct QuarterOfYear(u8);

impl QuarterOfYear {
    /// First quarter.
    pub const Q1: Self = Self(1);

    /// Second quarter.
    pub const Q2: Self = Self(2);

    /// Third quarter.
    pub const Q3: Self = Self(3);

    /// Fourth quarter.
    pub const Q4: Self = Self(4);

    /// Smallest valid quarter number.
    pub const MIN: u8 = 1;

    /// Largest valid quarter number.
    pub const MAX: u8 = 4;

    /// Builds a validated quarter-of-year.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodQuarter`] when `quarter` is outside
    /// `1..=4`.
    pub const fn new(quarter: u8) -> Result<Self, DomainError> {
        if quarter >= Self::MIN && quarter <= Self::MAX {
            Ok(Self(quarter))
        } else {
            Err(DomainError::InvalidPeriodQuarter { quarter })
        }
    }

    /// Returns the quarter number.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

impl TryFrom<u8> for QuarterOfYear {
    type Error = DomainError;

    fn try_from(quarter: u8) -> Result<Self, Self::Error> {
        Self::new(quarter)
    }
}

impl From<QuarterOfYear> for u8 {
    fn from(quarter: QuarterOfYear) -> Self {
        quarter.get()
    }
}

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

impl Serialize for QuarterOfYear {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for QuarterOfYear {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(QuarterOfYearVisitor)
    }
}

struct QuarterOfYearVisitor;

impl Visitor<'_> for QuarterOfYearVisitor {
    type Value = QuarterOfYear;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a canonical quarter string or integer in 1..=4")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        parse_quarter_of_year_code(value).map_err(DeError::custom)
    }

    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        quarter_of_year_from_i64(value).map_err(DeError::custom)
    }

    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        quarter_of_year_from_u64(value).map_err(DeError::custom)
    }
}

paft_core::other_string_code_type!(
    /// Provider-specific period token that is not modeled by [`ReportingPeriod`].
    pub struct OtherPeriod for ReportingPeriod;
    type Error = DomainError;
    parse(input) => input.parse::<ReportingPeriod>();
    invalid(input) => DomainError::InvalidPeriodFormat {
        format: input.to_string(),
    };
);

/// Reporting or fiscal period label with structured variants and extensible fallback.
///
/// `ReportingPeriod` models labels reported by issuers, analysts, or providers:
/// `2023Q4`, `FY2023`, `2023-12-31`, and provider-specific ranges are labels,
/// not calendar boundary claims. A fiscal `2023Q4` may not overlap calendar Q4.
/// Use [`CalendarPeriod`] when you need date boundary helpers.
///
/// Canonical/serde rules:
/// - Emission uses a single canonical form per variant (UPPERCASE ASCII where applicable)
/// - Parser accepts a superset of tokens (aliases, case-insensitive where appropriate)
/// - `Other(s)` serializes to its canonical `code()` string (no escape prefix)
/// - `Display` output matches the canonical form for structured variants and the raw `s` for `Other(s)`
/// - Serde round-trips preserve identity for canonical variants; unknown tokens normalize to `Other(UPPERCASE)`
///
/// Canonical outputs:
/// - Quarters: `YYYYQ#` (e.g., `2023Q4`)
/// - Years: `YYYY` (e.g., `2023`)
/// - Dates: `YYYY-MM-DD` (ISO 8601)
/// - `Other` stores and emits `canonicalize`-style tokens
///
/// `Display` and serde always emit the canonical forms listed above. The parser
/// accepts common provider variants (e.g., `FY2023`, `2023-Q4`, `12/31/2023`) and
/// normalizes to the single canonical emission for round-trip stability.
///
/// `ReportingPeriod` intentionally does not implement `Ord` or date-boundary
/// helpers: cross-granularity ordering needs caller-chosen semantics (fiscal
/// calendar, exact date, provider-specific `Other`, etc.).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReportingPeriod {
    /// Quarterly period with year and quarter number
    Quarter {
        /// The year of the quarter
        year: PeriodYear,
        /// The quarter number (1-4)
        quarter: QuarterOfYear,
    },
    /// Annual period with year
    Year {
        /// The year of the annual period
        year: PeriodYear,
    },
    /// Specific date
    Date(
        /// Validated calendar date
        PeriodDate,
    ),
    /// Unknown or provider-specific period format
    Other(OtherPeriod),
}

impl ReportingPeriod {
    /// Builds a validated quarterly period.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] or
    /// [`DomainError::InvalidPeriodQuarter`] when either component is outside
    /// its accepted range.
    pub fn quarterly(year: i32, quarter: u8) -> Result<Self, DomainError> {
        Ok(Self::Quarter {
            year: PeriodYear::new(year)?,
            quarter: QuarterOfYear::new(quarter)?,
        })
    }

    /// Builds a validated annual period.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] when `year` is outside
    /// `0..=9999`.
    pub fn annual(year: i32) -> Result<Self, DomainError> {
        Ok(Self::Year {
            year: PeriodYear::new(year)?,
        })
    }

    /// Builds a validated date period.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] when `date.year()` is
    /// outside `0..=9999`.
    pub fn date(date: NaiveDate) -> Result<Self, DomainError> {
        Ok(Self::Date(PeriodDate::new(date)?))
    }

    /// Builds an unknown period token, rejecting tokens modeled by [`ReportingPeriod`].
    ///
    /// # Errors
    ///
    /// Returns an error if `input` is empty, cannot be canonicalized, parses to
    /// a modeled [`ReportingPeriod`] variant, or matches a supported structured
    /// period shape with invalid components.
    ///
    /// Partial modeled-looking provider labels that do not match a supported
    /// structured parser, such as `FY`, may still be accepted as
    /// [`ReportingPeriod::Other`].
    pub fn other(input: &str) -> Result<Self, DomainError> {
        OtherPeriod::new(input).map(Self::Other)
    }

    /// Returns the canonical display/serde code for this period.
    #[must_use]
    pub fn code(&self) -> Cow<'_, str> {
        match self {
            Self::Quarter { year, quarter } => Cow::Owned(format!("{year}Q{quarter}")),
            Self::Year { year } => Cow::Owned(year.to_string()),
            Self::Date(date) => Cow::Owned(date.to_string()),
            Self::Other(s) => Cow::Borrowed(s.as_ref()),
        }
    }
    /// Returns the year for this period, if applicable
    #[must_use]
    pub const fn year(&self) -> Option<i32> {
        match self {
            Self::Quarter { year, .. } | Self::Year { year } => Some(year.get()),
            _ => None,
        }
    }

    /// Returns the validated year component for this period, if applicable.
    #[must_use]
    pub const fn period_year(&self) -> Option<PeriodYear> {
        match self {
            Self::Quarter { year, .. } | Self::Year { year } => Some(*year),
            _ => None,
        }
    }

    /// Returns the quarter number for quarterly periods
    #[must_use]
    pub const fn quarter(&self) -> Option<u8> {
        match self {
            Self::Quarter { quarter, .. } => Some(quarter.get()),
            _ => None,
        }
    }

    /// Returns the validated quarter component for quarterly periods.
    #[must_use]
    pub const fn quarter_of_year(&self) -> Option<QuarterOfYear> {
        match self {
            Self::Quarter { quarter, .. } => Some(*quarter),
            _ => None,
        }
    }

    /// Returns true if this is a quarterly period
    #[must_use]
    pub const fn is_quarterly(&self) -> bool {
        matches!(self, Self::Quarter { .. })
    }

    /// Returns true if this is an annual period
    #[must_use]
    pub const fn is_annual(&self) -> bool {
        matches!(self, Self::Year { .. })
    }

    /// Returns true if this is a specific date period
    #[must_use]
    pub const fn is_date(&self) -> bool {
        matches!(self, Self::Date(_))
    }
}

/// Calendar period bucket with date-boundary helpers.
///
/// `CalendarPeriod` is closed over actual calendar years, quarters, and dates.
/// It intentionally has no provider-specific `Other` variant and rejects fiscal
/// aliases such as `FY2023`; use [`ReportingPeriod`] for fiscal/provider labels.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CalendarPeriod {
    /// Calendar quarter with year and quarter number.
    Quarter {
        /// The calendar year of the quarter.
        year: PeriodYear,
        /// The quarter number (1-4).
        quarter: QuarterOfYear,
    },
    /// Calendar year.
    Year {
        /// The calendar year.
        year: PeriodYear,
    },
    /// Specific calendar date.
    Date(
        /// Validated calendar date.
        PeriodDate,
    ),
}

impl CalendarPeriod {
    /// Builds a validated calendar quarter.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] or
    /// [`DomainError::InvalidPeriodQuarter`] when either component is outside
    /// its accepted range.
    pub fn quarterly(year: i32, quarter: u8) -> Result<Self, DomainError> {
        Ok(Self::Quarter {
            year: PeriodYear::new(year)?,
            quarter: QuarterOfYear::new(quarter)?,
        })
    }

    /// Builds a validated calendar year.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] when `year` is outside
    /// `0..=9999`.
    pub fn annual(year: i32) -> Result<Self, DomainError> {
        Ok(Self::Year {
            year: PeriodYear::new(year)?,
        })
    }

    /// Builds a validated calendar date.
    ///
    /// # Errors
    /// Returns [`DomainError::InvalidPeriodYear`] when `date.year()` is
    /// outside `0..=9999`.
    pub fn date(date: NaiveDate) -> Result<Self, DomainError> {
        Ok(Self::Date(PeriodDate::new(date)?))
    }

    /// Returns the canonical display/serde code for this calendar period.
    #[must_use]
    pub fn code(&self) -> Cow<'_, str> {
        match self {
            Self::Quarter { year, quarter } => Cow::Owned(format!("{year}Q{quarter}")),
            Self::Year { year } => Cow::Owned(year.to_string()),
            Self::Date(date) => Cow::Owned(date.to_string()),
        }
    }

    /// Returns the year for this calendar period, if applicable.
    #[must_use]
    pub const fn year(&self) -> Option<i32> {
        match self {
            Self::Quarter { year, .. } | Self::Year { year } => Some(year.get()),
            Self::Date(_) => None,
        }
    }

    /// Returns the validated year component for this calendar period, if applicable.
    #[must_use]
    pub const fn period_year(&self) -> Option<PeriodYear> {
        match self {
            Self::Quarter { year, .. } | Self::Year { year } => Some(*year),
            Self::Date(_) => None,
        }
    }

    /// Returns the quarter number for calendar quarters.
    #[must_use]
    pub const fn quarter(&self) -> Option<u8> {
        match self {
            Self::Quarter { quarter, .. } => Some(quarter.get()),
            Self::Year { .. } | Self::Date(_) => None,
        }
    }

    /// Returns the validated quarter component for calendar quarters.
    #[must_use]
    pub const fn quarter_of_year(&self) -> Option<QuarterOfYear> {
        match self {
            Self::Quarter { quarter, .. } => Some(*quarter),
            Self::Year { .. } | Self::Date(_) => None,
        }
    }

    /// Returns true if this is a calendar quarter.
    #[must_use]
    pub const fn is_quarterly(&self) -> bool {
        matches!(self, Self::Quarter { .. })
    }

    /// Returns true if this is a calendar year.
    #[must_use]
    pub const fn is_annual(&self) -> bool {
        matches!(self, Self::Year { .. })
    }

    /// Returns true if this is a specific calendar date.
    #[must_use]
    pub const fn is_date(&self) -> bool {
        matches!(self, Self::Date(_))
    }

    /// Returns the next chronological quarter bucket after this calendar period.
    ///
    /// - For `Date`, computes the quarter containing the date, then returns the next quarter.
    /// - For `Quarter`, returns the next quarter (wrapping to Q1 of the next year).
    /// - For `Year`, returns `Q1` of the next year.
    #[must_use]
    pub fn next_quarter(&self) -> Option<Self> {
        match self {
            Self::Date(d) => {
                let (year, quarter) = quarter_for_date(d.get())?;
                let (year, quarter) = increment_quarter(year, quarter)?;
                Some(Self::Quarter { year, quarter })
            }
            Self::Quarter { year, quarter } => {
                let (year, quarter) = increment_quarter(*year, *quarter)?;
                Some(Self::Quarter { year, quarter })
            }
            Self::Year { year } => {
                let next_year = PeriodYear::new(year.get() + 1).ok()?;
                Some(Self::Quarter {
                    year: next_year,
                    quarter: QuarterOfYear::Q1,
                })
            }
        }
    }

    /// Returns the last calendar date of the year this period belongs to.
    ///
    /// - For `Date`, uses the date's year.
    /// - For `Quarter`, uses the quarter's calendar year.
    /// - For `Year`, uses that year.
    #[must_use]
    pub fn year_end(&self) -> NaiveDate {
        let y = match self {
            Self::Date(d) => d.get().year(),
            Self::Quarter { year, .. } | Self::Year { year } => year.get(),
        };
        expect_valid_date(y, 12, 31)
    }

    /// Returns the first calendar date covered by this period.
    ///
    /// - For `Date`, returns the date itself.
    /// - For `Quarter`, returns the first day of that calendar quarter.
    /// - For `Year`, returns January 1 of that year.
    #[must_use]
    pub const fn start_date(&self) -> NaiveDate {
        match self {
            Self::Date(d) => d.get(),
            Self::Quarter { year, quarter } => {
                let month = match quarter.get() {
                    1 => 1,
                    2 => 4,
                    3 => 7,
                    4 => 10,
                    _ => unreachable!(),
                };
                expect_valid_date(year.get(), month, 1)
            }
            Self::Year { year } => expect_valid_date(year.get(), 1, 1),
        }
    }

    /// Returns the last calendar date covered by this period.
    ///
    /// - For `Date`, returns the date itself.
    /// - For `Quarter`, returns the last day of that calendar quarter.
    /// - For `Year`, returns December 31 of that year.
    #[must_use]
    pub const fn end_date(&self) -> NaiveDate {
        match self {
            Self::Date(d) => d.get(),
            Self::Quarter { year, quarter } => {
                let (month, day) = match quarter.get() {
                    1 => (3, 31),
                    2 => (6, 30),
                    3 => (9, 30),
                    4 => (12, 31),
                    _ => unreachable!(),
                };
                expect_valid_date(year.get(), month, day)
            }
            Self::Year { year } => expect_valid_date(year.get(), 12, 31),
        }
    }

    /// Returns true if this calendar period overlaps `other`.
    ///
    /// Calendar periods are closed ranges over dates, so adjacent quarters do
    /// not overlap, while a year overlaps every quarter and date inside that
    /// calendar year.
    #[must_use]
    pub fn overlaps(&self, other: &Self) -> bool {
        self.start_date() <= other.end_date() && other.start_date() <= self.end_date()
    }

    /// Returns true if this calendar period fully contains `other`.
    ///
    /// Containment is directional: a year contains its quarters and dates, but
    /// a quarter or date does not contain the year.
    #[must_use]
    pub fn contains(&self, other: &Self) -> bool {
        self.start_date() <= other.start_date() && self.end_date() >= other.end_date()
    }

    /// Returns true if both values are the same exact calendar bucket.
    ///
    /// Cross-granularity containment is not an exact match: a calendar year
    /// and one of its quarters overlap, but they are not the same bucket.
    #[must_use]
    pub fn is_same_exact_bucket_as(&self, other: &Self) -> bool {
        self == other
    }
}

// Per-format parser results.
//
// `Some(Ok(p))` means the input fully matched the format and produced a valid
// `ReportingPeriod`. `Some(Err(()))` means the input matched the format structurally
// (i.e., the original regex would have matched) but the captured values were
// invalid (e.g., `2023Q5`, `2023-13-01`); the caller treats this as
// `InvalidPeriodFormat`. `None` means the input does not match this format
// and the caller should try the next one.
type ReportingPeriodAttempt = Option<Result<ReportingPeriod, ()>>;

#[inline]
const fn expect_valid_date(year: i32, month: u32, day: u32) -> NaiveDate {
    let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
        unreachable!();
    };
    date
}

#[inline]
fn read_4_digits(b: &[u8], start: usize) -> Option<i32> {
    if start + 4 > b.len() {
        return None;
    }
    let mut v: i32 = 0;
    for &c in &b[start..start + 4] {
        if !c.is_ascii_digit() {
            return None;
        }
        v = v * 10 + i32::from(c - b'0');
    }
    Some(v)
}

#[inline]
fn read_1_or_2_digits(b: &[u8], start: usize) -> Option<(u32, usize)> {
    let &first = b.get(start)?;
    if !first.is_ascii_digit() {
        return None;
    }
    let d1 = u32::from(first - b'0');
    if let Some(&second) = b.get(start + 1)
        && second.is_ascii_digit()
    {
        Some((d1 * 10 + u32::from(second - b'0'), 2))
    } else {
        Some((d1, 1))
    }
}

#[inline]
fn date_or_err(year: i32, month: u32, day: u32) -> Result<ReportingPeriod, ()> {
    NaiveDate::from_ymd_opt(year, month, day)
        .ok_or(())
        .and_then(|date| ReportingPeriod::date(date).map_err(|_| ()))
}

fn calendar_year(s: &str) -> Option<PeriodYear> {
    let b = s.as_bytes();
    if b.len() != 4 {
        return None;
    }
    PeriodYear::new(read_4_digits(b, 0)?).ok()
}

fn quarter_for_date(d: NaiveDate) -> Option<(PeriodYear, QuarterOfYear)> {
    let year = PeriodYear::new(d.year()).ok()?;
    let m = d.month();
    let quarter = match m {
        1..=3 => QuarterOfYear::Q1,
        4..=6 => QuarterOfYear::Q2,
        7..=9 => QuarterOfYear::Q3,
        _ => QuarterOfYear::Q4,
    };
    Some((year, quarter))
}

fn increment_quarter(
    year: PeriodYear,
    quarter: QuarterOfYear,
) -> Option<(PeriodYear, QuarterOfYear)> {
    if quarter.get() < QuarterOfYear::MAX {
        let next_quarter = QuarterOfYear::new(quarter.get() + 1).ok()?;
        Some((year, next_quarter))
    } else {
        let next_year = PeriodYear::new(year.get() + 1).ok()?;
        Some((next_year, QuarterOfYear::Q1))
    }
}

impl ReportingPeriod {
    /// Parse quarterly period format: "2023Q4", "2023-Q4", "2023 Q4",
    /// "2023  Q4", "2023\tQ4", "2023 \t Q4".
    fn parse_quarterly(s: &str) -> ReportingPeriodAttempt {
        let b = s.as_bytes();
        // Minimum form is `YYYYQ#` (6 bytes).
        if b.len() < 6 {
            return None;
        }

        let year = PeriodYear::new(read_4_digits(b, 0)?).ok()?;
        let mut idx = 4;

        // Optional separator between the year and the `Q`:
        //   - a single `-`, or
        //   - a run of ASCII whitespace (matches `parse_year`'s "Fiscal "
        //     handling — `is_ascii_whitespace` covers space, tab, CR, LF and
        //     form feed but, importantly, no Unicode whitespace).
        // The two forms are mutually exclusive: we don't mix `-` with spaces.
        if b[idx] == b'-' {
            idx += 1;
        } else {
            while idx < b.len() && b[idx].is_ascii_whitespace() {
                idx += 1;
            }
        }
        if idx >= b.len() {
            return None;
        }

        // Case-insensitive 'Q'.
        if b[idx] != b'Q' && b[idx] != b'q' {
            return None;
        }
        idx += 1;

        let q_bytes = b.get(idx..)?;
        if q_bytes.is_empty() {
            return None;
        }

        // Valid quarters are always exactly one digit. Multi-digit runs of
        // digits structurally match the original `Q\d+` regex but are
        // out-of-range, so they're a structural-only match (caller turns into
        // `InvalidPeriodFormat`). A multi-byte tail with any non-digit is
        // simply not a quarterly token at all.
        if q_bytes.len() > 1 {
            return q_bytes.iter().all(u8::is_ascii_digit).then_some(Err(()));
        }

        let c = q_bytes[0];
        if !c.is_ascii_digit() {
            return None;
        }
        let quarter = c - b'0';
        let Ok(quarter) = QuarterOfYear::new(quarter) else {
            return Some(Err(()));
        };

        Some(Ok(Self::Quarter { year, quarter }))
    }

    /// Parse year period format: "2023", "FY2023", "Fiscal 2023".
    fn parse_year(s: &str) -> Option<Self> {
        let b = s.as_bytes();
        let digits_start = match b.len() {
            4 => 0,
            6 if b[..2].eq_ignore_ascii_case(b"FY") => 2,
            n if n >= 11 && b[..6].eq_ignore_ascii_case(b"FISCAL") => {
                let mut i = 6;
                while i < n && b[i].is_ascii_whitespace() {
                    i += 1;
                }
                if i == 6 {
                    return None;
                }
                i
            }
            _ => return None,
        };

        if b.len() - digits_start != 4 {
            return None;
        }
        let year = PeriodYear::new(read_4_digits(b, digits_start)?).ok()?;
        Some(Self::Year { year })
    }

    /// Parse date period: ISO `YYYY[-/]M[M][-/]D[D]`, US `M[M]/D[D]/YYYY`,
    /// or day-first `D[D]-M[M]-YYYY`.
    fn parse_date(s: &str) -> ReportingPeriodAttempt {
        let b = s.as_bytes();
        if !(8..=10).contains(&b.len()) {
            return None;
        }

        // ISO: `YYYY[-/]M[M][-/]D[D]`.
        if let Some(year) = read_4_digits(b, 0)
            && (b[4] == b'-' || b[4] == b'/')
        {
            let sep = b[4];
            let (month, m_len) = read_1_or_2_digits(b, 5)?;
            let after_m = 5 + m_len;
            if b.get(after_m).copied() == Some(sep) {
                let (day, d_len) = read_1_or_2_digits(b, after_m + 1)?;
                if after_m + 1 + d_len == b.len() {
                    return Some(date_or_err(year, month, day));
                }
            }
            // Leading `YYYY[-/]` cannot match the US or day-first shapes
            // (those need 1-2 digits before the first separator), so a
            // partial ISO match means no date format matches.
            return None;
        }

        // US (`/`-separated, year last) and day-first (`-`-separated, year
        // last) share a common prefix of 1-2 digits + separator + 1-2 digits
        // + same separator + 4-digit year.
        let (first, first_len) = read_1_or_2_digits(b, 0)?;
        let sep = *b.get(first_len)?;
        if sep != b'/' && sep != b'-' {
            return None;
        }

        let (second, second_len) = read_1_or_2_digits(b, first_len + 1)?;
        let after_second = first_len + 1 + second_len;
        if b.get(after_second).copied() != Some(sep) {
            return None;
        }

        let year_start = after_second + 1;
        if b.len() - year_start != 4 {
            return None;
        }
        let year = read_4_digits(b, year_start)?;

        let (month, day) = if sep == b'/' {
            (first, second)
        } else {
            (second, first)
        };

        Some(date_or_err(year, month, day))
    }
}

impl From<ReportingPeriod> for String {
    fn from(val: ReportingPeriod) -> Self {
        val.code().into_owned()
    }
}

impl fmt::Display for ReportingPeriod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.code())
    }
}

impl Serialize for ReportingPeriod {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.code())
    }
}

impl<'de> Deserialize<'de> for ReportingPeriod {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        raw.parse::<Self>().map_err(DeError::custom)
    }
}

impl std::str::FromStr for ReportingPeriod {
    type Err = DomainError;

    /// Invariant: the canonical form of a `ReportingPeriod::Other` produced here is
    /// guaranteed not to parse as any structured variant on a subsequent
    /// deserialize. Without this, inputs like `"-2023Q4"` (rejected by the
    /// structured parsers because of the leading `-`) would canonicalize to
    /// `"2023Q4"` and serialize back to a string that re-parses as
    /// `ReportingPeriod::Quarter`, breaking round-trip identity.
    ///
    /// To maintain the invariant without accepting malformed aliases, we
    /// re-run the structured parsers on the canonicalized form before
    /// returning `Other`. If any parser recognizes the canonical form, we
    /// return `InvalidPeriodFormat`; otherwise a malformed input such as
    /// `"-2023Q4"` would silently become `ReportingPeriod::Quarter`.
    #[cfg_attr(feature = "tracing", tracing::instrument(level = "debug", err))]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();

        if trimmed.is_empty() {
            return Err(DomainError::InvalidPeriodFormat {
                format: s.to_string(),
            });
        }

        let invalid = || DomainError::InvalidPeriodFormat {
            format: s.to_string(),
        };

        match Self::parse_quarterly(trimmed) {
            Some(Ok(period)) => return Ok(period),
            Some(Err(())) => return Err(invalid()),
            None => {}
        }

        if let Some(period) = Self::parse_year(trimmed) {
            return Ok(period);
        }

        match Self::parse_date(trimmed) {
            Some(Ok(period)) => return Ok(period),
            Some(Err(())) => return Err(invalid()),
            None => {}
        }

        let canonical = Canonical::try_new(trimmed).map_err(|_| invalid())?;

        // Re-run the structured parsers against the canonical token. Any
        // structured match is rejected: supported aliases have already matched
        // above, so reaching this point means canonicalization would otherwise
        // convert a malformed spelling into a modeled value.
        let canonical_str = canonical.as_ref();
        if Self::parse_quarterly(canonical_str).is_some() {
            return Err(invalid());
        }
        if Self::parse_year(canonical_str).is_some() {
            return Err(invalid());
        }
        if Self::parse_date(canonical_str).is_some() {
            return Err(invalid());
        }

        Ok(Self::Other(OtherPeriod::from_canonical_unchecked(
            canonical,
        )))
    }
}

impl TryFrom<String> for ReportingPeriod {
    type Error = DomainError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.as_str().parse()
    }
}

impl TryFrom<ReportingPeriod> for CalendarPeriod {
    type Error = DomainError;

    fn try_from(period: ReportingPeriod) -> Result<Self, Self::Error> {
        match period {
            ReportingPeriod::Quarter { year, quarter } => Ok(Self::Quarter { year, quarter }),
            ReportingPeriod::Year { year } => Ok(Self::Year { year }),
            ReportingPeriod::Date(date) => Ok(Self::Date(date)),
            ReportingPeriod::Other(other) => Err(DomainError::InvalidPeriodFormat {
                format: other.to_string(),
            }),
        }
    }
}

impl From<CalendarPeriod> for ReportingPeriod {
    fn from(period: CalendarPeriod) -> Self {
        match period {
            CalendarPeriod::Quarter { year, quarter } => Self::Quarter { year, quarter },
            CalendarPeriod::Year { year } => Self::Year { year },
            CalendarPeriod::Date(date) => Self::Date(date),
        }
    }
}

impl From<CalendarPeriod> for String {
    fn from(val: CalendarPeriod) -> Self {
        val.code().into_owned()
    }
}

impl fmt::Display for CalendarPeriod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.code())
    }
}

impl Serialize for CalendarPeriod {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.code())
    }
}

impl<'de> Deserialize<'de> for CalendarPeriod {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        raw.parse::<Self>().map_err(DeError::custom)
    }
}

impl std::str::FromStr for CalendarPeriod {
    type Err = DomainError;

    /// Parses calendar-only period tokens.
    ///
    /// Unlike [`ReportingPeriod`], this parser rejects fiscal aliases such as
    /// `FY2023` and unknown provider-specific labels.
    #[cfg_attr(feature = "tracing", tracing::instrument(level = "debug", err))]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();

        if trimmed.is_empty() {
            return Err(DomainError::InvalidPeriodFormat {
                format: s.to_string(),
            });
        }

        let invalid = || DomainError::InvalidPeriodFormat {
            format: s.to_string(),
        };

        match ReportingPeriod::parse_quarterly(trimmed) {
            Some(Ok(ReportingPeriod::Quarter { year, quarter })) => {
                return Ok(Self::Quarter { year, quarter });
            }
            Some(Ok(_)) => unreachable!("quarter parser only emits quarter periods"),
            Some(Err(())) => return Err(invalid()),
            None => {}
        }

        if let Some(year) = calendar_year(trimmed) {
            return Ok(Self::Year { year });
        }

        match ReportingPeriod::parse_date(trimmed) {
            Some(Ok(ReportingPeriod::Date(date))) => return Ok(Self::Date(date)),
            Some(Ok(_)) => unreachable!("date parser only emits date periods"),
            Some(Err(())) => return Err(invalid()),
            None => {}
        }

        Err(invalid())
    }
}

impl TryFrom<String> for CalendarPeriod {
    type Error = DomainError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.as_str().parse()
    }
}