citum-engine 0.64.0

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

//! Document-level batch formatting API.

use crate::api::AnnotationStyle;
use crate::error::ProcessorError;
use crate::processor::Processor;
use crate::reference::{Bibliography, Citation};
use crate::render::djot::Djot;
use crate::render::format::OutputFormat;
use crate::render::html::Html;
use crate::render::latex::Latex;
use crate::render::markdown::Markdown;
use crate::render::plain::PlainText;
use crate::render::typst::Typst;
use citum_schema::Style;
use citum_schema::locale::{GeneralTerm, TermForm};
use citum_schema::reference::{
    ClassExtension, CollectionType, ContributorRole as ReferenceRole, MonographComponentType,
    MonographType, ReferenceClass, SerialComponentType,
};
use citum_schema::template::ContributorRole as TemplateRole;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::{
    BibliographyEntry, CitationOccurrence, DocumentOptions, EntryMetadata, FormattedBibliography,
    FormattedCitation, OutputFormatKind, RefsInput, StyleInput, Warning, WarningLevel,
};

/// A request to format a complete document's citations and bibliography.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatDocumentRequest {
    /// The style to use (may be resolved locally or by an adapter).
    pub style: StyleInput,
    /// Optional partial-style overlay (YAML or JSON) merged over the resolved base
    /// style for this request only.
    ///
    /// Accepts any subset of the style YAML schema — e.g. just `options.contributors`
    /// to change `and`/et-al behaviour, or a full citation spec. Uses the same
    /// null-aware, typed-merge semantics as `extends` inheritance: supplied fields
    /// win over base style fields; an explicit `~` (null) value clears an inherited
    /// field. The base style is never mutated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style_overrides: Option<String>,
    /// Optional locale override as a BCP 47 language tag (e.g. `en-US`).
    /// When omitted or set to en-US the engine uses its built-in en-US locale;
    /// other locales emit a warning and fall back to en-US until adapter-side
    /// locale resolution is wired through.
    pub locale: Option<String>,
    /// Output format (plain, html, djot, latex, typst). Defaults to plain
    /// when omitted from the request.
    #[serde(default)]
    pub output_format: OutputFormatKind,
    /// Reference input as a local path, inline YAML, inline JSON, or legacy bare map.
    pub refs: RefsInput,
    /// Ordered citations as they appear in the document.
    pub citations: Vec<CitationOccurrence>,
    /// Optional document-level configuration.
    pub document_options: Option<DocumentOptions>,
}

/// The result of formatting a document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatDocumentResult {
    /// Formatted citations in document order.
    pub formatted_citations: Vec<FormattedCitation>,
    /// Formatted bibliography.
    pub bibliography: FormattedBibliography,
    /// Non-fatal warnings encountered during processing.
    pub warnings: Vec<Warning>,
}

/// Errors that can occur during document formatting.
#[derive(Debug)]
pub enum FormatDocumentError {
    /// The style ID or URI requires a resolver chain not available in the engine.
    UnresolvedInput(String),
    /// Failed to parse the style YAML.
    StyleParse(String),
    /// Failed to read or locate the style file.
    StylePath(String),
    /// Failed to read a local refs input path.
    RefsInputPath(String),
    /// Failed to parse refs input data.
    RefsInputParse(String),
    /// The processor encountered an error during rendering.
    Processing(ProcessorError),
    /// Style inheritance (`extends`) could not be resolved.
    StyleResolution(String),
}

impl std::fmt::Display for FormatDocumentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnresolvedInput(msg) => write!(f, "Unresolved style input: {}", msg),
            Self::StyleParse(msg) => write!(f, "Style parse error: {}", msg),
            Self::StylePath(msg) => write!(f, "Style path error: {}", msg),
            Self::RefsInputPath(msg) => write!(f, "Refs input path error: {}", msg),
            Self::RefsInputParse(msg) => write!(f, "Refs input parse error: {}", msg),
            Self::Processing(err) => write!(f, "Processing error: {}", err),
            Self::StyleResolution(msg) => write!(f, "Style resolution error: {}", msg),
        }
    }
}

impl std::error::Error for FormatDocumentError {}

impl From<ProcessorError> for FormatDocumentError {
    fn from(err: ProcessorError) -> Self {
        Self::Processing(err)
    }
}

/// Parse a partial-style overlay (YAML or JSON) and merge it over `style` in place.
///
/// Called internally by `format_document_with_style`; also available to surface crates
/// (e.g. `citum-server`) that pre-resolve the style before handing it to the processor.
///
/// Uses the same null-aware, typed-merge semantics as `extends` inheritance.
/// Calls `apply_scoped_options` after the merge so that overlay fields that affect
/// scoped options (label_wrap, date_position, repeated_author_rendering, etc.) take
/// effect in the same way they do during normal style resolution.
///
/// # Errors
///
/// Returns `FormatDocumentError::StyleParse` if the overlay cannot be parsed.
pub fn apply_style_overrides(
    style: &mut Style,
    overlay_src: &str,
) -> Result<(), FormatDocumentError> {
    let overlay = Style::from_yaml_bytes(overlay_src.as_bytes()).map_err(|e| {
        FormatDocumentError::StyleParse(format!("Failed to parse style_overrides: {e}"))
    })?;
    style.apply_overlay(&overlay);
    style.apply_scoped_options();
    Ok(())
}

