citum-engine 0.53.4

Citum citation and bibliography processor
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
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus
*/

//! Rendering logic for date fields with locale-aware formatting.
//!
//! This module handles date component rendering with support for different date forms,
//! time formatting, and locale-specific date presentation.

use crate::reference::{EdtfString, Reference};
use crate::values::{ComponentValues, ProcHints, ProcValues, RenderOptions};
use citum_edtf::{Day, Edtf, MonthOrSeason, Timezone, UnspecifiedYear, Year};
use citum_schema::locale::{GeneralTerm, TermForm};
use citum_schema::options::dates::TimeFormat;
use citum_schema::reference::types::RefDate;
use citum_schema::template::{DateForm, DateVariable as TemplateDateVar, TemplateDate};

fn month_to_string(month: u32, months: &[String]) -> String {
    if month > 0 {
        let index = month - 1;
        if let Some(month_name) = months.get(index as usize) {
            month_name.clone()
        } else {
            String::new()
        }
    } else {
        String::new()
    }
}

fn extract_month(date: &EdtfString, months: &[String]) -> String {
    let parsed_date = date.parse();
    let month: Option<u32> = match parsed_date {
        RefDate::Edtf(edtf) => edtf.month(),
        RefDate::Literal(_) => None,
    };
    match month {
        Some(month) => month_to_string(month, months),
        None => String::new(),
    }
}

/// Compute the delta for unspecified year ranges.
fn unspecified_year_delta(u: &UnspecifiedYear) -> i64 {
    match u {
        UnspecifiedYear::None => 0,
        UnspecifiedYear::One => 9,
        UnspecifiedYear::Two => 99,
        UnspecifiedYear::Three => 999,
        UnspecifiedYear::Four => 9999,
    }
}

/// Format a year with era-aware rendering.
fn format_display_year(
    year: &Year,
    date_terms: &citum_schema::locale::DateTerms,
    era_labels: &citum_schema::options::dates::EraLabels,
    _neg_unspecified: &citum_schema::options::dates::NegativeUnspecifiedYears,
    range_delimiter: &str,
) -> String {
    // Handle positive unspecified years: normalize 'u' to 'X'
    if year.unspecified != UnspecifiedYear::None && year.value > 0 {
        let mut s = year.value.to_string();
        let unspec_count = match year.unspecified {
            UnspecifiedYear::One => 1,
            UnspecifiedYear::Two => 2,
            UnspecifiedYear::Three => 3,
            UnspecifiedYear::Four => 4,
            _ => 0,
        };
        for _ in 0..unspec_count {
            if let Some(last) = s.pop()
                && last != '0'
            {
                s.push('X');
            }
        }
        if s.len() < year.value.to_string().len() {
            let diff = year.value.to_string().len() - s.len();
            for _ in 0..diff {
                s.push('X');
            }
        }
        return s;
    }

    // Handle negative unspecified years: compute historical range
    if year.unspecified != UnspecifiedYear::None && year.value <= 0 {
        let delta = unspecified_year_delta(&year.unspecified);
        let astronomical_min = year.value - delta;
        let astronomical_max = year.value;
        let historical_end = 1 - astronomical_max;
        let historical_start = 1 - astronomical_min;

        let era_term = match era_labels {
            citum_schema::options::dates::EraLabels::Default => {
                date_terms.before_era.as_deref().unwrap_or("")
            }
            citum_schema::options::dates::EraLabels::BcAd => date_terms.bc.as_deref().unwrap_or(""),
            citum_schema::options::dates::EraLabels::BceCe => {
                date_terms.bce.as_deref().unwrap_or("")
            }
        };

        if era_term.is_empty() {
            format!("{historical_start}{range_delimiter}{historical_end}")
        } else {
            format!("{historical_start}{range_delimiter}{historical_end} {era_term}")
        }
    } else if year.value <= 0 {
        // Fully specified negative year
        let historical_year = 1 - year.value;
        let era_term = match era_labels {
            citum_schema::options::dates::EraLabels::Default => {
                date_terms.before_era.as_deref().unwrap_or("")
            }
            citum_schema::options::dates::EraLabels::BcAd => date_terms.bc.as_deref().unwrap_or(""),
            citum_schema::options::dates::EraLabels::BceCe => {
                date_terms.bce.as_deref().unwrap_or("")
            }
        };

        if era_term.is_empty() {
            historical_year.to_string()
        } else {
            format!("{historical_year} {era_term}")
        }
    } else {
        // Positive year
        let era_term = match era_labels {
            citum_schema::options::dates::EraLabels::Default => "",
            citum_schema::options::dates::EraLabels::BcAd => date_terms.ad.as_deref().unwrap_or(""),
            citum_schema::options::dates::EraLabels::BceCe => {
                date_terms.ce.as_deref().unwrap_or("")
            }
        };

        if era_term.is_empty() {
            year.value.to_string()
        } else {
            format!("{} {}", year.value, era_term)
        }
    }
}

