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

//! Author-substitution logic for contributor rendering.
//!
//! When a reference has no author, this module handles the fallback chain:
//! editor → title → translator, as configured by the style's `substitute` block.

use crate::processor::rendering::get_variable_key;
use crate::reference::Reference;
use crate::render::format::OutputFormat;
use crate::values::text_case::apply_text_case;
use crate::values::title::resolve_substitute_text_case;
use crate::values::{ProcHints, ProcValues, RenderContext, RenderOptions};
use citum_schema::options::{
    RoleLabelPreset, SubstituteField, SubstituteKey, SubstituteTitleQuoteMode,
};
use citum_schema::reference::Title;
use citum_schema::reference::{
    AudioVisualType, ClassExtension, Contributor, ContributorRole as DataRole,
};
use citum_schema::template::{
    ContributorRole, ContributorRoles, Rendering, TemplateComponent, TemplateContributor, TitleType,
};

/// Resolved value occupying the style's effective primary-contributor slot.
#[derive(Debug, Clone)]
pub(crate) enum EffectivePrimary {
    /// A scalar contributor payload, including existing semantic-author fallback.
    Contributor {
        contributor: Box<Contributor>,
        role: ContributorRole,
    },
    /// An ordered cross-role candidate assembled from the native contributor vector.
    Merged(ContributorRoles),
    /// A title field used after contributor candidates are exhausted.
    Title { title: Title, kind: TitleType },
}

enum ResolvedRole {
    BuiltIn(ContributorRole),
    Custom(String),
}

impl ResolvedRole {
    fn key(&self) -> &str {
        match self {
            Self::BuiltIn(role) => role.as_str(),
            Self::Custom(role) => role.as_str(),
        }
    }

    fn built_in(&self) -> Option<&ContributorRole> {
        match self {
            Self::BuiltIn(role) => Some(role),
            Self::Custom(_) => None,
        }
    }
}

fn normalize_role_key(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }

    let canonical = trimmed
        .chars()
        .map(|ch| match ch {
            '_' => '-',
            other => other.to_ascii_lowercase(),
        })
        .collect::<String>();

    canonical
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
        .then_some(canonical)
}

fn parse_known_role(value: &str) -> Option<ContributorRole> {
    Some(match value {
        "author" => ContributorRole::Author,
        "chair" => ContributorRole::Chair,
        "editor" => ContributorRole::Editor,
        "translator" => ContributorRole::Translator,
        "director" => ContributorRole::Director,
        "composer" => ContributorRole::Composer,
        "illustrator" => ContributorRole::Illustrator,
        "collection-editor" => ContributorRole::CollectionEditor,
        "container-author" => ContributorRole::ContainerAuthor,
        "editorial-director" => ContributorRole::EditorialDirector,
        "textual-editor" => ContributorRole::TextualEditor,
        "original-author" => ContributorRole::OriginalAuthor,
        "reviewed-author" => ContributorRole::ReviewedAuthor,
        "recipient" => ContributorRole::Recipient,
        "interviewer" => ContributorRole::Interviewer,
        "guest" => ContributorRole::Guest,
        "performer" => ContributorRole::Performer,
        "inventor" => ContributorRole::Inventor,
        "counsel" => ContributorRole::Counsel,
        "writer" => ContributorRole::Writer,
        _ => return None,
    })
}

fn resolve_role_key(value: &str) -> Option<ResolvedRole> {
    let canonical = normalize_role_key(value)?;
    Some(
        parse_known_role(&canonical)
            .map(ResolvedRole::BuiltIn)
            .unwrap_or(ResolvedRole::Custom(canonical)),
    )
}

fn lookup_role_contributor(
    reference: &Reference,
    role: &ResolvedRole,
) -> Option<citum_schema::reference::contributor::Contributor> {
    match role {
        ResolvedRole::BuiltIn(ContributorRole::Editor) => reference.editor(),
        ResolvedRole::BuiltIn(ContributorRole::Translator) => reference.translator(),
        ResolvedRole::BuiltIn(role) => {
            data_role_for_builtin(role).and_then(|data_role| reference.contributor(data_role))
        }
        ResolvedRole::Custom(role) => reference.contributor(data_role_for_custom(role)),
    }
}