/// Format a complete document's citations and bibliography (convenience wrapper).
///
/// This function resolves the style locally using `StyleInput::resolve_local`.
/// For styles requiring a resolver chain (Id or Uri), use `format_document_with_style`
/// after pre-resolving.
///
/// # Errors
///
/// Returns an error if the style cannot be resolved, parsed, or if rendering fails.
pub fn format_document(
    request: FormatDocumentRequest,
) -> Result<FormatDocumentResult, FormatDocumentError> {
    let style = request.style.resolve_local()?;
    format_document_with_style(style, request)
}

/// Format a document, resolving the style through an injected resolver.
///
/// `Yaml` is parsed inline; `Id`, `Uri`, and `Path` are delegated to
/// `resolver.resolve_style`. This lets WASM/FFI callers supply their own
/// resolver chain without pre-resolving the style themselves.
///
/// # Errors
///
/// Returns an error if the resolver fails, the style cannot be parsed, or
/// if rendering fails.
pub fn format_document_with_resolver(
    request: FormatDocumentRequest,
    resolver: &citum_schema::StyleResolver,
) -> Result<FormatDocumentResult, FormatDocumentError> {
    let style = match &request.style {
        StyleInput::Yaml(_) => request.style.resolve_local()?,
        StyleInput::Id(value) | StyleInput::Uri(value) | StyleInput::Path(value) => resolver
            .resolve_style(value)
            .map_err(|e| FormatDocumentError::UnresolvedInput(e.to_string()))?,
    };
    // Fully resolve any `extends` chain via the injected resolver, then clear
    // `extends` so the processor's later `into_resolved()` call needs no
    // resolver. Mirrors `citum-server`'s `load_style`.
    let mut resolved = style
        .try_into_resolved_with(Some(resolver))
        .map_err(|e| FormatDocumentError::StyleResolution(e.to_string()))?;
    resolved.extends = None;
    format_document_with_style(resolved, request)
}

/// Format a document using an already-resolved style.
///
/// This is the primary entry point for adapters (citum-server, citum-bindings)
/// that have a resolver chain and can pre-resolve style IDs and URIs.
///
/// # Errors
///
/// Returns an error if rendering fails.
#[allow(
    clippy::too_many_lines,
    reason = "match arms grow one-to-one with format variants"
)]
pub fn format_document_with_style(
    style: Style,
    request: FormatDocumentRequest,
) -> Result<FormatDocumentResult, FormatDocumentError> {
    let mut warnings = Vec::new();

    // Apply per-request style overrides (merge over the resolved base style).
    let mut style = style;
    if let Some(src) = &request.style_overrides {
        apply_style_overrides(&mut style, src)?;
    }

    // Locale: the engine has no resolver chain for non-en-US locales.
    // Adapters with a citum_store dep can pre-resolve and call
    // Processor::with_locale directly; for now, emit a warning when a
    // non-en-US tag is requested and fall back to en-US.
    if let Some(tag) = &request.locale
        && !tag.is_empty()
        && !tag.eq_ignore_ascii_case("en-us")
    {
        warnings.push(Warning {
            level: WarningLevel::Warning,
            code: "locale_fallback".to_string(),
            citation_id: None,
            ref_id: None,
            message: format!(
                "Requested locale '{tag}' could not be loaded by the engine; falling back to en-US. Adapter-side locale resolution is not yet wired through."
            ),
        });
    }

    let bibliography = request.refs.resolve_local()?;
    let mut processor = Processor::new(style, bibliography);
    warnings.extend(unknown_reference_class_warnings(&processor.bibliography));
    warnings.extend(unknown_enum_warnings(&processor));

    if let Some(opts) = &request.document_options {
        // Rebuild the processor with the document-level integral-name override
        // before applying scalar field mutations (show_semantics etc.) so that
        // those mutations are not lost when the processor is reconstructed.
        if let Some(new_proc) = processor
            .processor_with_document_integral_name_override(opts.integral_name_memory.as_ref())
        {
            processor = new_proc;
        }
        if let Some(show_semantics) = opts.show_semantics {
            processor.show_semantics = show_semantics;
        }
        if let Some(inject_ast) = opts.inject_ast_indices {
            processor.set_inject_ast_indices(inject_ast);
        }
        if let Some(abbr_map) = opts.abbreviation_map.clone() {
            processor.abbreviation_map = Some(abbr_map);
        }
    }

    // Convert citations, recording missing-ref warnings and dropping items
    // whose reference IDs are absent from the bibliography. Citations with no
    // surviving items are kept as empty placeholders so the output preserves
    // input order and length.
    let mut citations: Vec<Citation> = Vec::new();
    for occ in request.citations {
        let mut citation: Citation = occ.into();
        citation.items.retain(|item| {
            if processor.bibliography.contains_key(&item.id) {
                true
            } else {
                warnings.push(Warning {
                    level: WarningLevel::Warning,
                    code: "missing_ref".to_string(),
                    citation_id: citation.id.clone(),
                    ref_id: Some(item.id.clone()),
                    message: format!("Reference '{}' not found in bibliography", item.id),
                });
                false
            }
        });
        citations.push(citation);
    }

    // Annotate integral-name First/Subsequent state from the processor's
    // effective config (no document structure available; all citations share
    // document scope). Safe no-op when no memory config is present.
    processor.annotate_flat_integral_name_states(&mut citations);

    // Process citations
    let formatted_citations = match request.output_format {
        OutputFormatKind::Plain => format_by_kind::<PlainText>(&processor, &citations)?,
        OutputFormatKind::Html => format_by_kind::<Html>(&processor, &citations)?,
        OutputFormatKind::Djot => format_by_kind::<Djot>(&processor, &citations)?,
        OutputFormatKind::Latex => format_by_kind::<Latex>(&processor, &citations)?,
        OutputFormatKind::Typst => format_by_kind::<Typst>(&processor, &citations)?,
        OutputFormatKind::Markdown => format_by_kind::<Markdown>(&processor, &citations)?,
    };

    // Process bibliography
    let bibliography = match request.output_format {
        OutputFormatKind::Plain => format_bibliography::<PlainText>(
            &processor,
            request.output_format,
            request.document_options.as_ref(),
        )?,
        OutputFormatKind::Html => format_bibliography::<Html>(
            &processor,
            request.output_format,
            request.document_options.as_ref(),
        )?,
        OutputFormatKind::Djot => format_bibliography::<Djot>(
            &processor,
            request.output_format,
            request.document_options.as_ref(),
        )?,
        OutputFormatKind::Latex => format_bibliography::<Latex>(
            &processor,
            request.output_format,
            request.document_options.as_ref(),
        )?,
        OutputFormatKind::Typst => format_bibliography::<Typst>(
            &processor,
            request.output_format,
            request.document_options.as_ref(),
        )?,
        OutputFormatKind::Markdown => format_bibliography::<Markdown>(
            &processor,
            request.output_format,
            request.document_options.as_ref(),
        )?,
    };

    Ok(FormatDocumentResult {
        formatted_citations,
        bibliography,
        warnings,
    })
}