/// Legacy format_display_year for backwards compatibility.
fn format_display_year_legacy(year: &Year, before_era: Option<&str>) -> String {
    if year.unspecified != UnspecifiedYear::None {
        return year.to_string();
    }

    if year.value <= 0 {
        let historical_year = 1 - year.value;
        if let Some(term) = before_era.filter(|term| !term.is_empty()) {
            format!("{historical_year} {term}")
        } else {
            historical_year.to_string()
        }
    } else {
        year.value.to_string()
    }
}

#[allow(dead_code, reason = "kept for backwards compatibility")]
fn extract_display_year_legacy(date: &EdtfString, before_era: Option<&str>) -> String {
    match date.parse() {
        RefDate::Edtf(edtf) => match edtf {
            Edtf::Date(date) => format_display_year_legacy(&date.year, before_era),
            Edtf::Interval(interval) => {
                format_display_year_legacy(&interval.start.year, before_era)
            }
            Edtf::IntervalFrom(date) | Edtf::IntervalTo(date) => {
                format_display_year_legacy(&date.year, before_era)
            }
        },
        RefDate::Literal(_) => String::new(),
    }
}

fn extract_range_end(
    date: &EdtfString,
    months: &[String],
    date_terms: &citum_schema::locale::DateTerms,
    era_labels: &citum_schema::options::dates::EraLabels,
    neg_unspecified: &citum_schema::options::dates::NegativeUnspecifiedYears,
    range_delimiter: &str,
) -> Option<String> {
    match date.parse() {
        RefDate::Edtf(edtf) => match edtf {
            Edtf::Interval(interval) => {
                let end = &interval.end;
                let year = format_display_year(
                    &end.year,
                    date_terms,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                );
                let month = match end.month_or_season {
                    Some(MonthOrSeason::Month(m)) => Some(m),
                    _ => None,
                };
                let day = match end.day {
                    Some(Day::Day(d)) => Some(d),
                    _ => None,
                };

                match (month, day) {
                    (Some(m), Some(d)) if m > 0 && d > 0 => {
                        let month_str = month_to_string(m, months);
                        Some(format!("{} {}, {}", month_str, d, year))
                    }
                    (Some(m), _) if m > 0 => {
                        let month_str = month_to_string(m, months);
                        Some(format!("{} {}", month_str, year))
                    }
                    _ => Some(year),
                }
            }
            Edtf::IntervalFrom(_date) => None, // Open-ended
            Edtf::IntervalTo(date) => {
                let year = format_display_year(
                    &date.year,
                    date_terms,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                );
                Some(year)
            }
            _ => None,
        },
        RefDate::Literal(_) => None,
    }
}

