citum 0.68.0

Citum CLI: render, check, convert, and manage citation styles, references, and documents
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
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

//! `render` subcommands: render a document (`render doc`) or render references
//! and citations directly from data files (`render refs`).

mod human;
mod json;

use super::CliResult;
use crate::args::{
    InputFormat, OutputFormat, RenderCommands, RenderDocArgs, RenderMode, RenderRefsArgs,
};
use crate::output::write_output;
use crate::style_resolver::{create_processor, load_any_style};
use crate::typst_pdf;
use citum_engine::processor::document::{djot::DjotParser, markdown::MarkdownParser};
use citum_engine::render::{
    djot::Djot, html::Html, latex::Latex, markdown::Markdown, plain::PlainText, typst::Typst,
};
use citum_engine::{BibliographyBlockRequest, Citation, DocumentFormat, Processor};
use citum_io::{
    AnnotationFormat, AnnotationStyle, load_annotations, load_merged_bibliography,
    load_merged_citations,
};
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::Path;

pub(super) fn dispatch(command: RenderCommands) -> CliResult {
    match command {
        RenderCommands::Doc(args) => run_render_doc(args),
        RenderCommands::Refs(args) => run_render_refs(args),
    }
}

/// Execute the `render doc` subcommand.
///
/// Reads a document, resolves citations against the provided bibliography,
/// and writes the rendered output to stdout or a file.
pub(super) fn run_render_doc(args: RenderDocArgs) -> CliResult {
    if args.pdf && args.format != OutputFormat::Typst {
        return Err("`--pdf` is only supported with `--format typst`.".into());
    }

    let style_obj = load_any_style(&args.style, args.no_semantics)?;
    let bibliography = load_merged_bibliography(&args.bibliography)?;

    if !args.citations.is_empty() {
        eprintln!(
            "Warning: --citations is currently ignored by `render doc`; citations are parsed from the input document."
        );
    }

    // Read document first so we can extract frontmatter locale for processor setup.
    let doc_content = fs::read_to_string(&args.input)?;

    // CLI --locale takes precedence over frontmatter options.locale.
    // Avoid cloning args.locale: only call extract_frontmatter_locale when needed.
    let fm_locale = args
        .locale
        .is_none()
        .then(|| extract_frontmatter_locale(&doc_content))
        .flatten();
    let effective_locale = args.locale.as_deref().or(fm_locale.as_deref());

    let processor = create_processor(
        style_obj,
        bibliography,
        &args.style,
        args.no_semantics,
        effective_locale,
    )?;

    let output = if let Some(blocks_path) = args.bibliography_blocks {
        let json = fs::read_to_string(&blocks_path).map_err(|e| {
            format!(
                "cannot read --bibliography-blocks file '{}': {e}",
                blocks_path.display()
            )
        })?;
        let requests: Vec<BibliographyBlockRequest> = serde_json::from_str(&json).map_err(|e| {
            format!(
                "invalid --bibliography-blocks JSON in '{}': {e}",
                blocks_path.display()
            )
        })?;
        let groups: Vec<_> = requests.into_iter().map(|r| r.group).collect();
        match args.input_format {
            InputFormat::Djot => render_doc_with_caller_blocks(
                &processor,
                &doc_content,
                args.format,
                DocumentInput::Djot,
                &groups,
            )?,
            InputFormat::Markdown => render_doc_with_caller_blocks(
                &processor,
                &doc_content,
                args.format,
                DocumentInput::Markdown,
                &groups,
            )?,
        }
    } else {
        match args.input_format {
            InputFormat::Djot => render_doc_with_output_format(
                &processor,
                &doc_content,
                args.format,
                DocumentInput::Djot,
            )?,
            InputFormat::Markdown => render_doc_with_output_format(
                &processor,
                &doc_content,
                args.format,
                DocumentInput::Markdown,
            )?,
        }
    };

    if args.pdf {
        let output_path = args
            .output
            .as_ref()
            .ok_or("`--pdf` requires `--output <file.pdf>`.")?;
        typst_pdf::compile_document_to_pdf(&output, output_path, args.typst_keep_source)?;
        return Ok(());
    }

    write_output(&output, args.output.as_ref())
}