/// Scan the bibliography for unknown reference classes and return compatibility warnings.
pub fn unknown_reference_class_warnings(bibliography: &Bibliography) -> Vec<Warning> {
    bibliography
        .iter()
        .filter_map(|(ref_id, reference)| {
            let ReferenceClass::Unknown(class) = reference.class() else {
                return None;
            };
            Some(Warning {
                level: WarningLevel::Warning,
                code: "unknown_reference_class".to_string(),
                citation_id: None,
                ref_id: Some(ref_id.clone()),
                message: format!(
                    "Reference '{ref_id}' uses unknown class '{class}'; rendering will use only fields this engine understands."
                ),
            })
        })
        .collect()
}

/// Scan the style and bibliography for unknown enum variants and term keys.
///
/// Returns a list of structured compatibility warnings for encounter of
/// unknown variants that were captured via the tolerant-enum mechanism.
pub fn unknown_enum_warnings(processor: &Processor) -> Vec<Warning> {
    let mut warnings = Vec::new();

    // 1. Scan bibliography
    for (ref_id, reference) in &processor.bibliography {
        match reference.extension() {
            ClassExtension::Monograph(r) => {
                if let MonographType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown monograph type '{s}'; rendering will use default monograph formatting."),
                    });
                }
            }
            ClassExtension::Collection(r) => {
                if let CollectionType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown collection type '{s}'; rendering will use default collection formatting."),
                    });
                }
            }
            ClassExtension::CollectionComponent(r) => {
                if let MonographComponentType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown monograph component type '{s}'; rendering will use default chapter formatting."),
                    });
                }
            }
            ClassExtension::SerialComponent(r) => {
                if let SerialComponentType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown serial component type '{s}'; rendering will use default article formatting."),
                    });
                }
            }
            _ => {}
        }

        for contributor in reference.all_contributor_entries() {
            if let ReferenceRole::Unknown(s) = &contributor.role {
                warnings.push(Warning {
                    level: WarningLevel::Warning,
                    code: "unknown_enum_variant".to_string(),
                    citation_id: None,
                    ref_id: Some(ref_id.clone()),
                    message: format!("Reference '{ref_id}' uses unknown contributor role '{s}'; this role may be ignored during rendering."),
                });
            }
        }
    }

    // 2. Scan Style
    if let Some(templates) = &processor.style.templates {
        for (name, template) in templates {
            scan_template_for_unknowns(template, &format!("template '{name}'"), &mut warnings);
        }
    }
    if let Some(citation) = &processor.style.citation
        && let Some(template) = &citation.template
    {
        scan_template_for_unknowns(template, "citation layout", &mut warnings);
    }
    if let Some(bib) = &processor.style.bibliography
        && let Some(template) = &bib.template
    {
        scan_template_for_unknowns(template, "bibliography layout", &mut warnings);
    }

    warnings
}