/// Formats a time with the specified format, optionally including seconds and timezone.
///
/// Converts 24-hour time to 12-hour format if specified, and appends localized
/// AM/PM or timezone indicators as configured.
fn format_time(
    time: citum_edtf::Time,
    format: &TimeFormat,
    show_seconds: bool,
    show_timezone: bool,
    am_term: Option<&str>,
    pm_term: Option<&str>,
    utc_term: Option<&str>,
) -> String {
    let (display_hour, period) = match format {
        TimeFormat::Hour12 => {
            let (h, p) = if time.hour == 0 {
                (12u32, am_term.unwrap_or("AM"))
            } else if time.hour < 12 {
                (time.hour, am_term.unwrap_or("AM"))
            } else if time.hour == 12 {
                (12u32, pm_term.unwrap_or("PM"))
            } else {
                (time.hour - 12, pm_term.unwrap_or("PM"))
            };
            (h, Some(p))
        }
        TimeFormat::Hour24 => (time.hour, None),
    };

    let time_str = if show_seconds {
        format!("{:02}:{:02}:{:02}", display_hour, time.minute, time.second)
    } else {
        format!("{:02}:{:02}", display_hour, time.minute)
    };

    let with_period = match period {
        Some(p) => format!("{time_str} {p}"),
        None => time_str,
    };

    if show_timezone {
        let tz_str = match time.timezone {
            Some(Timezone::Utc) => utc_term.unwrap_or("UTC").to_string(),
            Some(Timezone::Offset(mins)) => {
                let sign = if mins >= 0 { '+' } else { '-' };
                let abs = mins.unsigned_abs();
                format!("{}{:02}:{:02}", sign, abs / 60, abs % 60)
            }
            None => String::new(),
        };
        if tz_str.is_empty() {
            with_period
        } else {
            format!("{with_period} {tz_str}")
        }
    } else {
        with_period
    }
}

/// Format the start portion of a date range according to the given form.
fn format_range_start(
    date: &EdtfString,
    form: &DateForm,
    locale: &citum_schema::locale::Locale,
    date_config: Option<&citum_schema::options::dates::DateConfig>,
) -> String {
    let default_era = citum_schema::options::dates::EraLabels::Default;
    let default_neg_unspec = citum_schema::options::dates::NegativeUnspecifiedYears::default();
    let era_labels = date_config.map(|c| &c.era_labels).unwrap_or(&default_era);
    let neg_unspecified = date_config
        .map(|c| &c.negative_unspecified_years)
        .unwrap_or(&default_neg_unspec);
    let range_delimiter = date_config.map_or("", |c| c.range_delimiter.as_str());

    let extract_year = |d: &EdtfString| -> String {
        match d.parse() {
            RefDate::Edtf(edtf) => match edtf {
                Edtf::Date(date) => format_display_year(
                    &date.year,
                    &locale.dates,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                ),
                Edtf::Interval(interval) => format_display_year(
                    &interval.start.year,
                    &locale.dates,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                ),
                Edtf::IntervalFrom(date) | Edtf::IntervalTo(date) => format_display_year(
                    &date.year,
                    &locale.dates,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                ),
            },
            RefDate::Literal(_) => String::new(),
        }
    };

    match form {
        DateForm::Year => extract_year(date),
        DateForm::YearMonth => {
            let month = extract_month(date, &locale.dates.months.long);
            let year = extract_year(date);
            if month.is_empty() {
                year
            } else {
                format!("{month} {year}")
            }
        }
        DateForm::MonthDay => {
            let month = extract_month(date, &locale.dates.months.long);
            let day = date.day();
            match day {
                Some(d) => format!("{month} {d}"),
                None => month,
            }
        }
        DateForm::Full => {
            let year = extract_year(date);
            let month = extract_month(date, &locale.dates.months.long);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => year,
                (false, None) => format!("{month} {year}"),
                (false, Some(d)) => format!("{month} {d}, {year}"),
            }
        }
        DateForm::YearMonthDay => {
            let year = extract_year(date);
            let month = extract_month(date, &locale.dates.months.long);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => year,
                (false, None) => format!("{year}, {month}"),
                (false, Some(d)) => format!("{year}, {month} {d}"),
            }
        }
        DateForm::DayMonthAbbrYear => {
            let year = extract_year(date);
            let month = extract_month(date, &locale.dates.months.short);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => year,
                (false, None) => format!("{month} {year}"),
                (false, Some(d)) => format!("{d} {month} {year}"),
            }
        }
        DateForm::MonthAbbrDayYear => {
            let year = extract_year(date);
            let month = extract_month(date, &locale.dates.months.short);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => year,
                (false, None) => format!("{month} {year}"),
                (false, Some(d)) => format!("{month} {d}, {year}"),
            }
        }
        _ => extract_year(date),
    }
}

