gedcomkit 0.1.6

A byte-preserving GEDCOM document model: decoding, parsing, readings, version conversion, plausibility checks, and the GEDZIP container, for GEDCOM 5.5 through 7.x.
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
//! Reading a GEDCOM date payload without ever rewriting it.
//!
//! The payload is preserved exactly and parsed into a
//! structured view beside it, used for sorting, timelines, and plausibility
//! checks. An expression the parser does not understand keeps its text, is
//! marked [`DateKind::Unparsed`], is still displayed, and is never coerced.
//!
//! The forms below are not taken from the specification alone. Public
//! compatibility corpora contain many date shapes beyond the specification's
//! own `5 JAN 1882`. Files hold `5 January 1882`, `4 juillet 1764`, `21. Januar 1809`,
//! `rundt 1645`, `8.2.1664`, `Feb 11 th 1809`, `about May 1703`, `<1802>`,
//! `Infant`, and `DEAD`. Anything a genealogist typed once is in there
//! somewhere, so the parser is generous where it can be certain and honest
//! where it cannot.

use crate::Node;
use std::fmt::{self, Write as _};

/// The calendar a date is expressed in.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum Calendar {
    /// The default when nothing says otherwise.
    #[default]
    Gregorian,
    /// `@#DJULIAN@` in 5.5.1, `JULIAN` in 7.0.
    Julian,
    /// `@#DHEBREW@` / `HEBREW`.
    Hebrew,
    /// `@#DFRENCH R@` / `FRENCH_R`.
    FrenchRepublican,
    /// `@#DROMAN@`, which no producer in the corpus emits.
    Roman,
    /// A calendar escape the reader does not recognize, kept as written.
    Unknown,
}

impl Calendar {
    /// The name to show a user.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Gregorian => "Gregorian",
            Self::Julian => "Julian",
            Self::Hebrew => "Hebrew",
            Self::FrenchRepublican => "French Republican",
            Self::Roman => "Roman",
            Self::Unknown => "unrecognized calendar",
        }
    }
}

/// What kind of claim the expression makes about when something happened.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum DateKind {
    /// A single date, as precisely as it was given.
    #[default]
    Exact,
    /// `ABT`, and the several dozen ways files spell "about".
    About,
    /// `CAL` — worked out from another date.
    Calculated,
    /// `EST` — a guess the recorder owned up to.
    Estimated,
    /// `BEF`.
    Before,
    /// `AFT`.
    After,
    /// `BET … AND …`.
    Between,
    /// `FROM … TO …`, or either half alone.
    Period,
    /// `INT` — someone's reading of an unclear original.
    Interpreted,
    /// The parser could not read it. The text is still there.
    Unparsed,
}

impl DateKind {
    /// The word to put in front of the date when showing it.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Exact => "",
            Self::About => "about",
            Self::Calculated => "calculated",
            Self::Estimated => "estimated",
            Self::Before => "before",
            Self::After => "after",
            Self::Between => "between",
            Self::Period => "during",
            Self::Interpreted => "interpreted as",
            Self::Unparsed => "as written",
        }
    }
}

/// How much of a date is known.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum Precision {
    /// Nothing usable was recovered.
    #[default]
    None,
    /// A year.
    Year,
    /// A year and a month.
    Month,
    /// A year, a month, and a day.
    Day,
}

/// A point on the calendar, to whatever precision was given.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct DatePoint {
    /// The year. Negative for years before the common era.
    pub year: i32,
    /// The month, 1–12, when given.
    pub month: Option<u8>,
    /// The day, 1–31, when given.
    pub day: Option<u8>,
}

impl DatePoint {
    const fn year(year: i32) -> Self {
        Self {
            year,
            month: None,
            day: None,
        }
    }

    /// A point built by a caller, for writing a date the file does not yet
    /// hold. `None` when the pieces cannot be a calendar date: a month
    /// outside 1–12, a day outside 1–31, or a day given without its month.
    #[must_use]
    pub fn from_ymd(year: i32, month: Option<u8>, day: Option<u8>) -> Option<Self> {
        if let Some(month) = month
            && !(1..=12).contains(&month)
        {
            return None;
        }
        match day {
            Some(_) if month.is_none() => return None,
            Some(day) if !(1..=31).contains(&day) => return None,
            _ => (),
        }
        Some(Self { year, month, day })
    }

    /// The point as a GEDCOM `DATE` payload: `5 JAN 1882`, `JAN 1882`, or
    /// `1882` — the specification's own spelling, which both 5.5.1 and 7.0
    /// accept. This is the inverse the parser lacks by design: reading never
    /// rewrites a payload, so producing one is an explicit act.
    ///
    /// A negative year renders with GEDCOM 7's `BCE` epoch (`44 BCE`), which
    /// 5.5.1 has no spelling for.
    ///
    /// ```
    /// use gedcomkit::dates::DatePoint;
    ///
    /// let point = DatePoint::from_ymd(1882, Some(1), Some(5)).expect("valid");
    /// assert_eq!(point.to_gedcom(), "5 JAN 1882");
    /// assert_eq!(format!("ABT {}", DatePoint::from_ymd(1900, None, None).expect("valid").to_gedcom()), "ABT 1900");
    /// ```
    #[must_use]
    pub fn to_gedcom(&self) -> String {
        let (era_year, era) = if self.year < 0 {
            (-self.year, " BCE")
        } else {
            (self.year, "")
        };
        match (self.month, self.day) {
            (Some(month), Some(day)) => {
                format!("{day} {} {era_year}{era}", month_abbreviation(month))
            }
            (Some(month), None) => format!("{} {era_year}{era}", month_abbreviation(month)),
            _ => format!("{era_year}{era}"),
        }
    }

    /// How much of this point is known.
    #[must_use]
    pub const fn precision(&self) -> Precision {
        match (self.month, self.day) {
            (Some(_), Some(_)) => Precision::Day,
            (Some(_), None) => Precision::Month,
            _ => Precision::Year,
        }
    }

    /// A single number that orders points correctly, with an absent month or
    /// day sorting to the start of its period.
    #[must_use]
    pub fn sort_key(&self) -> i64 {
        let month = self.month.map_or(0, i64::from);
        let day = self.day.map_or(0, i64::from);
        i64::from(self.year) * 10_000 + month * 100 + day
    }
}