fn scan_template_for_unknowns(
    components: &[citum_schema::template::TemplateComponent],
    location: &str,
    warnings: &mut Vec<Warning>,
) {
    use citum_schema::template::TemplateComponent;
    for component in components {
        match component {
            TemplateComponent::Term(t) => {
                if let GeneralTerm::Unknown(s) = &t.term {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown locale term key '{s}'; this term may render as empty."),
                    });
                }
                if let Some(TermForm::Unknown(s)) = &t.form {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown term form '{s}'; falling back to long form."),
                    });
                }
            }
            TemplateComponent::Contributor(c) => {
                if let TemplateRole::Unknown(s) = &c.contributor {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown contributor role '{s}'; this role may be ignored."),
                    });
                }
            }
            TemplateComponent::Date(d) => {
                if let citum_schema::template::DateForm::Unknown(s) = &d.form {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown date form '{s}'; falling back to year only."),
                    });
                }
            }
            TemplateComponent::Group(g) => {
                scan_template_for_unknowns(&g.group, location, warnings);
            }
            _ => {}
        }
    }
}

/// Process citations and return formatted text.
pub(crate) fn format_by_kind<F>(
    processor: &Processor,
    citations: &[Citation],
) -> Result<Vec<FormattedCitation>, FormatDocumentError>
where
    F: OutputFormat<Output = String>,
{
    let texts = processor.process_citations_with_format::<F>(citations)?;

    let formatted = citations
        .iter()
        .zip(texts.iter())
        .map(|(citation, text)| {
            let ref_ids = citation.items.iter().map(|item| item.id.clone()).collect();
            FormattedCitation {
                id: citation.id.clone().unwrap_or_default(),
                text: text.clone(),
                ref_ids,
            }
        })
        .collect();

    Ok(formatted)
}

/// Format the bibliography by output kind.
pub(crate) fn format_bibliography<F>(
    processor: &Processor,
    format_kind: OutputFormatKind,
    doc_opts: Option<&DocumentOptions>,
) -> Result<FormattedBibliography, FormatDocumentError>
where
    F: OutputFormat<Output = String>,
{
    // Extract annotation map and style if present
    let (annotations, annotation_style) = if let Some(opts) = doc_opts {
        if let Some(anns) = &opts.annotations {
            let style = opts.annotation_format.as_ref().map(|fmt| AnnotationStyle {
                format: fmt.clone(),
            });
            (anns.clone(), style)
        } else {
            (HashMap::new(), None)
        }
    } else {
        (HashMap::new(), None)
    };

    // Render bibliography as string
    let content = if annotations.is_empty() {
        processor
            .render_bibliography_with_format_and_annotations::<F>(None, annotation_style.as_ref())
    } else {
        processor.render_bibliography_with_format_and_annotations::<F>(
            Some(&annotations),
            annotation_style.as_ref(),
        )
    };

    // Extract per-entry text in the requested output format and capture metadata.
    let proc_entries = processor.process_references_with_format::<F>().bibliography;
    let entries = proc_entries
        .into_iter()
        .map(|entry| {
            let entry_anns = if annotations.is_empty() {
                None
            } else {
                Some(&annotations)
            };
            let text = crate::render::bibliography::refs_to_string_with_format::<F>(
                vec![entry.clone()],
                entry_anns,
                annotation_style.as_ref(),
            );
            let metadata = EntryMetadata {
                author: entry.metadata.author.unwrap_or_default(),
                year: entry.metadata.year.unwrap_or_default(),
                title: entry.metadata.title.unwrap_or_default(),
            };
            BibliographyEntry {
                id: entry.id,
                text,
                metadata,
            }
        })
        .collect();

    Ok(FormattedBibliography {
        format: format_kind,
        content,
        entries,
    })
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    reason = "test code uses assertions and panic"
)]
mod tests {
    use super::*;
    use crate::api::CitationOccurrenceItem;
    use crate::{
        Config, ContributorForm, ContributorRole, DateForm, Processing, Rendering,
        TemplateComponent, TemplateContributor, TemplateDate, TemplateDateVariable,
        WrapPunctuation,
    };
    use citum_schema::options::{AndOptions, ContributorConfig};
    use citum_schema::reference::{EdtfString, InputReference, Monograph, MonographType, Title};
    use citum_schema::template::{TemplateTitle, TitleType};
    use citum_schema::{BibliographySpec, CitationSpec, StyleInfo};