/// Format a date range with start date and delimiter.
fn format_date_range(
    start: String,
    date: &EdtfString,
    locale: &citum_schema::locale::Locale,
    date_config: Option<&citum_schema::options::dates::DateConfig>,
) -> Option<String> {
    let era_labels = date_config
        .map(|c| &c.era_labels)
        .unwrap_or(&citum_schema::options::dates::EraLabels::Default);
    let neg_unspecified = date_config
        .map(|c| &c.negative_unspecified_years)
        .unwrap_or(&citum_schema::options::dates::NegativeUnspecifiedYears::Range);
    let delimiter = date_config.map_or("", |c| c.range_delimiter.as_str());

    if date.is_open_range() {
        // Open-ended range (e.g., "1990/..")
        if let Some(end_marker) = date_config
            .and_then(|c| c.open_range_marker.as_deref())
            .or(locale.dates.open_ended_term.as_deref())
        {
            Some(format!("{start}{delimiter}{end_marker}"))
        } else {
            // No open-ended term available - return start date only
            Some(start)
        }
    } else if let Some(end) = extract_range_end(
        date,
        &locale.dates.months.long,
        &locale.dates,
        era_labels,
        neg_unspecified,
        delimiter,
    ) {
        // Closed range with end date
        Some(format!("{start}{delimiter}{end}"))
    } else {
        Some(start)
    }
}

/// Apply uncertainty and approximation markers to formatted date.
fn apply_date_markers(
    value: String,
    date: &EdtfString,
    date_config: Option<&citum_schema::options::dates::DateConfig>,
) -> String {
    let mut result = value;
    if date.is_approximate()
        && let Some(marker) = date_config.and_then(|c| c.approximation_marker.as_ref())
    {
        result = format!("{marker}{result}");
    }
    if date.is_uncertain()
        && let Some(marker) = date_config.and_then(|c| c.uncertainty_marker.as_ref())
    {
        result = format!("{result}{marker}");
    }
    result
}

/// Compute the disambiguation suffix for year-based citations.
fn compute_disamb_suffix<F: crate::render::format::OutputFormat<Output = String>>(
    date: &EdtfString,
    form: &DateForm,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    fmt: &F,
) -> Option<String> {
    if hints.disamb_condition && date_form_displays_year(form) && !date.year().is_empty() {
        // Check if year suffix is enabled. Fall back to AuthorDate default
        // (year_suffix: true) when processing is not explicitly set, matching
        // the behavior in disambiguation.rs which uses unwrap_or_default().
        let use_suffix = options
            .config
            .processing
            .as_ref()
            .unwrap_or(&citum_schema::options::Processing::AuthorDate)
            .config()
            .disambiguate
            .as_ref()
            .is_some_and(|d| d.year_suffix);

        if use_suffix {
            int_to_letter(hints.group_index as u32).map(|s| fmt.text(&s))
        } else {
            None
        }
    } else {
        None
    }
}

fn date_form_displays_year(form: &DateForm) -> bool {
    !matches!(form, DateForm::MonthDay)
}