impl fmt::Display for DatePoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.month, self.day) {
            (Some(month), Some(day)) => {
                write!(formatter, "{day} {} {}", month_name(month), self.year)
            }
            (Some(month), None) => write!(formatter, "{} {}", month_name(month), self.year),
            _ => write!(formatter, "{}", self.year),
        }
    }
}

/// A GEDCOM date payload, read.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct GedcomDate {
    /// The payload exactly as the file wrote it. Never modified.
    pub original: String,
    /// The calendar, Gregorian unless an escape says otherwise.
    pub calendar: Calendar,
    /// What kind of claim the expression makes.
    pub kind: DateKind,
    /// The earliest instant the expression admits, when one was recovered.
    pub earliest: Option<DatePoint>,
    /// The latest instant the expression admits, when one was recovered. Equal
    /// to `earliest` for an exact date.
    pub latest: Option<DatePoint>,
    /// Text the expression carried that is not part of the date: a 7.0
    /// `PHRASE`, a parenthesized 5.5.1 phrase, or the whole payload when it
    /// could not be read at all.
    pub phrase: Option<String>,
}

impl GedcomDate {
    /// Reads a `DATE` payload.
    ///
    /// ```
    /// use gedcomkit::dates::{DateKind, GedcomDate};
    ///
    /// let date = GedcomDate::parse("ABT 5 January 1882");
    /// assert_eq!(date.kind, DateKind::About);
    /// assert_eq!(date.year_hint(), Some(1882));
    /// assert_eq!(date.display(), "about 5 January 1882");
    /// // The payload itself is never rewritten.
    /// assert_eq!(date.original, "ABT 5 January 1882");
    ///
    /// // What cannot be read says so and keeps its text.
    /// assert_eq!(GedcomDate::parse("Infant").kind, DateKind::Unparsed);
    /// ```
    #[must_use]
    pub fn parse(payload: &str) -> Self {
        let original = payload.to_owned();
        let (calendar, rest) = split_calendar(payload.trim());
        let (rest, phrase) = split_phrase(&rest);
        let mut date = parse_expression(&rest).unwrap_or_else(|| Self {
            original: original.clone(),
            calendar,
            kind: DateKind::Unparsed,
            earliest: None,
            latest: None,
            phrase: Some(payload.trim().to_owned()),
        });
        date.original = original;
        date.calendar = calendar;
        if let Some(phrase) = phrase {
            date.phrase = Some(phrase);
        }
        date
    }

    /// Whether anything usable was recovered.
    #[must_use]
    pub const fn is_parsed(&self) -> bool {
        !matches!(self.kind, DateKind::Unparsed)
    }

    /// How much of the date is known.
    #[must_use]
    pub fn precision(&self) -> Precision {
        self.earliest
            .map_or(Precision::None, |point| point.precision())
    }

    /// The year to file this date under, for a timeline or a sort.
    ///
    /// An unparsed expression still offers one when it contains something that
    /// can only be a year: `19 Jun 1820 age 26` files under 1820. That is a
    /// hint, not a reading, and the interface must not present it as the date.
    #[must_use]
    pub fn year_hint(&self) -> Option<i32> {
        if let Some(point) = self.earliest {
            return Some(point.year);
        }
        four_digit_year(&self.original)
    }

    /// A single number that orders dates on a timeline, or `None` when nothing
    /// orderable was found.
    #[must_use]
    pub fn sort_key(&self) -> Option<i64> {
        self.earliest
            .map(|point| point.sort_key())
            .or_else(|| self.year_hint().map(|year| i64::from(year) * 10_000))
    }

    /// The date in the interface's own words, for a caller that wants one
    /// string. The original payload stays available and is what an editor
    /// shows.
    #[must_use]
    pub fn display(&self) -> String {
        match (self.kind, self.earliest, self.latest) {
            (DateKind::Unparsed, ..) => self.original.trim().to_owned(),
            (DateKind::Exact, Some(point), _) => point.to_string(),
            (DateKind::Between, Some(from), Some(to)) => format!("between {from} and {to}"),
            (DateKind::Period, Some(from), Some(to)) => format!("from {from} to {to}"),
            (DateKind::Period, Some(from), None) => format!("from {from}"),
            (DateKind::Period, None, Some(to)) => format!("to {to}"),
            (kind, Some(point), _) | (kind, None, Some(point)) => {
                format!("{} {point}", kind.label())
            }
            _ => self.original.trim().to_owned(),
        }
    }