fn data_role_for_builtin(role: &ContributorRole) -> Option<DataRole> {
    Some(match role {
        ContributorRole::Director => DataRole::Director,
        ContributorRole::Composer => DataRole::Composer,
        ContributorRole::Illustrator => DataRole::Illustrator,
        ContributorRole::Recipient => DataRole::Recipient,
        ContributorRole::Interviewer => DataRole::Interviewer,
        ContributorRole::Guest => DataRole::Guest,
        ContributorRole::Performer => DataRole::Performer,
        ContributorRole::Writer => DataRole::Writer,
        ContributorRole::ContainerAuthor
        | ContributorRole::CollectionEditor
        | ContributorRole::EditorialDirector
        | ContributorRole::TextualEditor
        | ContributorRole::OriginalAuthor
        | ContributorRole::ReviewedAuthor
        | ContributorRole::Chair
        | ContributorRole::Inventor
        | ContributorRole::Counsel => DataRole::Unknown(role.as_str().to_string()),
        ContributorRole::Unknown(role) => DataRole::Unknown(role.clone()),
        ContributorRole::Author
        | ContributorRole::Editor
        | ContributorRole::Translator
        | ContributorRole::Publisher
        | ContributorRole::Interviewee => return None,
        _ => return None,
    })
}

fn data_role_for_custom(role: &str) -> DataRole {
    match role {
        "compiler" => DataRole::Compiler,
        "performer" => DataRole::Performer,
        "narrator" => DataRole::Narrator,
        "host" => DataRole::Host,
        "producer" | "executive-producer" => DataRole::Producer,
        "writer" => DataRole::Writer,
        _ => DataRole::Unknown(role.to_string()),
    }
}

/// Resolve all multilingual names for a contributor using the current options.
///
/// Eliminates the copy-paste resolution pattern across Editor, Translator, and
/// primary-contributor paths.
pub(super) fn resolve_multilingual_for_contrib(
    contrib: &citum_schema::reference::contributor::Contributor,
    options: &RenderOptions<'_>,
) -> Vec<crate::reference::FlatName> {
    let mode = options
        .config
        .multilingual
        .as_ref()
        .and_then(|m| m.name_mode.as_ref());
    let preferred_transliteration = options
        .config
        .multilingual
        .as_ref()
        .and_then(|m| m.preferred_transliteration.as_deref());
    let preferred_script = options
        .config
        .multilingual
        .as_ref()
        .and_then(|m| m.preferred_script.as_ref());
    crate::values::resolve_multilingual_name(
        contrib,
        mode,
        preferred_transliteration,
        preferred_script,
        &options.locale.locale,
    )
}

struct SubstituteRoleLabelContext<'a, 'b, F> {
    component: &'a TemplateContributor,
    role: &'a ResolvedRole,
    names_count: usize,
    reference: &'a Reference,
    options: &'a RenderOptions<'b>,
    effective_rendering: &'a Rendering,
    fmt: &'a F,
    substitute: &'a citum_schema::options::Substitute,
}

fn substitute_role_label_preset(
    role: &ResolvedRole,
    options: &RenderOptions<'_>,
    substitute: &citum_schema::options::Substitute,
) -> Option<RoleLabelPreset> {
    substitute
        .contributor_role_form
        .as_deref()
        .and_then(|form| match form {
            "short" => Some(RoleLabelPreset::ShortSuffix),
            "short-comma" => Some(RoleLabelPreset::ShortSuffixComma),
            "long" => Some(RoleLabelPreset::LongSuffix),
            _ => None,
        })
        .or_else(|| {
            let contributors = options.config.contributors.as_ref()?;
            role.built_in()
                .and_then(|known| contributors.effective_role_label_preset(known))
        })
        .or_else(|| {
            let contributors = options.config.contributors.as_ref()?;
            role.built_in()
                .and_then(|known| contributors.default_role_label_preset(known))
        })
}