/// Execute the `render refs` subcommand.
///
/// Renders bibliography entries and/or citations directly from data files
/// without requiring a full document.
pub(super) fn run_render_refs(args: RenderRefsArgs) -> CliResult {
    let style_obj = load_any_style(&args.style, args.no_semantics)?;
    let bibliography = load_merged_bibliography(&args.bibliography)?;

    // Forward-compat: surface fields the engine silently captured (and will
    // ignore) so data typos are visible at authoring time.
    for warning in citum_engine::api::unknown_reference_field_warnings(&bibliography.references) {
        eprintln!("Warning: {}", warning.message);
    }

    let item_ids = if let Some(k) = args.keys.clone() {
        k
    } else {
        bibliography.references.keys().cloned().collect()
    };

    let input_citations = if args.citations.is_empty() {
        None
    } else {
        Some(load_merged_citations(&args.citations)?)
    };

    let annotations = if let Some(path) = &args.annotations {
        Some(load_annotations(path)?)
    } else {
        None
    };

    let annotation_style = AnnotationStyle {
        format: AnnotationFormat::Djot,
    };

    let processor = create_processor(
        style_obj,
        bibliography,
        &args.style,
        args.no_semantics,
        args.locale.as_deref(),
    )?;

    let style_name = {
        let path = Path::new(&args.style);
        if path.exists() {
            path.file_name().map_or_else(
                || "unknown".to_string(),
                |s: &std::ffi::OsStr| s.to_string_lossy().to_string(),
            )
        } else {
            args.style.clone()
        }
    };

    let render_ctx = RenderContext {
        processor: &processor,
        style_name: &style_name,
        item_ids: &item_ids,
        annotations: annotations.as_ref(),
        annotation_style: &annotation_style,
    };
    let output = if args.json {
        render_refs_json(&render_ctx, args.mode, input_citations, args.format)?
    } else {
        render_refs_human(
            &render_ctx,
            args.mode,
            input_citations,
            args.show_keys,
            args.format,
        )?
    };

    write_output(&output, args.output.as_ref())
}

enum DocumentInput {
    Djot,
    Markdown,
}

/// Render a full document through the processor using the given output format.
///
/// Dispatches to the monomorphised `process_document` call matching `output_format`.
fn render_doc_with_output_format(
    processor: &Processor,
    content: &str,
    output_format: OutputFormat,
    input_format: DocumentInput,
) -> Result<String, Box<dyn Error>> {
    let doc_format = to_document_format(output_format)?;

    match input_format {
        DocumentInput::Djot => {
            let parser = DjotParser;
            match output_format {
                OutputFormat::Plain => {
                    Ok(processor.process_document::<_, PlainText>(content, &parser, doc_format))
                }
                OutputFormat::Html => {
                    Ok(processor.process_document::<_, Html>(content, &parser, doc_format))
                }
                OutputFormat::Djot => {
                    Ok(processor.process_document::<_, Djot>(content, &parser, doc_format))
                }
                OutputFormat::Markdown => {
                    Ok(processor.process_document::<_, Markdown>(content, &parser, doc_format))
                }
                OutputFormat::Latex => {
                    Ok(processor.process_document::<_, Latex>(content, &parser, doc_format))
                }
                OutputFormat::Typst => {
                    Ok(processor.process_document::<_, Typst>(content, &parser, doc_format))
                }
            }
        }
        DocumentInput::Markdown => {
            let parser = MarkdownParser;
            match output_format {
                OutputFormat::Plain => {
                    Ok(processor.process_document::<_, PlainText>(content, &parser, doc_format))
                }
                OutputFormat::Html => {
                    Ok(processor.process_document::<_, Html>(content, &parser, doc_format))
                }
                OutputFormat::Djot => {
                    Ok(processor.process_document::<_, Djot>(content, &parser, doc_format))
                }
                OutputFormat::Markdown => {
                    Ok(processor.process_document::<_, Markdown>(content, &parser, doc_format))
                }
                OutputFormat::Latex => {
                    Ok(processor.process_document::<_, Latex>(content, &parser, doc_format))
                }
                OutputFormat::Typst => {
                    Ok(processor.process_document::<_, Typst>(content, &parser, doc_format))
                }
            }
        }
    }
}