    /// The reading written in GEDCOM 5.5.1's own date grammar — `ABT 5 JAN
    /// 1882` for `about 5 January 1882` — or `None` when the grammar cannot
    /// hold it without losing something.
    ///
    /// This is a writer's tool, for a producer turning its own data into a
    /// file; reading never calls it, because a payload that arrived in a file
    /// is never rewritten. It is also deliberately narrow: what it returns
    /// says exactly what the original said, in the specification's spelling,
    /// or it returns nothing and leaves the caller to decide — keep the
    /// original, or write it as a date phrase `(…)`.
    ///
    /// - Keywords, months, and qualifiers in any language the reader knows
    ///   come back as `ABT`, `BEF`, `AFT`, `BET … AND …`, `FROM … TO …`,
    ///   `CAL`, `EST`, and the three-letter months.
    /// - A dual year the grammar can spell (`1740/41`, one year apart) is
    ///   kept; a slashed pair it cannot (`1679/1683`) makes an exact date an
    ///   `INT` date carrying the original as its phrase, and any other kind
    ///   `None`.
    /// - A phrase the original carried makes an exact date `INT … (phrase)`,
    ///   and any other kind `None`, since 5.5.1 gives only `INT` a phrase. An
    ///   `INT` date with no phrase is `None`: the grammar requires one, and
    ///   the bare date would pass an interpretation off as a fact.
    /// - The Gregorian and Julian calendars are written (the latter with
    ///   its `@#DJULIAN@` escape); the others number their months
    ///   differently from what the reader recovered, so they return `None`.
    /// - A Gregorian year before the common era is written `44 B.C.`. The
    ///   Julian grammar has neither an era nor a dual year, so a Julian date
    ///   before the era is `None`, and a slashed Julian year follows the
    ///   unspellable-pair rule above.
    ///
    /// ```
    /// use gedcomkit::dates::GedcomDate;
    ///
    /// let written = |text: &str| GedcomDate::parse(text).to_gedcom_5_5_1();
    /// assert_eq!(written("about 5 January 1882").as_deref(), Some("ABT 5 JAN 1882"));
    /// assert_eq!(written("13. september 1900").as_deref(), Some("13 SEP 1900"));
    /// assert_eq!(written("from 1701 to 1742").as_deref(), Some("FROM 1701 TO 1742"));
    /// assert_eq!(written("1740/41").as_deref(), Some("1740/41"));
    /// assert_eq!(written("1679/1683").as_deref(), Some("INT 1679 (1679/1683)"));
    /// assert_eq!(written("Infant"), None);
    /// ```
    #[must_use]
    pub fn to_gedcom_5_5_1(&self) -> Option<String> {
        let escape = match self.calendar {
            Calendar::Gregorian => "",
            Calendar::Julian => "@#DJULIAN@ ",
            _ => return None,
        };
        let gregorian = self.calendar == Calendar::Gregorian;
        // `B.C.` belongs to the Gregorian grammar alone.
        let before_era = [self.earliest, self.latest]
            .iter()
            .flatten()
            .any(|point| point.year < 0);
        if before_era && !gregorian {
            return None;
        }
        let dual = dual_year(&self.original);
        // The grammar spells a dual year only as a Gregorian year of the common
        // era followed by the next one's last two digits. Any other slashed
        // pair is only safe to carry as the phrase of an `INT` date, which
        // exists only for a single date.
        let spelled_dual = match dual {
            Some((first, second)) if second == first + 1 && gregorian && !before_era => {
                Some(second)
            }
            Some(_) if self.kind != DateKind::Exact => return None,
            _ => None,
        };
        let point = |point: DatePoint| -> String {
            let mut text = String::from(escape);
            text.push_str(&point_5_5_1(point));
            if let Some(second) = spelled_dual {
                // Writing to a String cannot fail.
                let _ = write!(text, "/{:02}", second.rem_euclid(100));
            }
            text
        };
        let reading = match (self.kind, self.earliest, self.latest) {
            // An unparsed date has no points and falls to the last arm.
            (DateKind::Exact | DateKind::Interpreted, Some(at), _) => point(at),
            (DateKind::About, Some(at), _) => format!("ABT {}", point(at)),
            (DateKind::Calculated, Some(at), _) => format!("CAL {}", point(at)),
            (DateKind::Estimated, Some(at), _) => format!("EST {}", point(at)),
            (DateKind::Before, _, Some(at)) => format!("BEF {}", point(at)),
            (DateKind::After, Some(at), _) => format!("AFT {}", point(at)),
            (DateKind::Between, Some(from), Some(to)) => {
                format!("BET {} AND {}", point(from), point(to))
            }
            (DateKind::Period, Some(from), Some(to)) => {
                format!("FROM {} TO {}", point(from), point(to))
            }
            (DateKind::Period, Some(from), None) => format!("FROM {}", point(from)),
            (DateKind::Period, None, Some(to)) => format!("TO {}", point(to)),
            _ => return None,
        };
        let phrase = match (&self.phrase, dual) {
            (Some(phrase), _) => Some(phrase.clone()),
            (None, Some(_)) if spelled_dual.is_none() => Some(self.original.trim().to_owned()),
            _ => None,
        };
        match phrase {
            // `INT` is only ever written with the phrase that justifies it;
            // without one, the bare date would silently turn an
            // interpretation into a fact.
            None if self.kind == DateKind::Interpreted => None,
            None => Some(reading),
            Some(phrase) if matches!(self.kind, DateKind::Exact | DateKind::Interpreted) => {
                // A phrase is closed by the first `)`, so brackets inside it
                // would end it early.
                let phrase = phrase.replace('(', "[").replace(')', "]");
                Some(format!("INT {reading} ({phrase})"))
            }
            Some(_) => None,
        }
    }
}

/// One point in 5.5.1's spelling: the specification's months, and `B.C.`
/// rather than 7.0's `BCE`.
fn point_5_5_1(point: DatePoint) -> String {
    if point.year < 0 {
        let positive = DatePoint {
            year: -point.year,
            ..point
        };
        return format!("{} B.C.", positive.to_gedcom());
    }
    point.to_gedcom()
}

/// The first slashed year pair in a payload — `1740/41`, `1679/1683` — as
/// two full years. `8/2/1664` is a numeric date, not a pair, and is skipped
/// because a pair's first half has three or four digits.
fn dual_year(text: &str) -> Option<(i32, i32)> {
    let bytes = text.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if !bytes[index].is_ascii_digit() {
            index += 1;
            continue;
        }
        let start = index;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
        }
        let first_text = &text[start..index];
        if index >= bytes.len() || bytes[index] != b'/' || !(3..=4).contains(&first_text.len()) {
            continue;
        }
        let second_start = index + 1;
        let mut end = second_start;
        while end < bytes.len() && bytes[end].is_ascii_digit() {
            end += 1;
        }
        let second_text = &text[second_start..end];
        // Another slash after the pair makes it part of a numeric date.
        if second_text.is_empty() || bytes.get(end) == Some(&b'/') {
            index = end;
            continue;
        }
        let first = first_text.parse::<i32>().ok()?;
        let second = if second_text.len() >= first_text.len() {
            second_text.parse::<i32>().ok()?
        } else {
            // `1740/41` names the second year by its last digits; `1699/00`
            // rolls over into the next century.
            let modulus = 10_i32.pow(u32::try_from(second_text.len()).ok()?);
            let tail = second_text.parse::<i32>().ok()?;
            let mut second = first - first.rem_euclid(modulus) + tail;
            if second <= first {
                second += modulus;
            }
            second
        };
        return Some((first, second));
    }
    None
}