/// Resolve substitute-path role labels for a rendered fallback contributor.
fn resolve_substitute_role_labels<F: OutputFormat<Output = String>>(
    context: &SubstituteRoleLabelContext<'_, '_, F>,
) -> (Option<String>, Option<String>) {
    let SubstituteRoleLabelContext {
        component,
        role,
        names_count,
        reference,
        options,
        effective_rendering,
        fmt,
        substitute,
    } = context;
    if matches!(role.built_in(), Some(ContributorRole::Author)) {
        return (None, None);
    }
    if options.context != RenderContext::Bibliography
        || role
            .built_in()
            .is_some_and(|known| super::is_role_label_omitted(options, known))
    {
        return (None, None);
    }

    if substitute.contributor_role_form.is_none()
        && substitute.contributor_role_case.is_none()
        && let Some(known) = role.built_in()
        && options
            .config
            .contributors
            .as_ref()
            .is_some_and(|contributors| {
                contributors.role_label_presentation(known).is_some()
                    || contributors
                        .role
                        .as_ref()
                        .and_then(|role_options| role_options.defaults)
                        .and_then(|defaults| defaults.presentation_for(known))
                        .is_some()
            })
    {
        let mut role_component = (*component).clone();
        role_component.contributor = known.clone().into();
        return super::labels::resolve_role_labels::<F>(super::labels::RoleLabelContext {
            component: &role_component,
            role: known,
            reference,
            names_count: *names_count,
            effective_rendering,
            options,
            fmt: *fmt,
            role_omitted: super::is_role_label_omitted(options, known),
        });
    }

    let preset = substitute_role_label_preset(role, options, substitute);

    preset
        .and_then(|selected| {
            if component.contributor == ContributorRole::Author
                && matches!(
                    selected,
                    RoleLabelPreset::VerbPrefix | RoleLabelPreset::VerbShortPrefix
                )
            {
                return None;
            }

            role.built_in().map(|known| {
                super::labels::resolve_role_label_preset::<F>(
                    known,
                    selected,
                    *names_count,
                    super::labels::RoleLabelTermOptions {
                        gender: None,
                        text_case: substitute.contributor_role_case,
                    },
                    effective_rendering,
                    options,
                    fmt,
                )
            })
        })
        .unwrap_or((None, None))
}