fn inline_disamb_suffix(formatted: &str, form: &DateForm, year: &str, suffix: &str) -> String {
    if year.is_empty() || suffix.is_empty() {
        return formatted.to_string();
    }

    let year_index = match form {
        DateForm::Year | DateForm::YearMonthDay => formatted.find(year),
        DateForm::YearMonth
        | DateForm::Full
        | DateForm::DayMonthAbbrYear
        | DateForm::MonthAbbrDayYear => formatted.rfind(year),
        DateForm::MonthDay => None,
        _ => None,
    };

    let Some(index) = year_index else {
        return format!("{formatted}{suffix}");
    };

    let year_end = index + year.len();
    #[allow(clippy::string_slice, reason = "indices derived from find/rfind")]
    let result = format!(
        "{}{}{}{}",
        &formatted[..index],
        year,
        suffix,
        &formatted[year_end..]
    );
    result
}

/// Format a single date (non-range) according to the given form.
#[allow(
    clippy::too_many_lines,
    reason = "date formatting handles 6 form variants"
)]
fn format_single_date(
    date: &EdtfString,
    form: &DateForm,
    locale: &citum_schema::locale::Locale,
    date_config: Option<&citum_schema::options::dates::DateConfig>,
) -> Option<String> {
    let default_era = citum_schema::options::dates::EraLabels::Default;
    let default_neg_unspec = citum_schema::options::dates::NegativeUnspecifiedYears::default();
    let era_labels = date_config.map(|c| &c.era_labels).unwrap_or(&default_era);
    let neg_unspecified = date_config
        .map(|c| &c.negative_unspecified_years)
        .unwrap_or(&default_neg_unspec);
    let range_delimiter = date_config.map_or("", |c| c.range_delimiter.as_str());

    let extract_year = |d: &EdtfString| -> String {
        match d.parse() {
            RefDate::Edtf(edtf) => match edtf {
                Edtf::Date(dt) => format_display_year(
                    &dt.year,
                    &locale.dates,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                ),
                Edtf::Interval(interval) => format_display_year(
                    &interval.start.year,
                    &locale.dates,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                ),
                Edtf::IntervalFrom(dt) | Edtf::IntervalTo(dt) => format_display_year(
                    &dt.year,
                    &locale.dates,
                    era_labels,
                    neg_unspecified,
                    range_delimiter,
                ),
            },
            RefDate::Literal(_) => String::new(),
        }
    };

    match form {
        DateForm::Year => {
            let year = extract_year(date);
            if year.is_empty() { None } else { Some(year) }
        }
        DateForm::YearMonth => {
            let year = extract_year(date);
            if year.is_empty() {
                return None;
            }
            let month = extract_month(date, &locale.dates.months.long);
            if month.is_empty() {
                Some(year)
            } else {
                Some(format!("{month} {year}"))
            }
        }
        DateForm::MonthDay => {
            let month = extract_month(date, &locale.dates.months.long);
            if month.is_empty() {
                return None;
            }
            let day = date.day();
            if let Some(rendered) =
                locale.resolve_date_pattern("pattern.date-month-day", None, Some(&month), day)
            {
                return Some(rendered);
            }
            match day {
                Some(d) => Some(format!("{month} {d}")),
                None => Some(month),
            }
        }
        DateForm::Full => {
            let year = extract_year(date);
            if year.is_empty() {
                return None;
            }
            let month = extract_month(date, &locale.dates.months.long);
            let day = date.day();
            let base = locale
                .resolve_date_pattern(
                    "pattern.date-full",
                    Some(&year),
                    (!month.is_empty()).then_some(month.as_str()),
                    day,
                )
                .unwrap_or_else(|| match (month.is_empty(), day) {
                    (true, _) => year.clone(),
                    (false, None) => format!("{month} {year}"),
                    (false, Some(d)) => format!("{month} {d}, {year}"),
                });
            // Append time component if configured and present
            if let (Some(time_fmt), Some(time)) = (
                date_config.and_then(|c| c.time_format.as_ref()),
                date.time(),
            ) {
                let show_secs = date_config.is_some_and(|c| c.show_seconds);
                let show_tz = date_config.is_some_and(|c| c.show_timezone);
                let time_str = format_time(
                    time,
                    time_fmt,
                    show_secs,
                    show_tz,
                    locale.dates.am.as_deref(),
                    locale.dates.pm.as_deref(),
                    locale.dates.timezone_utc.as_deref(),
                );
                Some(format!("{base}, {time_str}"))
            } else {
                Some(base)
            }
        }
        DateForm::YearMonthDay => {
            let year = extract_year(date);
            if year.is_empty() {
                return None;
            }
            let month = extract_month(date, &locale.dates.months.long);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => Some(year),
                (false, None) => Some(format!("{year}, {month}")),
                (false, Some(d)) => Some(format!("{year}, {month} {d}")),
            }
        }
        DateForm::DayMonthAbbrYear => {
            let year = extract_year(date);
            if year.is_empty() {
                return None;
            }
            let month = extract_month(date, &locale.dates.months.short);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => Some(year),
                (false, None) => Some(format!("{month} {year}")),
                (false, Some(d)) => Some(format!("{d} {month} {year}")),
            }
        }
        DateForm::MonthAbbrDayYear => {
            let year = extract_year(date);
            if year.is_empty() {
                return None;
            }
            let month = extract_month(date, &locale.dates.months.short);
            let day = date.day();
            match (month.is_empty(), day) {
                (true, _) => Some(year),
                (false, None) => Some(format!("{month} {year}")),
                (false, Some(d)) => Some(format!("{month} {d}, {year}")),
            }
        }
        _ => Some(extract_year(date)),
    }
}