    fn make_test_style() -> Style {
        Style {
            info: StyleInfo {
                title: Some("Test Style".to_string()),
                id: Some("test".into()),
                ..Default::default()
            },
            options: Some(Config {
                processing: Some(Processing::AuthorDate),
                ..Default::default()
            }),
            citation: Some(CitationSpec {
                template: Some(vec![
                    TemplateComponent::Contributor(TemplateContributor {
                        contributor: ContributorRole::Author,
                        form: ContributorForm::Short,
                        rendering: Rendering::default(),
                        ..Default::default()
                    }),
                    TemplateComponent::Date(TemplateDate {
                        date: TemplateDateVariable::Issued,
                        form: DateForm::Year,
                        rendering: Rendering::default(),
                        ..Default::default()
                    }),
                ]),
                wrap: Some(WrapPunctuation::Parentheses.into()),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    fn make_test_bibliography() -> RefsInput {
        let mut refs = Bibliography::new();
        refs.insert(
            "smith2020".to_string(),
            InputReference::Monograph(Box::new(Monograph {
                id: Some("smith2020".into()),
                r#type: MonographType::Book,
                title: Some(Title::Single("Sample Work".to_string())),
                issued: EdtfString("2020".to_string()),
                ..Default::default()
            })),
        );
        RefsInput::Json(serde_json::to_value(refs).unwrap())
    }

    fn make_markup_bibliography() -> RefsInput {
        let mut refs = Bibliography::new();
        refs.insert(
            "art1".to_string(),
            InputReference::Monograph(Box::new(Monograph {
                id: Some("art1".into()),
                r#type: MonographType::Book,
                title: Some(Title::Single(
                    "_Homo sapiens_ and *modern* world".to_string(),
                )),
                issued: EdtfString("2023".to_string()),
                ..Default::default()
            })),
        );
        RefsInput::Json(serde_json::to_value(refs).unwrap())
    }

    #[test]
    fn format_document_with_style_empty_citations() {
        let style = make_test_style();
        let refs = make_test_bibliography();
        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![],
            document_options: None,
        };

        let result = format_document_with_style(style, request);
        assert!(result.is_ok());
        let res = result.unwrap();
        assert_eq!(res.formatted_citations.len(), 0);
    }

    #[test]
    fn format_document_html_bibliography_entries_preserve_inline_markup() {
        let mut style = make_test_style();
        style.bibliography = Some(BibliographySpec {
            template: Some(vec![TemplateComponent::Title(TemplateTitle {
                title: TitleType::Primary,
                ..Default::default()
            })]),
            ..Default::default()
        });

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Html,
            refs: make_markup_bibliography(),
            citations: vec![],
            document_options: None,
        };

        let result = format_document_with_style(style, request).expect("should render");

        assert_eq!(
            result.bibliography.entries[0].text, result.bibliography.content,
            "single-entry bibliography should mirror the full bibliography payload"
        );
        assert!(
            result.bibliography.entries[0].text.contains(
                "<span class=\"citum-title\"><em>Homo sapiens</em> and <b>modern</b> world</span>"
            ),
            "per-entry HTML should preserve inline markup for Djot-bearing titles"
        );
    }

    #[test]
    fn format_document_missing_ref_warning() {
        let style = make_test_style();
        let refs = make_test_bibliography();

        let citation_occ = CitationOccurrence {
            id: "cite1".to_string(),
            items: vec![CitationOccurrenceItem {
                id: "unknown_ref".to_string(),
                locator: None,
                prefix: None,
                suffix: None,
                integral_name_state: None,
                org_abbreviation_state: None,
            }],
            mode: None,
            note_number: None,
            suppress_author: None,
            grouped: None,
            prefix: None,
            suffix: None,
            sentence_start: None,
        };

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![citation_occ],
            document_options: None,
        };

        let result = format_document_with_style(style, request);
        assert!(result.is_ok());
        let res = result.unwrap();
        assert!(res.warnings.iter().any(|w| w.code == "missing_ref"));
    }

    #[test]
    fn format_document_unknown_reference_class_warning() {
        let style = make_test_style();
        let mut refs = Bibliography::new();
        let unknown_ref: InputReference = serde_json::from_str(
            r#"{
                "class": "dance-performance",
                "id": "pina2011",
                "title": "Pina",
                "issued": "2011",
                "venue": "Berlin"
            }"#,
        )
        .expect("unknown class should parse through the compatibility path");
        refs.insert("pina2011".to_string(), unknown_ref);

        let citation_occ = CitationOccurrence {
            id: "cite1".to_string(),
            items: vec![CitationOccurrenceItem {
                id: "pina2011".to_string(),
                locator: None,
                prefix: None,
                suffix: None,
                integral_name_state: None,
                org_abbreviation_state: None,
            }],
            mode: None,
            note_number: None,
            suppress_author: None,
            grouped: None,
            prefix: None,
            suffix: None,
            sentence_start: None,
        };

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs: RefsInput::Json(serde_json::to_value(refs).unwrap()),
            citations: vec![citation_occ],
            document_options: None,
        };