/// Format a substitute contributor using the current role-aware config path.
#[allow(
    clippy::too_many_arguments,
    reason = "Role-aware substitute formatting needs shared engine state until this module is refactored."
)]
fn resolve_named_substitute<F: OutputFormat<Output = String>>(
    role: &ResolvedRole,
    contributor: &citum_schema::reference::contributor::Contributor,
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    let names_vec = resolve_multilingual_for_contrib(contributor, options);
    if names_vec.is_empty() {
        return None;
    }

    // Preserve the scalar author fast path. Semantic authors are not
    // substitutes, do not carry role labels, and should avoid constructing a
    // substituted variable key on every bibliography render.
    if matches!(role.built_in(), Some(ContributorRole::Author)) {
        let formatted = super::format_contributor_names(
            component,
            &ContributorRole::Author,
            &names_vec,
            reference,
            effective_rendering,
            options,
            hints,
        );
        return Some(ProcValues {
            value: crate::values::apply_abbreviation(formatted, options.abbreviation_map),
            prefix: None,
            suffix: None,
            url: crate::values::resolve_effective_url(
                component.links.as_ref(),
                options.config.links.as_ref(),
                reference,
                citum_schema::options::LinkAnchor::Component,
            ),
            substituted_key: None,
            pre_formatted: false,
        });
    }

    let effective_name_order = component.name_order.as_ref().or_else(|| {
        role.built_in().and_then(|known| {
            options
                .config
                .contributors
                .as_ref()
                .and_then(|contributors| contributors.effective_role_name_order(known))
        })
    });

    // Priority chain for name_form:
    // 1. component.name_form (TemplateContributor-level override - highest priority)
    // 2. effective_rendering.name_form (from overrides, second priority)
    // 3. config (options-level fallback)
    let effective_name_form = component.name_form.or(effective_rendering.name_form);

    let name_overrides = super::names::NamesOverrides {
        name_order: effective_name_order,
        sort_separator: component.sort_separator.as_ref(),
        delimiter: component.delimiter.as_ref(),
        shorten: component.shorten.as_ref(),
        and: component.and.as_ref(),
        initialize_with: effective_rendering.initialize_with.as_ref(),
        name_form: effective_name_form,
        strip_periods: effective_rendering.strip_periods,
        item_language: crate::values::effective_item_language(reference),
    };
    let formatted =
        super::names::format_names(&names_vec, &component.form, options, &name_overrides, hints);
    let (prefix, suffix) = resolve_substitute_role_labels::<F>(&SubstituteRoleLabelContext {
        component,
        role,
        names_count: names_vec.len(),
        reference,
        options,
        effective_rendering,
        fmt,
        substitute,
    });

    let url = crate::values::resolve_effective_url(
        component.links.as_ref(),
        options.config.links.as_ref(),
        reference,
        citum_schema::options::LinkAnchor::Component,
    );

    let substituted_key = role.built_in().map_or_else(
        || Some(format!("contributor:{}", role.key())),
        |known| {
            get_variable_key(&TemplateComponent::Contributor(TemplateContributor {
                contributor: known.clone().into(),
                rendering: component.rendering.clone(),
                ..Default::default()
            }))
        },
    );

    Some(ProcValues {
        value: fmt.text(&formatted),
        prefix,
        suffix,
        url,
        substituted_key,
        pre_formatted: true,
    })
}

#[allow(
    clippy::too_many_arguments,
    reason = "Substitute lookup and formatting share the same rendering state."
)]
fn resolve_contributor_substitute_for_role<F: OutputFormat<Output = String>>(
    role: &ResolvedRole,
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    let contributor = lookup_role_contributor(reference, role)?;
    resolve_named_substitute(
        role,
        &contributor,
        component,
        hints,
        options,
        reference,
        effective_rendering,
        fmt,
        substitute,
    )
}

/// Check if a role should be suppressed by role-substitute configuration.
///
/// Returns true if this role appears as a fallback in some other role's chain
/// AND that primary role has data on the reference.
pub(super) fn is_role_suppressed_by_substitute(
    role: &ContributorRole,
    substitute: &citum_schema::options::Substitute,
    reference: &Reference,
) -> bool {
    let role_str = role.as_str();

    for (primary_role_str, fallback_chain) in &substitute.role_substitute {
        // Check if this role is in the fallback chain
        if !fallback_chain
            .iter()
            .filter_map(|entry| resolve_role_key(entry))
            .any(|entry| entry.key() == role_str)
        {
            continue;
        }

        if let Some(primary_role) = resolve_role_key(primary_role_str)
            && lookup_role_contributor(reference, &primary_role).is_some()
        {
            return true;
        }
    }

    false
}

fn find_role_substitute_chain<'a>(
    substitute: &'a citum_schema::options::Substitute,
    primary_role: &ContributorRole,
) -> Option<&'a Vec<String>> {
    let primary_role_str = primary_role.as_str();

    substitute
        .role_substitute
        .get(primary_role_str)
        .or_else(|| {
            substitute
                .role_substitute
                .iter()
                .find_map(|(configured_role, fallback_chain)| {
                    resolve_role_key(configured_role)
                        .filter(|resolved| resolved.key() == primary_role_str)
                        .map(|_| fallback_chain)
                })
        })
}