impl ComponentValues for TemplateDate {
    fn values<F: crate::render::format::OutputFormat<Output = String>>(
        &self,
        reference: &Reference,
        hints: &ProcHints,
        options: &RenderOptions<'_>,
    ) -> Option<ProcValues<F::Output>> {
        let fmt = F::default();
        let date_opt: Option<EdtfString> = match self.date {
            TemplateDateVar::Issued => reference.csl_issued_date(),
            TemplateDateVar::Accessed => reference.accessed(),
            TemplateDateVar::OriginalPublished => reference.original_date(),
            _ => None,
        };

        let Some(date) = date_opt.filter(|d| !d.0.is_empty()) else {
            // Handle fallback if date is missing
            if let Some(fallbacks) = &self.fallback {
                for component in fallbacks {
                    if let Some(values) = component.values::<F>(reference, hints, options) {
                        return Some(values);
                    }
                }
            }
            // For issued dates, substitute the locale's "no-date" term (e.g. "n.d.")
            if matches!(self.date, TemplateDateVar::Issued)
                && let Some(nd) = options.locale.resolved_general_term(
                    &GeneralTerm::NoDate,
                    &TermForm::Short,
                    None,
                )
            {
                return Some(ProcValues {
                    value: nd,
                    prefix: None,
                    suffix: None,
                    url: None,
                    substituted_key: None,
                    pre_formatted: false,
                });
            }
            return None;
        };

        let locale = options.locale;
        let date_config = options.config.dates.as_ref();
        let effective_form = self.form.clone();

        let formatted = if date.is_range() {
            // Handle date ranges
            let start = format_range_start(&date, &effective_form, locale, date_config);
            format_date_range(start, &date, locale, date_config)
        } else {
            // Single date (not a range)
            format_single_date(&date, &effective_form, locale, date_config)
        };

        // Apply uncertainty and approximation markers
        let formatted = formatted.map(|value| apply_date_markers(value, &date, date_config));

        // Handle disambiguation suffix (a, b, c...)
        let disamb_suffix = compute_disamb_suffix(&date, &effective_form, hints, options, &fmt);

        formatted.map(|value| {
            let (value, suffix) = if let Some(ref suffix) = disamb_suffix {
                (
                    inline_disamb_suffix(&value, &effective_form, &date.year(), suffix),
                    None,
                )
            } else {
                (value, None)
            };

            ProcValues {
                value,
                prefix: None,
                suffix,
                url: crate::values::resolve_effective_url(
                    self.links.as_ref(),
                    options.config.links.as_ref(),
                    reference,
                    citum_schema::options::LinkAnchor::Component,
                ),
                substituted_key: None,
                pre_formatted: false,
            }
        })
    }
}