        let result = format_document_with_style(style, request).unwrap();
        let warning = result
            .warnings
            .iter()
            .find(|w| w.code == "unknown_reference_class")
            .expect("unknown class warning should be emitted");
        assert_eq!(warning.ref_id.as_deref(), Some("pina2011"));
        assert!(warning.message.contains("dance-performance"));
    }

    #[test]
    fn format_document_yaml_style_input() {
        let style = make_test_style();
        let yaml_style = serde_yaml::to_string(&style).expect("serialize test style");

        let mut refs = Bibliography::new();
        refs.insert(
            "test2024".to_string(),
            InputReference::Monograph(Box::new(Monograph {
                id: Some("test2024".into()),
                r#type: MonographType::Book,
                title: Some(Title::Single("Test Work".to_string())),
                issued: EdtfString("2024".to_string()),
                ..Default::default()
            })),
        );

        let citation_occ = CitationOccurrence {
            id: "c1".to_string(),
            items: vec![CitationOccurrenceItem {
                id: "test2024".to_string(),
                locator: None,
                prefix: None,
                suffix: None,
                integral_name_state: None,
                org_abbreviation_state: None,
            }],
            mode: None,
            note_number: None,
            suppress_author: None,
            grouped: None,
            prefix: None,
            suffix: None,
            sentence_start: None,
        };

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml(yaml_style),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs: RefsInput::Json(serde_json::to_value(refs).unwrap()),
            citations: vec![citation_occ],
            document_options: None,
        };

        let result = format_document(request);
        assert!(result.is_ok());
        let res = result.unwrap();
        assert_eq!(res.formatted_citations.len(), 1);
        assert!(!res.formatted_citations[0].text.is_empty());
    }

    #[test]
    fn format_document_uri_input_unresolved() {
        let request = FormatDocumentRequest {
            style: StyleInput::Uri("https://example.com/style.yaml".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs: RefsInput::Json(serde_json::Value::Object(Default::default())),
            citations: vec![],
            document_options: None,
        };

        let result = format_document(request);
        match result {
            Err(FormatDocumentError::UnresolvedInput(_)) => {
                // Expected
            }
            _ => panic!("Expected UnresolvedInput error"),
        }
    }

    /// A minimal resolver that returns a fixed style for any ID.
    struct MockResolver(Style);

    impl citum_resolver_api::StyleResolver for MockResolver {
        type Style = Style;
        type Locale = citum_schema::locale::Locale;

        fn resolve_style(&self, _uri: &str) -> Result<Style, citum_schema::ResolverError> {
            Ok(self.0.clone())
        }

        fn resolve_locale(
            &self,
            id: &str,
        ) -> Result<citum_schema::locale::Locale, citum_schema::ResolverError> {
            Err(citum_schema::ResolverError::LocaleNotFound(
                std::borrow::Cow::Owned(id.to_string()),
            ))
        }
    }

    #[test]
    fn format_document_with_resolver_injects_style_for_id_input() {
        let style = make_test_style();
        let resolver = MockResolver(style);
        let refs = make_test_bibliography();

        let citation_occ = CitationOccurrence {
            id: "c1".to_string(),
            items: vec![CitationOccurrenceItem {
                id: "smith2020".to_string(),
                locator: None,
                prefix: None,
                suffix: None,
                integral_name_state: None,
                org_abbreviation_state: None,
            }],
            mode: None,
            note_number: None,
            suppress_author: None,
            grouped: None,
            prefix: None,
            suffix: None,
            sentence_start: None,
        };

        let request = FormatDocumentRequest {
            style: StyleInput::Id("any-id".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![citation_occ],
            document_options: None,
        };

        // Without a resolver, the same Id input must be rejected.
        match format_document(request.clone()) {
            Err(FormatDocumentError::UnresolvedInput(_)) => {}
            other => panic!("expected UnresolvedInput without resolver, got: {other:?}"),
        }

        // With the injected resolver it must succeed.
        let result = format_document_with_resolver(request, &resolver);
        assert!(result.is_ok(), "expected Ok, got: {:?}", result.err());
        let res = result.unwrap();
        assert_eq!(res.formatted_citations.len(), 1);
        assert!(
            !res.formatted_citations[0].text.is_empty(),
            "formatted citation text should not be empty"
        );
    }

    /// Build an author-date style whose citation template renders contributor short form.
    fn make_two_author_style() -> Style {
        Style {
            info: StyleInfo {
                title: Some("Override Test Style".to_string()),
                id: Some("override-test".into()),
                ..Default::default()
            },
            options: Some(Config {
                processing: Some(Processing::AuthorDate),
                // Explicitly set `and: text` so the override to `symbol` is observable
                // in rendered output without relying on any default connector.
                contributors: Some(ContributorConfig {
                    and: Some(AndOptions::Text),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            citation: Some(CitationSpec {
                template: Some(vec![
                    TemplateComponent::Contributor(TemplateContributor {
                        contributor: ContributorRole::Author,
                        form: ContributorForm::Short,
                        rendering: Rendering::default(),
                        ..Default::default()
                    }),
                    TemplateComponent::Date(TemplateDate {
                        date: TemplateDateVariable::Issued,
                        form: DateForm::Year,
                        rendering: Rendering {
                            prefix: Some(", ".to_string()),
                            ..Default::default()
                        },
                        ..Default::default()
                    }),
                ]),
                wrap: Some(WrapPunctuation::Parentheses.into()),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    /// Build a refs input with a two-author book so the "and" connector is exercised.
    ///
    /// Uses inline YAML (the reliably tested deserialization path) rather than
    /// round-tripping through `serde_json::to_value` which may not preserve the
    /// contributor tagged-enum layout the engine expects.
    fn make_two_author_refs() -> RefsInput {
        RefsInput::Yaml(
            r#"duo2024:
  class: monograph
  id: duo2024
  type: book
  title: Duo Work
  issued: "2024"
  author:
    - family: Smith
      given: Alice
    - family: Jones
      given: Bob
"#
            .to_string(),
        )
    }

    /// Helper: produce a single-item citation occurrence for a given ref id.
    fn cite(ref_id: &str) -> CitationOccurrence {
        CitationOccurrence {
            id: "c1".to_string(),
            items: vec![CitationOccurrenceItem {
                id: ref_id.to_string(),
                locator: None,
                prefix: None,
                suffix: None,
                integral_name_state: None,
                org_abbreviation_state: None,
            }],
            mode: None,
            note_number: None,
            suppress_author: None,
            grouped: None,
            prefix: None,
            suffix: None,
            sentence_start: None,
        }
    }

    #[test]
    fn style_overrides_and_symbol_changes_rendered_output() {
        let base_style = make_two_author_style();
        let refs = make_two_author_refs();

        // given: base style produces a citation containing "and"
        let request_base = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs: refs.clone(),
            citations: vec![cite("duo2024")],
            document_options: None,
        };
        let result_base = format_document_with_style(base_style.clone(), request_base).unwrap();
        let text_base = &result_base.formatted_citations[0].text;
        assert!(
            text_base.contains("and"),
            "base style should use text 'and' connector, got: {text_base:?}"
        );

        // when: style_overrides switches connector to symbol "&"
        let request_override = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: Some("options:\n  contributors:\n    and: symbol\n".to_string()),
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![cite("duo2024")],
            document_options: None,
        };
        let result_override =
            format_document_with_style(base_style.clone(), request_override).unwrap();
        let text_override = &result_override.formatted_citations[0].text;
        assert!(
            text_override.contains('&'),
            "overridden style should use '&' connector, got: {text_override:?}"
        );

        // then: base style struct is untouched — still has Text, not Symbol
        let base_and = base_style
            .options
            .as_ref()
            .and_then(|o| o.contributors.as_ref())
            .and_then(|c| c.and.as_ref());
        assert!(
            matches!(base_and, Some(&AndOptions::Text)),
            "base style must not be mutated; expected And::Text, got: {base_and:?}"
        );
    }

    #[test]
    fn style_overrides_invalid_yaml_returns_parse_error() {
        let style = make_test_style();
        let refs = make_test_bibliography();

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: Some("{ unclosed yaml: [".to_string()),
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![],
            document_options: None,
        };

        match format_document_with_style(style, request) {
            Err(FormatDocumentError::StyleParse(msg)) => {
                assert!(
                    msg.contains("style_overrides"),
                    "error message should mention style_overrides, got: {msg}"
                );
            }
            other => panic!("expected StyleParse error, got: {other:?}"),
        }
    }

    #[test]
    fn apply_style_overrides_merges_option_field() {
        let mut style = make_test_style();
        apply_style_overrides(&mut style, "options:\n  contributors:\n    and: symbol\n")
            .expect("apply_style_overrides should succeed");

        let and_option = style
            .options
            .as_ref()
            .and_then(|o| o.contributors.as_ref())
            .and_then(|c| c.and.as_ref());
        assert!(
            matches!(and_option, Some(&AndOptions::Symbol)),
            "expected And::Symbol after override, got: {and_option:?}"
        );
    }

    // --- integral_name_memory wiring ---

    /// Build a style that has integral-name memory configured with scope=Document,
    /// contexts=BodyAndNotes, subsequent_form=Short, and an integral sub-template
    /// that renders the author in Long (given + family) form.
    fn make_integral_name_style() -> Style {
        use citum_schema::options::{
            IntegralNameContexts, IntegralNameMemoryConfig, IntegralNameScope, SubsequentNameForm,
        };
        Style {
            info: StyleInfo {
                title: Some("Integral Name Memory Test".to_string()),
                id: Some("integral-name-memory-test".into()),
                ..Default::default()
            },
            options: Some(Config {
                processing: Some(Processing::AuthorDate),
                integral_name_memory: Some(IntegralNameMemoryConfig {
                    scope: Some(IntegralNameScope::Document),
                    contexts: Some(IntegralNameContexts::BodyAndNotes),
                    subsequent_form: Some(SubsequentNameForm::Short),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            citation: Some(CitationSpec {
                integral: Some(Box::new(CitationSpec {
                    template: Some(vec![TemplateComponent::Contributor(TemplateContributor {
                        contributor: ContributorRole::Author,
                        form: ContributorForm::Long,
                        rendering: Rendering::default(),
                        ..Default::default()
                    })]),
                    ..Default::default()
                })),
                template: Some(vec![
                    TemplateComponent::Contributor(TemplateContributor {
                        contributor: ContributorRole::Author,
                        form: ContributorForm::Short,
                        rendering: Rendering::default(),
                        ..Default::default()
                    }),
                    TemplateComponent::Date(TemplateDate {
                        date: TemplateDateVariable::Issued,
                        form: DateForm::Year,
                        rendering: Rendering::default(),
                        ..Default::default()
                    }),
                ]),
                wrap: Some(WrapPunctuation::Parentheses.into()),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    fn make_smith_refs() -> RefsInput {
        RefsInput::Yaml(
            r#"smith2020:
  class: monograph
  id: smith2020
  type: book
  title: Smith Book
  issued: "2020"
  author:
    - family: Smith
      given: John
"#
            .to_string(),
        )
    }

    fn make_integral_occ(id: &str, ref_id: &str) -> CitationOccurrence {
        CitationOccurrence {
            id: id.to_string(),
            items: vec![CitationOccurrenceItem {
                id: ref_id.to_string(),
                locator: None,
                prefix: None,
                suffix: None,
                integral_name_state: None,
                org_abbreviation_state: None,
            }],
            mode: Some(citum_schema::data::citation::CitationMode::Integral),
            note_number: None,
            suppress_author: None,
            grouped: None,
            prefix: None,
            suffix: None,
            sentence_start: None,
        }
    }

    #[test]
    fn document_options_integral_name_memory_first_full_then_short() {
        use crate::processor::document::DocumentIntegralNameOverride;

        let style = make_integral_name_style();
        let refs = make_smith_refs();

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![
                make_integral_occ("c1", "smith2020"),
                make_integral_occ("c2", "smith2020"),
            ],
            document_options: Some(DocumentOptions {
                integral_name_memory: Some(DocumentIntegralNameOverride {
                    enabled: Some(true),
                    ..Default::default()
                }),
                ..Default::default()
            }),
        };

        let result = format_document_with_style(style, request).expect("should render");

        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.code == "integral_name_memory_not_applied"),
            "stale warning must not appear: {:?}",
            result.warnings
        );
        assert_eq!(
            result.formatted_citations[0].text, "John Smith",
            "first integral cite should render full name form"
        );
        assert_eq!(
            result.formatted_citations[1].text, "Smith",
            "second integral cite of same author should render short form"
        );
    }

    #[test]
    fn document_options_integral_name_memory_disabled_keeps_full_form() {
        use crate::processor::document::DocumentIntegralNameOverride;

        let style = make_integral_name_style();
        let refs = make_smith_refs();

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![
                make_integral_occ("c1", "smith2020"),
                make_integral_occ("c2", "smith2020"),
            ],
            document_options: Some(DocumentOptions {
                integral_name_memory: Some(DocumentIntegralNameOverride {
                    enabled: Some(false),
                    ..Default::default()
                }),
                ..Default::default()
            }),
        };

        let result = format_document_with_style(style, request).expect("should render");

        // With memory disabled both occurrences should render the natural integral
        // template form (Long = "John Smith") without any subsequent rewrite.
        assert_eq!(
            result.formatted_citations[0].text, "John Smith",
            "first integral cite: {}",
            result.formatted_citations[0].text
        );
        assert_eq!(
            result.formatted_citations[1].text, "John Smith",
            "second integral cite should also be full when memory is disabled"
        );
    }

    #[test]
    fn style_native_integral_name_memory_applied_without_document_override() {
        // Style has integral_name_memory in its own options; no document_options
        // override is supplied. The flat API must still annotate First/Subsequent.
        let style = make_integral_name_style();
        let refs = make_smith_refs();

        let request = FormatDocumentRequest {
            style: StyleInput::Yaml("dummy".to_string()),
            style_overrides: None,
            locale: None,
            output_format: OutputFormatKind::Plain,
            refs,
            citations: vec![
                make_integral_occ("c1", "smith2020"),
                make_integral_occ("c2", "smith2020"),
            ],
            document_options: None,
        };

        let result = format_document_with_style(style, request).expect("should render");

        assert_eq!(
            result.formatted_citations[0].text, "John Smith",
            "first integral cite should render full name form"
        );
        assert_eq!(
            result.formatted_citations[1].text, "Smith",
            "second integral cite should render short form from style-native config"
        );
    }
}