/// Attempt to substitute a non-author contributor field via role-substitute fallback chain.
///
/// Returns `Some(ProcValues)` if a substitute from the chain was found, `None` if the chain
/// is exhausted with no result.
#[allow(
    clippy::too_many_arguments,
    reason = "Role-aware role-substitute needs shared engine state."
)]
pub(super) fn resolve_role_substitute<F: OutputFormat<Output = String>>(
    primary_role: &ContributorRole,
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    let fallback_chain = find_role_substitute_chain(substitute, primary_role)?;

    for fallback_role_str in fallback_chain {
        let Some(fallback_role) = resolve_role_key(fallback_role_str) else {
            continue;
        };

        if let Some(result) = resolve_contributor_substitute_for_role(
            &fallback_role,
            component,
            hints,
            options,
            reference,
            effective_rendering,
            fmt,
            substitute,
        ) {
            return Some(result);
        }
    }

    None
}

/// The `substituted_key` recorded on `ProcValues` for a title substitution,
/// keyed by which title slot filled the missing-author position.
fn substituted_key_for_title_type(title_type: &TitleType) -> &'static str {
    match title_type {
        TitleType::ParentSerial => "title:ParentSerial",
        _ => "title:Primary",
    }
}

fn resolve_title_substitute<F: OutputFormat<Output = String>>(
    title: Title,
    title_type: &TitleType,
    component: &TemplateContributor,
    options: &RenderOptions<'_>,
    reference: &Reference,
    fmt: &F,
    quote_in_citation: bool,
) -> ProcValues<F::Output> {
    let substituted_key = substituted_key_for_title_type(title_type);
    let title_str = title_substitute_text(title, options.context);
    // The substitute chain has no `TemplateTitle` to carry a per-component
    // `text-case:` override, so only the style's category-level `titles:`
    // config (keyed by reference type) applies here — see
    // `resolve_substitute_text_case`.
    let title_str = match resolve_substitute_text_case(title_type, reference, options) {
        Some(case) => apply_text_case(&title_str, case),
        None => title_str,
    };
    let value = if options.context == RenderContext::Citation && quote_in_citation {
        let marks = crate::render::format::QuoteMarks::from(&options.locale.grammar_options);
        fmt.quote(fmt.text(&title_str), &marks)
    } else {
        fmt.text(&title_str)
    };

    let url = crate::values::resolve_effective_url(
        component.links.as_ref(),
        options.config.links.as_ref(),
        reference,
        citum_schema::options::LinkAnchor::Title,
    );

    ProcValues {
        value,
        prefix: None,
        suffix: None,
        url,
        substituted_key: Some(substituted_key.to_string()),
        pre_formatted: true,
    }
}

/// Resolve whether a substituted title should be quoted per the reference's
/// title-category rendering (`titles:` config), mirroring how a normal
/// (non-substitute) title component resolves quoting — see
/// `effective_title_quote_depth`. Defaults to no quoting when the style has
/// no `titles:` config for the category, matching that function's default.
fn resolve_category_quote(reference: &Reference, options: &RenderOptions<'_>) -> bool {
    let ref_type = reference.ref_type();
    let lang = reference.language();
    crate::render::component::get_title_category_rendering(
        &TitleType::Primary,
        Some(&ref_type),
        lang.as_deref(),
        &options.config,
    )
    .and_then(|rendering| rendering.quote)
    .unwrap_or(false)
}

fn title_substitute_text(title: Title, context: RenderContext) -> String {
    if context != RenderContext::Citation {
        return title.to_string();
    }

    match title {
        Title::Structured(s) => s.main,
        Title::MultiStructured(v) => v
            .into_iter()
            .next()
            .map(|(_, s)| s.main)
            .unwrap_or_default(),
        Title::Shorthand(abbr, _) => abbr,
        _ => title.to_string(),
    }
}

fn resolve_parent_serial_title(reference: &Reference) -> Option<Title> {
    match reference.extension() {
        ClassExtension::SerialComponent(_)
        | ClassExtension::LegalCase(_)
        | ClassExtension::Treaty(_) => reference.container_title(),
        _ => None,
    }
}

fn native_type_key(reference: &Reference) -> Option<&'static str> {
    reference
        .as_audio_visual()
        .and_then(|work| match work.r#type {
            AudioVisualType::Film => Some("film"),
            AudioVisualType::Episode => Some("episode"),
            AudioVisualType::Recording => Some("recording"),
            AudioVisualType::Broadcast => Some("broadcast"),
            _ => None,
        })
}