/// Convert a 1-based index into an alphabetic suffix (`1 -> "a"`, `27 -> "aa"`).
#[must_use]
pub fn int_to_letter(n: u32) -> Option<String> {
    if n == 0 {
        return None;
    }

    let mut result = String::new();
    let mut num = n - 1;

    loop {
        result.push((b'a' + (num % 26) as u8) as char);
        if num < 26 {
            break;
        }
        num = num / 26 - 1;
    }

    Some(result.chars().rev().collect())
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod tests {
    use super::*;

    #[test]
    fn test_int_to_letter() {
        // Test basic single-letter conversions (1-26)
        assert_eq!(int_to_letter(1), Some("a".to_string()));
        assert_eq!(int_to_letter(2), Some("b".to_string()));
        assert_eq!(int_to_letter(26), Some("z".to_string()));

        // Test double-letter conversions (27+)
        assert_eq!(int_to_letter(27), Some("aa".to_string()));
        assert_eq!(int_to_letter(52), Some("az".to_string()));
        assert_eq!(int_to_letter(53), Some("ba".to_string()));

        // Test zero returns None
        assert_eq!(int_to_letter(0), None);
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod time_tests {
    use super::*;
    use citum_edtf::{Time, Timezone};

    #[test]
    fn test_format_time_12h_utc() {
        let time = Time {
            hour: 23,
            minute: 20,
            second: 30,
            timezone: Some(Timezone::Utc),
        };
        let result = format_time(
            time,
            &TimeFormat::Hour12,
            false,
            true,
            Some("AM"),
            Some("PM"),
            Some("UTC"),
        );
        assert_eq!(result, "11:20 PM UTC");
    }

    #[test]
    fn test_format_time_24h_utc() {
        let time = Time {
            hour: 23,
            minute: 20,
            second: 30,
            timezone: Some(Timezone::Utc),
        };
        let result = format_time(
            time,
            &TimeFormat::Hour24,
            false,
            true,
            None,
            None,
            Some("UTC"),
        );
        assert_eq!(result, "23:20 UTC");
    }

    #[test]
    fn test_format_time_with_offset() {
        let time = Time {
            hour: 10,
            minute: 10,
            second: 10,
            timezone: Some(Timezone::Offset(330)),
        };
        let result = format_time(
            time,
            &TimeFormat::Hour24,
            false,
            true,
            None,
            None,
            Some("UTC"),
        );
        assert_eq!(result, "10:10 +05:30");
    }

    #[test]
    fn test_format_time_no_timezone() {
        let time = Time {
            hour: 14,
            minute: 30,
            second: 0,
            timezone: None,
        };
        let result = format_time(time, &TimeFormat::Hour24, false, false, None, None, None);
        assert_eq!(result, "14:30");
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod era_tests {
    use super::*;
    use citum_edtf::{UnspecifiedYear, Year};
    use citum_schema::locale::DateTerms;
    use citum_schema::options::dates::{EraLabels, NegativeUnspecifiedYears};

    fn en_terms() -> DateTerms {
        DateTerms::en_us()
    }

    #[test]
    fn positive_year_default_no_suffix() {
        let year = Year {
            value: 54,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "54");
    }

    #[test]
    fn positive_year_bc_ad() {
        let year = Year {
            value: 54,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::BcAd,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "54 AD");
    }

    #[test]
    fn positive_year_bce_ce() {
        let year = Year {
            value: 54,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::BceCe,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "54 CE");
    }

    #[test]
    fn negative_year_default() {
        let year = Year {
            value: -43,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "44 BC");
    }

    #[test]
    fn negative_year_bc_ad() {
        let year = Year {
            value: -43,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::BcAd,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "44 BC");
    }

    #[test]
    fn negative_year_bce_ce() {
        let year = Year {
            value: -43,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::BceCe,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "44 BCE");
    }

    #[test]
    fn positive_unspecified_ones() {
        let year = Year {
            value: 1990,
            unspecified: UnspecifiedYear::One,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "199X");
    }

    #[test]
    fn positive_unspecified_two() {
        let year = Year {
            value: 1900,
            unspecified: UnspecifiedYear::Two,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "19XX");
    }

    #[test]
    fn negative_unspecified_range() {
        let year = Year {
            value: -90,
            unspecified: UnspecifiedYear::One,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "100–91 BC");
    }

    #[test]
    fn negative_unspecified_century() {
        let year = Year {
            value: 0,
            unspecified: UnspecifiedYear::Two,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "100–1 BC");
    }

    #[test]
    fn backwards_compat_negative_year() {
        let year = Year {
            value: -99,
            unspecified: UnspecifiedYear::None,
        };
        let result = format_display_year(
            &year,
            &en_terms(),
            &EraLabels::Default,
            &NegativeUnspecifiedYears::Range,
            "",
        );
        assert_eq!(result, "100 BC");
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "Panicking is acceptable in tests."
)]
mod locale_pattern_tests {
    use super::*;
    use citum_schema::locale::Locale;

    fn en_us() -> Locale {
        Locale::from_yaml_str(include_str!("../../../../locales/en-US.yaml"))
            .expect("en-US locale should parse")
    }

    fn es_es() -> Locale {
        Locale::from_yaml_str(include_str!("../../../../locales/es-ES.yaml"))
            .expect("es-ES locale should parse")
    }

    fn eu_es() -> Locale {
        Locale::from_yaml_str(include_str!("../../../../locales/eu-ES.yaml"))
            .expect("eu-ES locale should parse")
    }

    fn full(locale: &Locale, edtf: &str) -> String {
        format_single_date(&EdtfString(edtf.to_string()), &DateForm::Full, locale, None)
            .expect("date should render")
    }

    fn month_day(locale: &Locale, edtf: &str) -> String {
        format_single_date(
            &EdtfString(edtf.to_string()),
            &DateForm::MonthDay,
            locale,
            None,
        )
        .expect("date should render")
    }

    #[test]
    fn en_us_full_unchanged_by_pattern_machinery() {
        // Regression: en-US declares no pattern.date-*, so the engine's
        // hardcoded English assembly must still produce the original output.
        assert_eq!(full(&en_us(), "2023-01-12"), "January 12, 2023");
    }

    #[test]
    fn en_us_month_day_unchanged_by_pattern_machinery() {
        assert_eq!(month_day(&en_us(), "2023-01-12"), "January 12");
    }

    #[test]
    fn es_es_full_uses_locale_pattern() {
        // Spanish day-first assembly via pattern.date-full.
        assert_eq!(full(&es_es(), "2023-01-12"), "12 de enero de 2023");
    }

    #[test]
    fn es_es_month_day_uses_locale_pattern() {
        assert_eq!(month_day(&es_es(), "2023-01-12"), "12 de enero");
    }

    #[test]
    fn eu_es_full_uses_locale_pattern() {
        // Basque genitive-absolutive shape via pattern.date-full.
        // Content is PROVISIONAL — see locales/eu-ES.yaml header comment.
        assert_eq!(full(&eu_es(), "2023-01-12"), "2023ko urtarrilaren 12a");
    }

    #[test]
    fn eu_es_month_day_uses_locale_pattern() {
        assert_eq!(month_day(&eu_es(), "2023-01-12"), "urtarrilaren 12a");
    }

    #[test]
    fn pattern_missing_day_falls_back_to_english_assembly() {
        // Year-month only input: pattern.date-full requires {$day} so the
        // evaluator returns None, and the engine falls through to its
        // hardcoded `{month} {year}` assembly. (A future pattern.date-year-month
        // can fix this for inflected locales — out of scope for this bean.)
        assert_eq!(full(&es_es(), "2023-01"), "enero 2023");
    }
}