fn parse_expression(input: &str) -> Option<GedcomDate> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return None;
    }

    let build = |kind: DateKind, earliest: Option<DatePoint>, latest: Option<DatePoint>| {
        Some(GedcomDate {
            original: String::new(),
            calendar: Calendar::Gregorian,
            kind,
            earliest,
            latest,
            phrase: None,
        })
    };

    // Two-sided forms first: `BET x AND y`, `FROM x TO y`. The separators are
    // matched case-insensitively and in every spelling the corpus shows.
    if let Some((left, right)) = split_keyword(trimmed, &["AND", "ET", "UND", "OG"])
        && let Some(prefix) =
            strip_keyword(left, &["BET", "BETWEEN", "ENTRE", "ZWISCHEN", "MELLOM"])
    {
        let from = parse_point(prefix);
        let to = parse_point(right);
        if from.is_some() || to.is_some() {
            return build(DateKind::Between, from, to);
        }
    }
    if let Some((left, right)) = split_keyword(trimmed, &["TO", "AU", "BIS", "TIL"])
        && let Some(prefix) = strip_keyword(left, &["FROM", "DE", "DU", "VON", "FRA"])
    {
        let from = parse_point(prefix);
        let to = parse_point(right);
        if from.is_some() || to.is_some() {
            return build(DateKind::Period, from, to);
        }
    }

    // `FROM x` opens an interval and `TO x` closes one, so neither fits the
    // generic prefix loop below.
    if let Some(rest) = strip_keyword(trimmed, &["FROM", "SINCE"]) {
        return build(DateKind::Period, parse_point(rest), None);
    }
    if let Some(rest) = strip_keyword(trimmed, &["TO", "UNTIL"]) {
        return build(DateKind::Period, None, parse_point(rest));
    }

    // One-sided prefixes.
    for (kind, words) in PREFIXES {
        if let Some(rest) = strip_keyword(trimmed, words) {
            let point = parse_point(rest)?;
            return match kind {
                DateKind::Before => build(DateKind::Before, None, Some(point)),
                DateKind::After => build(DateKind::After, Some(point), None),
                other => build(*other, Some(point), Some(point)),
            };
        }
    }

    // `<1802>` is one producer's way of saying "uncertain".
    if let Some(inner) = trimmed
        .strip_prefix('<')
        .and_then(|rest| rest.strip_suffix('>'))
    {
        let point = parse_point(inner)?;
        return build(DateKind::About, Some(point), Some(point));
    }

    let point = parse_point(trimmed)?;
    build(DateKind::Exact, Some(point), Some(point))
}

/// Prefixes in every spelling the surveyed exports show, English first.
/// A trailing full stop is handled by the matcher, not listed here.
const PREFIXES: &[(DateKind, &[&str])] = &[
    (
        DateKind::About,
        &[
            "ABT",
            "ABOUT",
            "CIRCA",
            "CA",
            "APPROX",
            "ENVIRON",
            "UM",
            "RUNDT",
            "OMKRING",
            "CERCA",
            "VERSO",
            "VERS",
            "AROUND",
            "APPROXIMATELY",
            "APROXIMADAMENTE",
            "OMTRENT",
            "CIRKA",
            "CIR",
            "C",
            "PROBABLY",
            "PROBABLEMENT",
        ],
    ),
    (DateKind::Calculated, &["CAL", "CALCULATED"]),
    (DateKind::Estimated, &["EST", "ESTIMATED"]),
    (
        DateKind::Before,
        &["BEF", "BEFORE", "AVANT", "VOR", "PRIMA", "ANTES", "FØR"],
    ),
    (
        DateKind::After,
        &[
            "AFT", "AFTER", "APRES", "APRÈS", "NACH", "DOPO", "DESPUES", "ETTER", "EFTER",
        ],
    ),
    (DateKind::Interpreted, &["INT", "INTERPRETED"]),
];

/// Splits off a calendar escape. 5.5.1 writes `@#DJULIAN@`, 7.0 writes the
/// name as a bare word.
fn split_calendar(input: &str) -> (Calendar, String) {
    if let Some(rest) = input.strip_prefix("@#D")
        && let Some((name, remainder)) = rest.split_once('@')
    {
        return (calendar_from(name), remainder.trim().to_owned());
    }
    for (name, calendar) in [
        ("GREGORIAN", Calendar::Gregorian),
        ("JULIAN", Calendar::Julian),
        ("HEBREW", Calendar::Hebrew),
        ("FRENCH_R", Calendar::FrenchRepublican),
        ("ROMAN", Calendar::Roman),
    ] {
        if let Some(rest) = input.strip_prefix(name)
            && rest.starts_with(' ')
        {
            return (calendar, rest.trim().to_owned());
        }
    }
    (Calendar::Gregorian, input.to_owned())
}

fn calendar_from(name: &str) -> Calendar {
    match name.trim().to_ascii_uppercase().as_str() {
        "GREGORIAN" => Calendar::Gregorian,
        "JULIAN" => Calendar::Julian,
        "HEBREW" => Calendar::Hebrew,
        "FRENCH R" | "FRENCH_R" => Calendar::FrenchRepublican,
        "ROMAN" => Calendar::Roman,
        _ => Calendar::Unknown,
    }
}

/// Splits off a 5.5.1 parenthesized phrase, which may be the whole payload.
fn split_phrase(input: &str) -> (String, Option<String>) {
    let trimmed = input.trim();
    let Some(open) = trimmed.find('(') else {
        return (trimmed.to_owned(), None);
    };
    let Some(close) = trimmed.rfind(')') else {
        return (trimmed.to_owned(), None);
    };
    if close < open {
        return (trimmed.to_owned(), None);
    }
    let phrase = trimmed[open + 1..close].trim().to_owned();
    let rest = format!("{} {}", &trimmed[..open], &trimmed[close + 1..]);
    (
        rest.trim().to_owned(),
        (!phrase.is_empty()).then_some(phrase),
    )
}

/// Finds a bare keyword used as a separator, case-insensitively.
fn split_keyword<'a>(input: &'a str, words: &[&str]) -> Option<(&'a str, &'a str)> {
    let upper = input.to_ascii_uppercase();
    for word in words {
        let needle = format!(" {word} ");
        if let Some(position) = upper.find(&needle) {
            return Some((&input[..position], &input[position + needle.len()..]));
        }
    }
    None
}

/// Strips a leading keyword, with or without a trailing full stop.
///
/// The keyword may be followed by a space, a full stop, or — as `abt1810`
/// and `c1700` are written — directly by the date's first digit. Case is
/// compared for every script, so `après` matches `APRÈS`.
fn strip_keyword<'a>(input: &'a str, words: &[&str]) -> Option<&'a str> {
    let trimmed = input.trim();
    for word in words {
        let Some(after) = strip_prefix_ignoring_case(trimmed, word) else {
            continue;
        };
        let rest = match after.chars().next() {
            Some(' ' | '.') => after[1..].trim(),
            Some(digit) if digit.is_ascii_digit() => after,
            _ => continue,
        };
        if !rest.is_empty() {
            return Some(rest);
        }
    }
    None
}

/// `text` without its first characters when they are `word`, compared
/// without regard to case in any script.
fn strip_prefix_ignoring_case<'a>(text: &'a str, word: &str) -> Option<&'a str> {
    let mut characters = text.char_indices();
    let mut end = 0;
    for expected in word.chars() {
        let (index, actual) = characters.next()?;
        if !actual.to_lowercase().eq(expected.to_lowercase()) {
            return None;
        }
        end = index + actual.len_utf8();
    }
    Some(&text[end..])
}