fn exact_type_candidates<'a>(
    reference: &Reference,
    substitute: &'a citum_schema::options::Substitute,
) -> Option<&'a [SubstituteKey]> {
    if let Some(candidates) =
        native_type_key(reference).and_then(|key| substitute.overrides.get(key))
    {
        return Some(candidates.as_slice());
    }

    substitute
        .overrides
        .get(&reference.ref_type())
        .map(Vec::as_slice)
}

fn contributor_for_candidate(reference: &Reference, role: &ContributorRole) -> Option<Contributor> {
    lookup_role_contributor(reference, &ResolvedRole::BuiltIn(role.clone()))
}

/// An [`EffectivePrimary`] candidate paired with the multilingual names that
/// justify selecting it, resolved together in a single pass.
///
/// `resolve_candidate` needs a candidate's names only to test whether it is
/// non-empty (to decide whether the candidate qualifies); keeping the
/// resolved vector alongside the selected variant lets
/// [`effective_primary_names`] reuse it instead of re-running the same
/// (potentially expensive, suppression-aware) name assembly a second time.
struct EffectivePrimaryResolution {
    primary: EffectivePrimary,
    names: Vec<crate::reference::FlatName>,
}

fn resolve_candidate(
    candidate: &SubstituteKey,
    reference: &Reference,
    config: &citum_schema::options::Config,
    locale: &citum_schema::locale::Locale,
) -> Option<EffectivePrimaryResolution> {
    match candidate {
        SubstituteKey::Contributor(candidate) => {
            if let Some(role) = candidate.contributor.as_single() {
                contributor_for_candidate(reference, role).and_then(|contributor| {
                    let names =
                        super::merged::semantic_contributor_names(&contributor, config, locale);
                    (!names.is_empty()).then(|| EffectivePrimaryResolution {
                        primary: EffectivePrimary::Contributor {
                            contributor: Box::new(contributor),
                            role: role.clone(),
                        },
                        names,
                    })
                })
            } else {
                let component = TemplateContributor {
                    contributor: candidate.contributor.clone(),
                    ..Default::default()
                };
                let names = super::merged::semantic_names(&component, reference, config, locale);
                (!names.is_empty()).then(|| EffectivePrimaryResolution {
                    primary: EffectivePrimary::Merged(candidate.contributor.clone()),
                    names,
                })
            }
        }
        SubstituteKey::Field(field) => match field {
            SubstituteField::CollectionEditor => contributor_for_candidate(
                reference,
                &ContributorRole::CollectionEditor,
            )
            .and_then(|contributor| {
                let names = super::merged::semantic_contributor_names(&contributor, config, locale);
                (!names.is_empty()).then(|| EffectivePrimaryResolution {
                    primary: EffectivePrimary::Contributor {
                        contributor: Box::new(contributor),
                        role: ContributorRole::CollectionEditor,
                    },
                    names,
                })
            }),
            SubstituteField::Editor => reference.local_editor().and_then(|contributor| {
                let names = super::merged::semantic_contributor_names(&contributor, config, locale);
                (!names.is_empty()).then(|| EffectivePrimaryResolution {
                    primary: EffectivePrimary::Contributor {
                        contributor: Box::new(contributor),
                        role: ContributorRole::Editor,
                    },
                    names,
                })
            }),
            SubstituteField::ParentSerial => {
                resolve_parent_serial_title(reference).map(|title| EffectivePrimaryResolution {
                    primary: EffectivePrimary::Title {
                        title,
                        kind: TitleType::ParentSerial,
                    },
                    names: Vec::new(),
                })
            }
            SubstituteField::Title => reference.title().map(|title| EffectivePrimaryResolution {
                primary: EffectivePrimary::Title {
                    title,
                    kind: TitleType::Primary,
                },
                names: Vec::new(),
            }),
            SubstituteField::Translator => reference.translator().and_then(|contributor| {
                let names = super::merged::semantic_contributor_names(&contributor, config, locale);
                (!names.is_empty()).then(|| EffectivePrimaryResolution {
                    primary: EffectivePrimary::Contributor {
                        contributor: Box::new(contributor),
                        role: ContributorRole::Translator,
                    },
                    names,
                })
            }),
        },
    }
}