/// Render a document using caller-supplied bibliography groups (from `--bibliography-blocks`).
///
/// Mirrors [`render_doc_with_output_format`] but routes through
/// [`Processor::process_document_with_caller_blocks`] so the sectional
/// bibliographies are driven by the unified engine primitive rather than
/// in-document `:::bibliography{...}` fenced divs.
fn render_doc_with_caller_blocks(
    processor: &Processor,
    content: &str,
    output_format: OutputFormat,
    input_format: DocumentInput,
    groups: &[citum_schema::grouping::BibliographyGroup],
) -> Result<String, Box<dyn Error>> {
    let doc_format = to_document_format(output_format)?;
    match input_format {
        DocumentInput::Djot => {
            let parser = citum_engine::processor::document::djot::DjotParser;
            match output_format {
                OutputFormat::Plain => Ok(processor
                    .process_document_with_caller_blocks::<_, PlainText>(
                        content, groups, &parser, doc_format,
                    )),
                OutputFormat::Html => Ok(processor.process_document_with_caller_blocks::<_, Html>(
                    content, groups, &parser, doc_format,
                )),
                OutputFormat::Djot => Ok(processor.process_document_with_caller_blocks::<_, Djot>(
                    content, groups, &parser, doc_format,
                )),
                OutputFormat::Markdown => Ok(processor
                    .process_document_with_caller_blocks::<_, Markdown>(
                        content, groups, &parser, doc_format,
                    )),
                OutputFormat::Latex => Ok(processor
                    .process_document_with_caller_blocks::<_, Latex>(
                        content, groups, &parser, doc_format,
                    )),
                OutputFormat::Typst => Ok(processor
                    .process_document_with_caller_blocks::<_, Typst>(
                        content, groups, &parser, doc_format,
                    )),
            }
        }
        DocumentInput::Markdown => {
            let parser = citum_engine::processor::document::markdown::MarkdownParser;
            match output_format {
                OutputFormat::Plain => Ok(processor
                    .process_document_with_caller_blocks::<_, PlainText>(
                        content, groups, &parser, doc_format,
                    )),
                OutputFormat::Html => Ok(processor.process_document_with_caller_blocks::<_, Html>(
                    content, groups, &parser, doc_format,
                )),
                OutputFormat::Djot => Ok(processor.process_document_with_caller_blocks::<_, Djot>(
                    content, groups, &parser, doc_format,
                )),
                OutputFormat::Markdown => Ok(processor
                    .process_document_with_caller_blocks::<_, Markdown>(
                        content, groups, &parser, doc_format,
                    )),
                OutputFormat::Latex => Ok(processor
                    .process_document_with_caller_blocks::<_, Latex>(
                        content, groups, &parser, doc_format,
                    )),
                OutputFormat::Typst => Ok(processor
                    .process_document_with_caller_blocks::<_, Typst>(
                        content, groups, &parser, doc_format,
                    )),
            }
        }
    }
}

/// Map the CLI [`OutputFormat`] enum to the engine's [`DocumentFormat`].
fn to_document_format(output_format: OutputFormat) -> Result<DocumentFormat, Box<dyn Error>> {
    match output_format {
        OutputFormat::Plain => Ok(DocumentFormat::Plain),
        OutputFormat::Html => Ok(DocumentFormat::Html),
        OutputFormat::Djot => Ok(DocumentFormat::Djot),
        OutputFormat::Markdown => Ok(DocumentFormat::Markdown),
        OutputFormat::Latex => Ok(DocumentFormat::Latex),
        OutputFormat::Typst => Ok(DocumentFormat::Typst),
    }
}

/// Shared rendering context threaded through the reference-rendering call chain.
pub(super) struct RenderContext<'a> {
    /// The configured citation processor.
    pub(super) processor: &'a citum_engine::Processor,
    /// Display name of the active style.
    pub(super) style_name: &'a str,
    /// Reference IDs to render.
    pub(super) item_ids: &'a [String],
    /// Optional annotation map (reference ID → annotation text).
    pub(super) annotations: Option<&'a HashMap<String, String>>,
    /// Formatting style for annotations.
    pub(super) annotation_style: &'a citum_io::AnnotationStyle,
}