/// Reads one point: a year, a month and year, or a day, month, and year.
fn parse_point(input: &str) -> Option<DatePoint> {
    let cleaned = input.trim().trim_end_matches([',', '.', ';']).trim();
    if cleaned.is_empty() {
        return None;
    }

    // GEDCOM 7's epoch: `44 BCE` is the year before 43 BCE. The point's year
    // is negated, which is exactly what [`DatePoint::to_gedcom`] writes back.
    // 5.5.1 spells the same epoch `B.C.`, whose last full stop the trim above
    // has already taken.
    if let Some(rest) = ["BCE", "bce", "B.C", "b.c"]
        .iter()
        .find_map(|suffix| cleaned.strip_suffix(suffix))
        .map(str::trim_end)
        .filter(|rest| !rest.is_empty())
    {
        let mut point = parse_point(rest)?;
        point.year = -point.year;
        return Some(point);
    }

    // `8.2.1664` and `4/18/1616`. Both appear in the corpus; the first is
    // day-first European and the second is month-first American, and the only
    // way to tell them apart is the separator, which is what producers use.
    if let Some(point) = parse_numeric(cleaned) {
        return Some(point);
    }

    // A dual year — `1740/41`, `1679/1683` — is one day written under two
    // calendars, not two dates. The historical year is the first.
    if let Some(point) = parse_dual_year(cleaned) {
        return Some(point);
    }
    // The same pair ending a full date, `10 January 1566/67`, files under the
    // first year; the writer finds the pair again in the original.
    if let Some((head, tail)) = cleaned.rsplit_once(' ')
        && let Some(year) = parse_dual_year(tail)
    {
        return parse_point(&format!("{head} {}", year.year));
    }

    // Producers lose the space between pieces — `19JUL1818`, `21 Nov1896`,
    // and `5 Novem1886` all appear in real exports — so a run of
    // digits and a run of letters are separated before anything is matched.
    let tokens: Vec<String> = cleaned
        .split([' ', '\u{a0}', ','])
        .flat_map(split_runs)
        .filter(|token| {
            !matches!(
                token.to_ascii_lowercase().as_str(),
                "de" | "of" | "den" | "le"
            )
        })
        .collect();
    let tokens: Vec<&str> = tokens.iter().map(String::as_str).collect();

    match tokens.as_slice() {
        [year] => parse_year(year).map(DatePoint::year),
        [month, year] => {
            let year = parse_year(year)?;
            Some(DatePoint {
                year,
                month: Some(month_number(month)?),
                day: None,
            })
        }
        [first, second, year] => {
            let year = parse_year(year)?;
            // A month written as a word decides the order: `5 January 1882`
            // is day-first and `April 9, 1950` month-first. Only when both
            // are numbers is day-first assumed, because `5 1 1882` would
            // otherwise read its `5` as May.
            let named = |token: &str| !token.bytes().all(|byte| byte.is_ascii_digit());
            let (month, day) = if named(second) {
                (month_number(second)?, first)
            } else if named(first) {
                (month_number(first)?, second)
            } else {
                month_number(second).map_or_else(
                    || month_number(first).map(|month| (month, second)),
                    |month| Some((month, first)),
                )?
            };
            Some(DatePoint {
                year,
                month: Some(month),
                day: Some(parse_day(day)?),
            })
        }
        [first, second, third, fourth] => {
            // `Feb 11 th 1809`, and `April 15 , 1873` once punctuation splits.
            let year = parse_year(fourth)?;
            let month = month_number(first).or_else(|| month_number(second))?;
            let day = parse_day(second).or_else(|| parse_day(third))?;
            Some(DatePoint {
                year,
                month: Some(month),
                day: Some(day),
            })
        }
        _ => None,
    }
}

fn parse_numeric(input: &str) -> Option<DatePoint> {
    for (separator, month_first) in [('.', false), ('/', true), ('-', false)] {
        let parts: Vec<&str> = input.split(separator).collect();
        if parts.len() != 3 {
            continue;
        }
        if !parts
            .iter()
            .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
        {
            continue;
        }
        // A four-digit first part is a year, whatever the separator: ISO order.
        if parts[0].len() == 4 {
            let year = parts[0].parse::<i32>().ok()?;
            return Some(DatePoint {
                year,
                month: parse_month_number(parts[1]),
                day: parse_day(parts[2]),
            });
        }
        let year = parse_year(parts[2])?;
        let (day, month) = if month_first {
            (parts[1], parts[0])
        } else {
            (parts[0], parts[1])
        };
        return Some(DatePoint {
            year,
            month: parse_month_number(month),
            day: parse_day(day),
        });
    }
    None
}

/// `1740/41` and `1679/1683`: the Julian and Gregorian readings of one year.
fn parse_dual_year(input: &str) -> Option<DatePoint> {
    let (first, second) = input.split_once('/')?;
    let digits = |value: &str| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit());
    if !digits(first) || !digits(second) || !(3..=4).contains(&first.len()) {
        return None;
    }
    Some(DatePoint::year(first.parse::<i32>().ok()?))
}

/// Splits a token at every boundary between digits and non-digits, dropping
/// anything that is only punctuation.
fn split_runs(token: &str) -> Vec<String> {
    let mut runs = Vec::new();
    let mut current = String::new();
    let mut in_digits = false;
    for character in token.chars() {
        let digit = character.is_ascii_digit();
        if !current.is_empty() && digit != in_digits {
            runs.push(std::mem::take(&mut current));
        }
        in_digits = digit;
        current.push(character);
    }
    if !current.is_empty() {
        runs.push(current);
    }
    runs.retain(|run| run.chars().any(char::is_alphanumeric));
    runs
}

fn parse_year(token: &str) -> Option<i32> {
    let cleaned = token.trim_matches(|character: char| !character.is_ascii_digit());
    if cleaned.is_empty() {
        return None;
    }
    // `1740/41` and `1699/1700` are dual years: the same day under two
    // calendars. The first is the historical year and is what we file under.
    let first = cleaned.split('/').next()?;
    let year = first.parse::<i32>().ok()?;
    (0..=9999).contains(&year).then_some(year)
}

fn parse_day(token: &str) -> Option<u8> {
    let cleaned = token.trim_matches(|character: char| !character.is_ascii_digit());
    let day = cleaned.parse::<u8>().ok()?;
    (1..=31).contains(&day).then_some(day)
}