/// Resolve the effective-primary candidate and its names together, computing
/// each candidate's name assembly at most once. Shared by [`effective_primary`]
/// and [`effective_primary_names`] so neither re-derives the other's work.
fn resolve_effective_primary(
    reference: &Reference,
    substitute: &citum_schema::options::Substitute,
    config: &citum_schema::options::Config,
    locale: &citum_schema::locale::Locale,
) -> Option<EffectivePrimaryResolution> {
    if let Some(candidates) = exact_type_candidates(reference, substitute) {
        for candidate in candidates {
            if let Some(resolved) = resolve_candidate(candidate, reference, config, locale) {
                return Some(resolved);
            }
        }
    }

    if let Some(contributor) = reference.author() {
        let names = super::merged::semantic_contributor_names(&contributor, config, locale);
        if !names.is_empty() {
            return Some(EffectivePrimaryResolution {
                primary: EffectivePrimary::Contributor {
                    contributor: Box::new(contributor),
                    role: ContributorRole::Author,
                },
                names,
            });
        }
    }

    substitute
        .template
        .iter()
        .find_map(|candidate| resolve_candidate(candidate, reference, config, locale))
}

/// Resolve the single effective-primary value shared by rendering and semantic consumers.
pub(crate) fn effective_primary(
    reference: &Reference,
    substitute: &citum_schema::options::Substitute,
    config: &citum_schema::options::Config,
    locale: &citum_schema::locale::Locale,
) -> Option<EffectivePrimary> {
    resolve_effective_primary(reference, substitute, config, locale)
        .map(|resolved| resolved.primary)
}

/// Resolve effective-primary names for sorting, matching, and disambiguation.
pub(crate) fn effective_primary_names(
    reference: &Reference,
    substitute: &citum_schema::options::Substitute,
    config: &citum_schema::options::Config,
    locale: &citum_schema::locale::Locale,
) -> Vec<crate::reference::FlatName> {
    resolve_effective_primary(reference, substitute, config, locale)
        .map(|resolved| resolved.names)
        .unwrap_or_default()
}

/// Attempt to substitute an empty author field with editor, title, or translator.
///
/// Returns `Some(ProcValues)` if a substitute was found, `None` if the chain
/// is exhausted with no result (caller should then return `None` from `values()`).
pub(super) fn resolve_author_substitute<F: OutputFormat<Output = String>>(
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    match effective_primary(reference, substitute, &options.config, options.locale) {
        Some(EffectivePrimary::Contributor { contributor, role }) => resolve_named_substitute(
            &ResolvedRole::BuiltIn(role),
            &contributor,
            component,
            hints,
            options,
            reference,
            effective_rendering,
            fmt,
            substitute,
        ),
        Some(EffectivePrimary::Merged(roles)) => {
            let mut merged = component.clone();
            merged.contributor = roles;
            merged.merge = None;
            let mut values = super::merged::values(
                &merged,
                reference,
                hints,
                options,
                effective_rendering,
                fmt,
            )?;
            values.substituted_key = Some("contributor:effective-primary".to_string());
            Some(values)
        }
        Some(EffectivePrimary::Title { title, kind }) => {
            let quote_in_citation = matches!(kind, TitleType::Primary)
                && match substitute.title_quote {
                    Some(SubstituteTitleQuoteMode::ByCategory) => {
                        resolve_category_quote(reference, options)
                    }
                    Some(SubstituteTitleQuoteMode::Always) | None => true,
                };
            Some(resolve_title_substitute(
                title,
                &kind,
                component,
                options,
                reference,
                fmt,
                quote_in_citation,
            ))
        }
        None => None,
    }
}