/// Render bibliography/citation output as a human-readable string.
///
/// Dispatches to the correct monomorphised format renderer based on `output_format`.
fn render_refs_human(
    ctx: &RenderContext<'_>,
    mode: RenderMode,
    citations: Option<Vec<Citation>>,
    show_keys: bool,
    output_format: OutputFormat,
) -> Result<String, Box<dyn Error>> {
    use human::print_human_safe;
    let show_cite = matches!(mode, RenderMode::Cite | RenderMode::Both);
    let show_bib = matches!(mode, RenderMode::Bib | RenderMode::Both);
    match output_format {
        OutputFormat::Plain => {
            print_human_safe::<PlainText>(ctx, show_cite, show_bib, citations, show_keys)
                .map_err(std::convert::Into::into)
        }
        OutputFormat::Html => {
            print_human_safe::<Html>(ctx, show_cite, show_bib, citations, show_keys)
                .map_err(std::convert::Into::into)
        }
        OutputFormat::Djot => {
            print_human_safe::<Djot>(ctx, show_cite, show_bib, citations, show_keys)
                .map_err(std::convert::Into::into)
        }
        OutputFormat::Markdown => {
            print_human_safe::<Markdown>(ctx, show_cite, show_bib, citations, show_keys)
                .map_err(std::convert::Into::into)
        }
        OutputFormat::Latex => {
            print_human_safe::<Latex>(ctx, show_cite, show_bib, citations, show_keys)
                .map_err(std::convert::Into::into)
        }
        OutputFormat::Typst => {
            print_human_safe::<Typst>(ctx, show_cite, show_bib, citations, show_keys)
                .map_err(std::convert::Into::into)
        }
    }
}

/// Render bibliography/citation output as a JSON string.
///
/// Builds a JSON object containing rendered citation and/or bibliography entries,
/// keyed by reference ID.
fn render_refs_json(
    ctx: &RenderContext<'_>,
    mode: RenderMode,
    citations: Option<Vec<Citation>>,
    output_format: OutputFormat,
) -> Result<String, Box<dyn Error>> {
    use json::print_json_with_format;
    let show_cite = matches!(mode, RenderMode::Cite | RenderMode::Both);
    let show_bib = matches!(mode, RenderMode::Bib | RenderMode::Both);
    match output_format {
        OutputFormat::Plain => {
            print_json_with_format::<PlainText>(ctx, show_cite, show_bib, citations)
        }
        OutputFormat::Html => print_json_with_format::<Html>(ctx, show_cite, show_bib, citations),
        OutputFormat::Djot => print_json_with_format::<Djot>(ctx, show_cite, show_bib, citations),
        OutputFormat::Markdown => {
            print_json_with_format::<Markdown>(ctx, show_cite, show_bib, citations)
        }
        OutputFormat::Latex => print_json_with_format::<Latex>(ctx, show_cite, show_bib, citations),
        OutputFormat::Typst => print_json_with_format::<Typst>(ctx, show_cite, show_bib, citations),
    }
}

/// Extract the `options.locale` field from document YAML frontmatter, if present.
///
/// Returns `None` when the document has no frontmatter, the frontmatter has no
/// `options:` block, or `options.locale` is absent. Parsing errors are silently
/// ignored — the engine will fall back to the style's default locale.
fn extract_frontmatter_locale(content: &str) -> Option<String> {
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct FrontmatterOptions {
        locale: Option<String>,
    }

    #[derive(Deserialize)]
    struct MinimalFrontmatter {
        options: Option<FrontmatterOptions>,
    }

    let trimmed = content.trim_start();
    if !trimmed.starts_with("---") {
        return None;
    }
    #[allow(clippy::string_slice, reason = "'---' is 1-byte ASCII")]
    let after_opening = &trimmed[3..];
    // Use "\n---" so embedded "---" in YAML values (e.g. abstract: "foo---bar")
    // does not falsely close the frontmatter block.
    let closing_pos = after_opening.find("\n---").map(|p| p + 1)?;
    #[allow(
        clippy::string_slice,
        reason = "closing_pos is '\\n' offset + 1, which lands on ASCII '-'"
    )]
    let frontmatter_str = &after_opening[..closing_pos];
    serde_yaml::from_str::<MinimalFrontmatter>(frontmatter_str)
        .ok()?
        .options?
        .locale
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "tests"
)]
mod tests {
    use super::*;
    use crate::style_resolver::parse_locale_override_bytes;
    use citum_engine::Bibliography;
    use citum_io::LoadedBibliography;
    use citum_schema::Style;
    use std::collections::HashMap;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn test_output_format_display() {
        assert_eq!(OutputFormat::Plain.to_string(), "plain");
        assert_eq!(OutputFormat::Html.to_string(), "html");
        assert_eq!(OutputFormat::Djot.to_string(), "djot");
        assert_eq!(OutputFormat::Markdown.to_string(), "markdown");
        assert_eq!(OutputFormat::Latex.to_string(), "latex");
        assert_eq!(OutputFormat::Typst.to_string(), "typst");
    }