fn parse_month_number(token: &str) -> Option<u8> {
    let month = token.trim().parse::<u8>().ok()?;
    (1..=12).contains(&month).then_some(month)
}

/// The month names the corpus actually contains: GEDCOM's own abbreviations,
/// English in full, and the French, German, Norwegian, Italian, and Spanish
/// forms that a `FamilySearch` export carries through from the original record.
fn month_number(token: &str) -> Option<u8> {
    let key = token
        .trim_matches(|character: char| !character.is_alphanumeric())
        .to_lowercase();
    if key.is_empty() {
        return None;
    }
    if let Some(month) = parse_month_number(&key) {
        return Some(month);
    }
    for (index, names) in MONTH_NAMES.iter().enumerate() {
        if names.iter().any(|name| *name == key) {
            return u8::try_from(index + 1).ok();
        }
    }
    // Any unambiguous prefix of an English month, which covers `Novem` and
    // `Sept` without inviting a wrong guess.
    for (index, names) in MONTH_NAMES.iter().enumerate() {
        if key.len() >= 3 && names[1].starts_with(&key) {
            return u8::try_from(index + 1).ok();
        }
    }
    None
}

/// Per month: the GEDCOM abbreviation, the English name, then the other
/// languages found in the surveyed exports.
const MONTH_NAMES: [&[&str]; 12] = [
    &[
        "jan", "january", "janvier", "janv", "januar", "januari", "gennaio", "enero", "jänner",
    ],
    &[
        "feb", "february", "février", "fevrier", "févr", "fév", "februar", "februari", "febbraio",
        "febrero",
    ],
    &[
        "mar", "march", "mars", "märz", "marz", "maerz", "marzo", "marts",
    ],
    &["apr", "april", "avril", "avr", "aprile", "abril"],
    &["may", "mai", "maggio", "mayo", "mei"],
    &["jun", "june", "juin", "juni", "giugno", "junio"],
    &["jul", "july", "juillet", "juil", "juli", "luglio", "julio"],
    &["aug", "august", "août", "aout", "agosto", "augusti"],
    &[
        "sep",
        "september",
        "septembre",
        "settembre",
        "septiembre",
        "sept",
    ],
    &[
        "oct", "october", "octobre", "oktober", "ottobre", "octubre", "okt",
    ],
    &["nov", "november", "novembre", "noviembre"],
    &[
        "dec",
        "december",
        "décembre",
        "decembre",
        "dezember",
        "desember",
        "déc",
        "dicembre",
        "diciembre",
        "des",
    ],
];

/// The GEDCOM month abbreviation, `JAN` through `DEC`.
fn month_abbreviation(month: u8) -> &'static str {
    const NAMES: [&str; 12] = [
        "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
    ];
    NAMES
        .get(usize::from(month.saturating_sub(1)))
        .copied()
        .unwrap_or("")
}

fn month_name(month: u8) -> &'static str {
    const NAMES: [&str; 12] = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];
    NAMES
        .get(usize::from(month.saturating_sub(1)))
        .copied()
        .unwrap_or("")
}

/// When a record was last changed or created, read from a `CHAN` or `CREA`
/// structure: the `DATE` beneath it, and the `TIME` beneath that.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Timestamp {
    /// The `DATE` payload, parsed. `original` holds it exactly as written.
    pub date: GedcomDate,
    /// The `TIME` payload exactly as written — `10:31:12`, when given.
    pub time: Option<String>,
}

impl Timestamp {
    /// The timestamp in the interface's words: the date's display form, with
    /// the time appended when there is one.
    #[must_use]
    pub fn display(&self) -> String {
        self.time.as_ref().map_or_else(
            || self.date.display(),
            |time| format!("{} {time}", self.date.display()),
        )
    }
}

/// A record's last-change timestamp: its `CHAN` structure read, falling back
/// to `CREA` — GEDCOM 7's creation date — when no change was recorded.
///
/// ```
/// let document = gedcomkit::Document::parse(
///     "0 HEAD\n0 @I1@ INDI\n1 CHAN\n2 DATE 5 JAN 2026\n3 TIME 10:31:12\n0 TRLR\n",
/// )?;
/// let record = document.record("@I1@").expect("record");
/// let changed = gedcomkit::dates::changed(record).expect("timestamp");
/// assert_eq!(changed.display(), "5 January 2026 10:31:12");
/// # Ok::<(), gedcomkit::GedcomError>(())
/// ```
#[must_use]
pub fn changed(record: &Node) -> Option<Timestamp> {
    ["CHAN", "CREA"]
        .iter()
        .find_map(|tag| record.first(tag))
        .and_then(timestamp_of)
}

/// Reads the `DATE`/`TIME` pair beneath any structure that carries one — a
/// `CHAN`, a `CREA`, or a vendor's own stamp.
#[must_use]
pub fn timestamp_of(node: &Node) -> Option<Timestamp> {
    let date = node.first("DATE")?;
    Some(Timestamp {
        time: date.value_of("TIME").or_else(|| node.value_of("TIME")),
        date: GedcomDate::parse(&date.logical_value()),
    })
}

/// Builds the structure that records a timestamp.
///
/// `CHAN` (or `CREA`, or a vendor tag) with `DATE` and, when given, `TIME`
/// beneath it. The crate does no I/O and reads no clock; the caller supplies
/// the moment.
///
/// ```
/// use gedcomkit::dates::{DatePoint, timestamp_node};
///
/// let point = DatePoint::from_ymd(2026, Some(9), Some(6)).expect("valid");
/// let node = timestamp_node("CHAN", point, Some("10:31:12"));
/// let text = gedcomkit::Document { records: vec![node] }.to_text();
/// assert_eq!(text, "0 CHAN\n1 DATE 6 SEP 2026\n2 TIME 10:31:12\n");
/// ```
#[must_use]
pub fn timestamp_node(tag: &str, point: DatePoint, time: Option<&str>) -> Node {
    let mut date = Node::with_value("DATE", point.to_gedcom());
    if let Some(time) = time {
        date = date.child(Node::with_value("TIME", time));
    }
    Node::new(tag).child(date)
}

/// The first standalone four-digit run that could be a year.
fn four_digit_year(input: &str) -> Option<i32> {
    let bytes = input.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if !bytes[index].is_ascii_digit() {
            index += 1;
            continue;
        }
        let start = index;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
        }
        if index - start == 4
            && let Ok(year) = input[start..index].parse::<i32>()
            && (1000..=2999).contains(&year)
        {
            return Some(year);
        }
    }
    None
}

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

    fn parsed(payload: &str) -> GedcomDate {
        GedcomDate::parse(payload)
    }

    #[test]
    fn the_payload_is_never_modified() {
        let date = parsed("  ABT 1900  ");
        assert_eq!(date.original, "  ABT 1900  ");
    }

    #[test]
    fn a_reading_is_written_in_the_5_5_1_grammar() {
        let written = |text: &str| parsed(text).to_gedcom_5_5_1();
        let cases: &[(&str, Option<&str>)] = &[
            ("5 JAN 1882", Some("5 JAN 1882")),
            ("29 May 1823", Some("29 MAY 1823")),
            ("Apr 1850", Some("APR 1850")),
            ("about 1575", Some("ABT 1575")),
            ("Abt. 1656", Some("ABT 1656")),
            ("before 29 September 1793", Some("BEF 29 SEP 1793")),
            ("after 1850", Some("AFT 1850")),
            ("8. Juni 1886", Some("8 JUN 1886")),
            ("14.10.1635", Some("14 OCT 1635")),
            ("<1873>", Some("ABT 1873")),
            ("May 22, 1942", Some("22 MAY 1942")),
            ("23Jun1807", Some("23 JUN 1807")),
            ("environ janvier 1620", Some("ABT JAN 1620")),
            ("avant 6 septembre 1892", Some("BEF 6 SEP 1892")),
            ("BET 1898 AND 1902", Some("BET 1898 AND 1902")),
            ("FROM 1701", Some("FROM 1701")),
            ("CAL 1824", Some("CAL 1824")),
            ("EST 1630", Some("EST 1630")),
            ("1699/00", Some("1699/00")),
            ("1679/1683", Some("INT 1679 (1679/1683)")),
            ("ABT 1679/1683", None),
            (
                "INT 5 JAN 1882 (the fifth, by the ink)",
                Some("INT 5 JAN 1882 (the fifth, by the ink)"),
            ),
            ("@#DJULIAN@ 10 MAR 1700", Some("@#DJULIAN@ 10 MAR 1700")),
            ("@#DHEBREW@ 1 TSH 5600", None),
            // Found in review: none of these may lose anything in silence.
            ("INT 1900", None),
            ("1740/1741 BCE", Some("INT 1740 B.C. (1740/1741 BCE)")),
            ("@#DJULIAN@ 44 BCE", None),
            (
                "@#DJULIAN@ 1740/41",
                Some("INT @#DJULIAN@ 1740 (@#DJULIAN@ 1740/41)"),
            ),
            ("ABT @#DJULIAN@ 1740/41", None),
            ("44 BCE", Some("44 B.C.")),
            ("DEAD", None),
            ("", None),
        ];
        for (text, expected) in cases {
            assert_eq!(written(text).as_deref(), *expected, "{text:?}");
        }
    }

    #[test]
    fn what_is_written_reads_back_as_the_same_reading() {
        for text in [
            "about 5 January 1882",
            "before July 1843",
            "from 1701 to 1742",
            "1740/41",
            "44 BCE",
        ] {
            let reading = parsed(text);
            let written = reading.to_gedcom_5_5_1().expect("writable");
            let reread = parsed(&written);
            assert_eq!(
                (reread.kind, reread.earliest, reread.latest),
                (reading.kind, reading.earliest, reading.latest),
                "{text:?} -> {written:?}"
            );
        }
    }

    #[test]
    fn the_spellings_a_producer_writing_its_own_data_met() {
        // Each of these reached a 5.5.1 export as a date phrase before the
        // reader knew it.
        let written = |text: &str| parsed(text).to_gedcom_5_5_1();
        let cases: &[(&str, &str)] = &[
            ("après 12 juillet 1670", "AFT 12 JUL 1670"),
            ("før 1679", "BEF 1679"),
            ("etter 1649", "AFT 1649"),
            ("vers 1646", "ABT 1646"),
            ("Cir 1700", "ABT 1700"),
            ("c. 1625", "ABT 1625"),
            ("c1700", "ABT 1700"),
            ("abt1810", "ABT 1810"),
            ("around 1580", "ABT 1580"),
            ("before29 Sept 1793", "BEF 29 SEP 1793"),
            ("April 9, 1950", "9 APR 1950"),
            ("12 DÉC 1790", "12 DEC 1790"),
            ("desember 1702", "DEC 1702"),
            ("10 January 1566/67", "10 JAN 1566/67"),
            ("entre 1700 et 1705", "BET 1700 AND 1705"),
            ("du 1656 au 1663", "FROM 1656 TO 1663"),
        ];
        for (text, expected) in cases {
            assert_eq!(written(text).as_deref(), Some(*expected), "{text:?}");
        }
        // A keyword needs a boundary: `Cal` is not `C` followed by `al`.
        assert_eq!(parsed("CAL 1824").kind, DateKind::Calculated);
        assert_eq!(parsed("Catherine").kind, DateKind::Unparsed);
    }

    #[test]
    fn a_numeric_date_is_not_a_dual_year() {
        assert_eq!(dual_year("4/18/1616"), None);
        assert_eq!(dual_year("8.2.1664"), None);
        assert_eq!(dual_year("1740/41"), Some((1740, 1741)));
        assert_eq!(dual_year("5 JAN 1699/00"), Some((1699, 1700)));
    }

    #[test]
    fn specification_forms_read_as_written() {
        assert_eq!(parsed("1821").earliest, Some(DatePoint::year(1821)));
        let exact = parsed("5 JAN 1882");
        assert_eq!(exact.kind, DateKind::Exact);
        assert_eq!(
            exact.earliest,
            Some(DatePoint {
                year: 1882,
                month: Some(1),
                day: Some(5)
            })
        );
        assert_eq!(parsed("ABT 1900").kind, DateKind::About);
        assert_eq!(parsed("EST 1630").kind, DateKind::Estimated);
        assert_eq!(parsed("CAL 1824").kind, DateKind::Calculated);
        assert_eq!(parsed("BEF 1815").kind, DateKind::Before);
        assert_eq!(parsed("AFT 1649").kind, DateKind::After);
    }

    #[test]
    fn ranges_and_periods_keep_both_ends() {
        let between = parsed("BET 1898 AND 1902");
        assert_eq!(between.kind, DateKind::Between);
        assert_eq!(between.earliest, Some(DatePoint::year(1898)));
        assert_eq!(between.latest, Some(DatePoint::year(1902)));

        let period = parsed("from 1701 to 1742");
        assert_eq!(period.kind, DateKind::Period);
        assert_eq!(period.earliest, Some(DatePoint::year(1701)));
        assert_eq!(period.latest, Some(DatePoint::year(1742)));
    }

    #[test]
    fn the_forms_the_requirement_corpus_actually_contains() {
        // Every one of these was measured in family.ged on 2026-09-04.
        type Case = (&'static str, i32, Option<u8>, Option<u8>, DateKind);
        let cases: &[Case] = &[
            ("5 January 1882", 1882, Some(1), Some(5), DateKind::Exact),
            ("22 March 1635", 1635, Some(3), Some(22), DateKind::Exact),
            ("about 1575", 1575, None, None, DateKind::About),
            ("Abt 1872", 1872, None, None, DateKind::About),
            ("abt. 1625", 1625, None, None, DateKind::About),
            ("rundt 1645", 1645, None, None, DateKind::About),
            ("um 1660", 1660, None, None, DateKind::About),
            ("environ 1830", 1830, None, None, DateKind::About),
            ("4 juillet 1764", 1764, Some(7), Some(4), DateKind::Exact),
            ("21. Januar 1809", 1809, Some(1), Some(21), DateKind::Exact),
            ("22. März 1873", 1873, Some(3), Some(22), DateKind::Exact),
            ("16 gennaio 1847", 1847, Some(1), Some(16), DateKind::Exact),
            (
                "13 de enero de 1855",
                1855,
                Some(1),
                Some(13),
                DateKind::Exact,
            ),
            ("January 1652", 1652, Some(1), None, DateKind::Exact),
            ("8.2.1664", 1664, Some(2), Some(8), DateKind::Exact),
            ("4/18/1616", 1616, Some(4), Some(18), DateKind::Exact),
            ("<1802>", 1802, None, None, DateKind::About),
            (
                "before 29 March 1795",
                1795,
                Some(3),
                Some(29),
                DateKind::Before,
            ),
            ("Vor Februar 1843", 1843, Some(2), None, DateKind::Before),
            ("19JUL1818", 1818, Some(7), Some(19), DateKind::Exact),
            ("21 Nov1896", 1896, Some(11), Some(21), DateKind::Exact),
            ("April 15, 1873", 1873, Some(4), Some(15), DateKind::Exact),
            ("07 October 1853,", 1853, Some(10), Some(7), DateKind::Exact),
            ("1679/1683", 1679, None, None, DateKind::Exact),
            ("ABT Oct 1803", 1803, Some(10), None, DateKind::About),
            (
                "About 21 Jun 1969",
                1969,
                Some(6),
                Some(21),
                DateKind::About,
            ),
        ];

        for (payload, year, month, day, kind) in cases {
            let date = parsed(payload);
            assert_eq!(date.kind, *kind, "kind of {payload:?}");
            let point = date
                .earliest
                .or(date.latest)
                .unwrap_or_else(|| panic!("{payload:?} produced no point"));
            assert_eq!(point.year, *year, "year of {payload:?}");
            assert_eq!(point.month, *month, "month of {payload:?}");
            assert_eq!(point.day, *day, "day of {payload:?}");
        }
    }

    #[test]
    fn what_cannot_be_read_keeps_its_text_and_says_so() {
        for payload in ["Infant", "DEAD", "Unknown", "1799 or 12 April 1811"] {
            let date = parsed(payload);
            assert_eq!(date.kind, DateKind::Unparsed, "{payload:?}");
            assert_eq!(date.display(), payload);
            assert_eq!(date.phrase.as_deref(), Some(payload));
        }
    }

    #[test]
    fn an_unreadable_expression_can_still_offer_a_year_to_sort_by() {
        let date = parsed("19 Jun 1820 age 26");
        assert_eq!(date.kind, DateKind::Unparsed);
        assert_eq!(date.year_hint(), Some(1820));
        assert!(date.sort_key().is_some());
    }

    #[test]
    fn a_calendar_escape_is_recognized_in_both_versions() {
        let five = parsed("@#DJULIAN@ 12 FEB 1740");
        assert_eq!(five.calendar, Calendar::Julian);
        assert_eq!(five.earliest.expect("point").day, Some(12));

        let seven = parsed("JULIAN 12 FEB 1740");
        assert_eq!(seven.calendar, Calendar::Julian);
    }

    #[test]
    fn an_interpretation_keeps_its_phrase() {
        let date = parsed("INT 1900 (the year the church burned)");
        assert_eq!(date.kind, DateKind::Interpreted);
        assert_eq!(date.earliest, Some(DatePoint::year(1900)));
        assert_eq!(date.phrase.as_deref(), Some("the year the church burned"));
    }

    #[test]
    fn a_version_seven_bce_year_reads_negative_and_writes_back() {
        let date = parsed("44 BCE");
        assert_eq!(date.kind, DateKind::Exact);
        assert_eq!(date.earliest, Some(DatePoint::year(-44)));
        assert_eq!(date.earliest.expect("point").to_gedcom(), "44 BCE");

        let about = parsed("ABT 100 BCE");
        assert_eq!(about.kind, DateKind::About);
        assert_eq!(about.earliest, Some(DatePoint::year(-100)));

        // Earlier BCE years sort earlier.
        assert!(
            parsed("100 BCE").sort_key() < parsed("44 BCE").sort_key(),
            "100 BCE came after 44 BCE"
        );
    }

    #[test]
    fn a_before_only_date_sorts_at_its_boundary_year() {
        // `BEF 1815` has no earliest instant; it is filed at the year named,
        // which is the boundary of what it admits. Asserted so a change to
        // this compromise is a decision rather than an accident.
        let date = parsed("BEF 1815");
        assert_eq!(date.earliest, None);
        assert_eq!(date.year_hint(), Some(1815));
        assert_eq!(date.sort_key(), Some(1815 * 10_000));
    }

    #[test]
    fn dates_sort_by_the_earliest_instant_they_admit() {
        let mut dates = ["1900", "5 JAN 1882", "ABT 1875", "BET 1890 AND 1895"]
            .map(parsed)
            .to_vec();
        dates.sort_by_key(GedcomDate::sort_key);

        let order: Vec<&str> = dates.iter().map(|date| date.original.as_str()).collect();
        assert_eq!(
            order,
            ["ABT 1875", "5 JAN 1882", "BET 1890 AND 1895", "1900"]
        );
    }
}