    #[test]
    fn test_load_merged_bibliography_rejects_cross_file_duplicate_membership() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock should be after epoch")
            .as_nanos();
        let base = std::env::temp_dir().join(format!("citum-merged-bib-{now}"));
        std::fs::create_dir_all(&base).expect("temp dir should be created");

        let bib_a = base.join("a.yaml");
        let bib_b = base.join("b.yaml");

        std::fs::write(
            &bib_a,
            r#"
references:
  - class: monograph
    id: ref-a
    type: book
    title: Book A
    issued: "2020"
sets:
  group-1: [ref-a]
"#,
        )
        .expect("first fixture should write");
        std::fs::write(
            &bib_b,
            r#"
references:
  - class: monograph
    id: ref-a
    type: book
    title: Book A
    issued: "2020"
sets:
  group-2: [ref-a]
"#,
        )
        .expect("second fixture should write");

        let err = load_merged_bibliography(&[bib_a.clone(), bib_b.clone()])
            .expect_err("must reject cross-file duplicate membership");
        let msg = err.to_string();
        assert!(
            msg.contains("appears in both compound sets 'group-1' and 'group-2'"),
            "unexpected error: {msg}"
        );

        let _ = std::fs::remove_file(bib_a);
        let _ = std::fs::remove_file(bib_b);
        let _ = std::fs::remove_dir(base);
    }

    #[test]
    fn test_create_processor_applies_locale_override_from_file_style() {
        use citum_schema::options::Config;
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock should be after epoch")
            .as_nanos();
        let base = std::env::temp_dir().join(format!("citum-locale-override-{now}"));
        let style_path = base.join("style.yaml");
        let overrides_dir = base.join("locales").join("overrides");
        std::fs::create_dir_all(&overrides_dir).expect("override dir should exist");
        std::fs::write(&style_path, "info: { title: Test Style }\n")
            .expect("style file should write");
        std::fs::write(
            overrides_dir.join("test-override.yaml"),
            r#"
grammar-options:
  punctuation-in-quote: false
  nbsp-before-colon: false
  open-quote: "<<"
  close-quote: ">>"
  open-inner-quote: "<"
  close-inner-quote: ">"
  serial-comma: false
  page-range-delimiter: "~"
"#,
        )
        .expect("override file should write");

        let style = Style {
            info: citum_schema::StyleInfo {
                title: Some("Test Style".into()),
                default_locale: Some("en-US".into()),
                ..Default::default()
            },
            options: Some(Config {
                locale_override: Some("test-override".into()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let loaded = LoadedBibliography {
            references: Bibliography::new(),
            sets: None,
        };

        let processor = create_processor(
            style,
            loaded,
            style_path.to_str().expect("utf-8 path"),
            false,
            None,
        )
        .expect("processor should apply locale override");

        assert!(!processor.locale.punctuation_in_quote);
        assert_eq!(processor.locale.grammar_options.open_quote, "<<");
        assert_eq!(processor.locale.grammar_options.page_range_delimiter, "~");

        let _ = std::fs::remove_dir_all(base);
    }

    #[test]
    fn test_create_processor_applies_builtin_locale_override() {
        let style = citum_schema::embedded::get_embedded_style("chicago")
            .expect("embedded style should exist")
            .expect("embedded style should parse");
        let loaded = LoadedBibliography {
            references: Bibliography::new(),
            sets: None,
        };

        let processor =
            create_processor(style, loaded, "chicago", false, None).expect("processor should load");

        assert_eq!(processor.locale.locale, "en-US");
        assert_eq!(
            processor
                .style
                .options
                .as_ref()
                .and_then(|c| c.locale_override.as_deref()),
            Some("en-US-chicago")
        );
        assert_eq!(
            processor.locale.grammar_options.page_range_delimiter,
            "\u{2013}"
        );
    }

    #[test]
    fn test_create_processor_locale_arg_overrides_style_default() {
        let style = citum_schema::embedded::get_embedded_style("apa")
            .expect("embedded style should exist")
            .expect("embedded style should parse");
        let loaded = LoadedBibliography {
            references: Bibliography::new(),
            sets: None,
        };

        let processor = create_processor(style, loaded, "apa", false, Some("es-ES"))
            .expect("processor should load with locale override");

        assert_eq!(processor.locale.locale, "es-ES");
    }

    #[test]
    fn test_create_processor_locale_arg_skips_style_locale_override() {
        let style = citum_schema::embedded::get_embedded_style("chicago")
            .expect("embedded style should exist")
            .expect("embedded style should parse");
        let loaded = LoadedBibliography {
            references: Bibliography::new(),
            sets: None,
        };

        let processor = create_processor(style, loaded, "chicago", false, Some("es-ES"))
            .expect("processor should load requested locale");

        assert_eq!(processor.locale.locale, "es-ES");
        assert!(!processor.locale.grammar_options.serial_comma);
        assert_eq!(processor.locale.grammar_options.open_quote, "«");
    }

    #[test]
    fn test_create_processor_locale_arg_rejects_unknown_locale() {
        let style = citum_schema::embedded::get_embedded_style("apa")
            .expect("embedded style should exist")
            .expect("embedded style should parse");
        let loaded = LoadedBibliography {
            references: Bibliography::new(),
            sets: None,
        };

        let err = create_processor(style, loaded, "apa", false, Some("zz-ZZ"))
            .expect_err("unknown explicit locale should error");

        assert!(
            err.to_string().contains("locale not found: 'zz-ZZ'"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_parse_locale_override_bytes_from_json() {
        let override_data = serde_json::to_vec(&serde_json::json!({
            "messages": { "term.page-label": "pg." },
            "legacy-term-aliases": { "page": "term.page-label" }
        }))
        .expect("json should serialize");

        let parsed = parse_locale_override_bytes(&override_data, "json")
            .expect("override json should parse");

        assert_eq!(
            parsed.messages,
            HashMap::from([(String::from("term.page-label"), String::from("pg."))])
        );
        assert_eq!(
            parsed.legacy_term_aliases.get("page").map(String::as_str),
            Some("term.page-label")
        );
    }

    #[test]
    fn test_extract_frontmatter_locale_present() {
        let content = "---\noptions:\n  locale: de-DE\n---\nBody text.";
        assert_eq!(
            extract_frontmatter_locale(content),
            Some(String::from("de-DE"))
        );
    }

    #[test]
    fn test_extract_frontmatter_locale_absent_options() {
        let content = "---\ntitle: My Doc\n---\nBody text.";
        assert!(extract_frontmatter_locale(content).is_none());
    }

    #[test]
    fn test_extract_frontmatter_locale_no_frontmatter() {
        let content = "No frontmatter here.";
        assert!(extract_frontmatter_locale(content).is_none());
    }

    #[test]
    fn test_extract_frontmatter_locale_options_without_locale() {
        let content = "---\noptions:\n  bibliography:\n    label-mode: numeric\n---\nBody.";
        assert!(extract_frontmatter_locale(content).is_none());
    }

    #[test]
    fn test_extract_frontmatter_locale_embedded_dashes_in_value() {
        // Regression: inline "---" inside a YAML value must not be treated as
        // the closing fence. The correct closing "---" is on its own line.
        let content = "---\ntitle: \"pre---post\"\noptions:\n  locale: fr-FR\n---\nBody.";
        assert_eq!(
            extract_frontmatter_locale(content),
            Some(String::from("fr-FR"))
        );
    }
}