character-wizard-cli 0.5.0

Native level-1 SRD character creation CLI
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
//! Derived character values and presentation-ready rule projections.

use std::collections::BTreeSet;

use crate::character_wizard_srd_data as srd;

use super::record::{
    Character, ClassResource, CoinPurse, EquipmentItem, SpellSlotPool, SpellTableEntry,
    SpellcastingProfile, WeaponAttack,
};

impl Character {
    #[must_use]
    pub fn skills(&self) -> BTreeSet<String> {
        let mut values: BTreeSet<String> = srd::background_rule(&self.background)
            .map_or(&[][..], |rule| rule.skills)
            .iter()
            .map(|value| (*value).to_owned())
            .collect();
        values.extend(self.class_skills.iter().cloned());
        values.extend(
            self.skilled_proficiencies
                .iter()
                .filter(|value| srd::skill_ability(value).is_some())
                .cloned(),
        );
        values.extend(self.human_skill.iter().cloned());
        values.extend(self.elf_keen_senses_skill.iter().cloned());
        values
    }

    #[must_use]
    pub fn skill_modifier(&self, skill: &str) -> i16 {
        let mut value = self
            .abilities
            .modifier(srd::skill_ability(skill).unwrap_or(""));
        if self.class_choices.expertise.contains(skill) {
            value += i16::from(self.proficiency_bonus()) * 2;
        } else if self.skills().contains(skill) {
            value += i16::from(self.proficiency_bonus());
        }
        if self.class_choices.divine_order.as_deref() == Some("Thaumaturge")
            && ["Arcana", "Religion"].contains(&skill)
        {
            value += self.abilities.modifier("wisdom").max(1);
        }
        if self.class_choices.primal_order.as_deref() == Some("Magician")
            && ["Arcana", "Nature"].contains(&skill)
        {
            value += self.abilities.modifier("wisdom").max(1);
        }
        value
    }

    #[must_use]
    pub fn hit_points(&self) -> i16 {
        i16::from(srd::class_rule(&self.character_class).map_or(0, |rule| rule.hit_die))
            + self.abilities.modifier("constitution")
            + i16::from(self.species == "Dwarf")
    }

    #[must_use]
    pub fn initiative_modifier(&self) -> i16 {
        self.abilities.modifier("dexterity")
            + if srd::background_rule(&self.background).is_some_and(|rule| rule.feat == "Alert")
                || self.human_origin_feat.as_deref() == Some("Alert")
            {
                i16::from(self.proficiency_bonus())
            } else {
                0
            }
    }

    #[must_use]
    pub fn speed(&self) -> u8 {
        let mut speed = if self.elf_lineage.as_deref() == Some("Wood Elf") {
            35
        } else {
            srd::species_rule(&self.species).map_or(0, |rule| rule.speed)
        };
        if self
            .equipped_armor()
            .as_deref()
            .and_then(srd::armor_rule)
            .and_then(|armor| armor.strength_requirement)
            .is_some_and(|required| self.abilities.strength < required)
        {
            speed = speed.saturating_sub(10);
        }
        speed
    }

    #[must_use]
    pub fn armor_class(&self) -> i16 {
        let dexterity = self.abilities.modifier("dexterity");
        let armor = self.equipped_armor();
        let mut value = if let Some(rule) = armor.as_deref().and_then(srd::armor_rule) {
            rule.base_ac
                + match rule.dexterity_cap {
                    Some(cap) => dexterity.min(cap),
                    None => dexterity,
                }
        } else if self.character_class == "Barbarian" {
            10 + dexterity + self.abilities.modifier("constitution")
        } else if self.character_class == "Monk" {
            10 + dexterity + self.abilities.modifier("wisdom")
        } else {
            10 + dexterity
        };
        if armor.is_some() && self.class_choices.fighting_style.as_deref() == Some("Defense") {
            value += 1;
        }
        if self.shield_equipped() {
            value += 2;
        }
        value
    }

    #[must_use]
    pub fn inventory(&self) -> Vec<EquipmentItem> {
        let mut grants = Vec::new();
        if self.class_equipment_option != "Gold"
            && let Some((items, _)) =
                srd::class_equipment(&self.character_class, &self.class_equipment_option)
        {
            grants.extend_from_slice(items);
        }
        if self.background_equipment_option == "A"
            && let Some((items, _)) = srd::background_equipment(&self.background)
        {
            grants.extend_from_slice(items);
        }
        let mut merged: Vec<((String, Option<String>), u16)> = Vec::new();
        for grant in grants {
            let expanded = srd::pack_contents(grant.name).unwrap_or(std::slice::from_ref(&grant));
            for item in expanded {
                let name = match item.name {
                    "Chosen Musical Instrument" => self
                        .bard_starting_instrument
                        .as_deref()
                        .unwrap_or(item.name),
                    "Chosen Monk Tool" => self
                        .class_choices
                        .tools
                        .first()
                        .map_or(item.name, String::as_str),
                    _ => item.name,
                };
                let weapon = item.weapon.or_else(|| srd::weapon_rule(name).map(|_| name));
                let key = (name.to_owned(), weapon.map(str::to_owned));
                if let Some((_, quantity)) =
                    merged.iter_mut().find(|(existing, _)| *existing == key)
                {
                    *quantity += item.quantity;
                } else {
                    merged.push((key, item.quantity));
                }
            }
        }
        merged
            .into_iter()
            .map(|((name, weapon), quantity)| {
                let category = if weapon.is_some() {
                    "Weapon"
                } else if srd::armor_rule(&name).is_some() {
                    "Armor"
                } else if name == "Shield" {
                    "Shield"
                } else if ["Arrow", "Bolt", "Firearm Bullet", "Sling Bullet", "Needle"]
                    .contains(&name.as_str())
                {
                    "Ammunition"
                } else {
                    "Gear"
                };
                EquipmentItem {
                    name,
                    quantity,
                    category: category.to_owned(),
                    weapon,
                }
            })
            .collect()
    }

    #[must_use]
    pub fn coins(&self) -> CoinPurse {
        let class_gold = if self.class_equipment_option == "Gold" {
            srd::class_starting_gold(&self.character_class).unwrap_or(0)
        } else {
            srd::class_equipment(&self.character_class, &self.class_equipment_option)
                .map_or(0, |(_, gold)| gold)
        };
        let background_gold = if self.background_equipment_option == "Gold" {
            50
        } else {
            srd::background_equipment(&self.background).map_or(0, |(_, gold)| gold)
        };
        CoinPurse {
            gold: class_gold + background_gold,
            ..CoinPurse::default()
        }
    }

    #[must_use]
    pub fn equipped_armor(&self) -> Option<String> {
        self.inventory()
            .into_iter()
            .find(|item| item.category == "Armor")
            .map(|item| item.name)
    }

    #[must_use]
    pub fn shield_equipped(&self) -> bool {
        self.inventory()
            .iter()
            .any(|item| item.category == "Shield")
    }

    fn is_weapon_proficient(&self, rule: srd::WeaponRule) -> bool {
        let training = srd::class_rule(&self.character_class).map_or("", |class| class.weapons);
        training == "Simple and Martial"
            || rule.category == "Simple"
            || (self.character_class == "Monk"
                && rule.kind == "Melee"
                && rule.properties.contains(&"Light"))
            || (self.character_class == "Rogue"
                && rule
                    .properties
                    .iter()
                    .any(|property| ["Finesse", "Light"].contains(property)))
    }

    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn weapon_attacks(&self) -> Vec<WeaponAttack> {
        self.inventory()
            .into_iter()
            .filter_map(|item| {
                let weapon = item.weapon.as_deref()?;
                let rule = srd::weapon_rule(weapon)?;
                let abilities: &[&str] = if rule.kind == "Ranged" {
                    &["dexterity"]
                } else if rule.properties.contains(&"Finesse") || self.character_class == "Monk" {
                    &["strength", "dexterity"]
                } else {
                    &["strength"]
                };
                let modifier = abilities
                    .iter()
                    .map(|ability| self.abilities.modifier(ability))
                    .max()
                    .unwrap_or(0);
                let mut attack_bonus = modifier
                    + if self.is_weapon_proficient(rule) {
                        i16::from(self.proficiency_bonus())
                    } else {
                        0
                    };
                if self.class_choices.fighting_style.as_deref() == Some("Archery")
                    && rule.kind == "Ranged"
                {
                    attack_bonus += 2;
                }
                let suffix = if modifier == 0 {
                    String::new()
                } else {
                    format!("{modifier:+}")
                };
                let mut notes = Vec::new();
                if item.quantity > 1 {
                    notes.push(format!("Quantity {}", item.quantity));
                }
                if let Some(damage) = rule.versatile_damage {
                    notes.push(format!("Versatile {damage}{suffix}"));
                }
                if self.class_choices.weapon_masteries.contains(weapon) {
                    notes.push(format!("Mastery: {}", rule.mastery));
                }
                if rule.properties.contains(&"Heavy") {
                    let ability = if rule.kind == "Ranged" {
                        self.abilities.dexterity
                    } else {
                        self.abilities.strength
                    };
                    if ability < 13 {
                        notes.push("Heavy: attack rolls have Disadvantage".to_owned());
                    }
                }
                Some(WeaponAttack {
                    name: item.name,
                    attack_bonus,
                    damage: format!("{}{suffix}", rule.damage),
                    damage_type: rule.damage_type.to_owned(),
                    range: rule.long_range.map_or_else(
                        || format!("{} ft.", rule.normal_range),
                        |long| format!("{}/{long} ft.", rule.normal_range),
                    ),
                    properties: rule
                        .properties
                        .iter()
                        .map(|value| (*value).to_owned())
                        .collect(),
                    notes,
                })
            })
            .collect()
    }

    #[must_use]
    pub fn darkvision_range(&self) -> Option<u8> {
        match self.elf_lineage.as_deref() {
            Some("Drow") => Some(120),
            Some("High Elf" | "Wood Elf") => Some(60),
            _ => srd::species_rule(&self.species).and_then(|rule| rule.darkvision_range),
        }
    }

    #[must_use]
    pub fn damage_resistances(&self) -> Vec<String> {
        let mut values = Vec::new();
        if self.species == "Dwarf" {
            values.push("Poison".to_owned());
        }
        if let Some(value) = self
            .dragonborn_ancestry
            .as_deref()
            .and_then(srd::dragonborn_damage_type)
        {
            values.push(value.to_owned());
        }
        if let Some(value) = self
            .tiefling_legacy
            .as_deref()
            .and_then(srd::tiefling_resistance)
        {
            values.push(value.to_owned());
        }
        values.dedup();
        values
    }

    #[must_use]
    pub fn spell_slots(&self) -> Vec<SpellSlotPool> {
        srd::level_one_spell_slots(&self.character_class).map_or_else(
            Vec::new,
            |(level, total, recovery)| {
                vec![SpellSlotPool {
                    level,
                    total,
                    recovery: recovery.to_owned(),
                }]
            },
        )
    }

    fn spellcasting_profile(
        &self,
        source: String,
        ability: &str,
        slots: Vec<SpellSlotPool>,
        free_casts: Vec<String>,
    ) -> SpellcastingProfile {
        let modifier = self.abilities.modifier(ability);
        SpellcastingProfile {
            source,
            ability: ability.to_owned(),
            modifier,
            save_dc: 8 + modifier + i16::from(self.proficiency_bonus()),
            attack_bonus: modifier + i16::from(self.proficiency_bonus()),
            granted_spell_slots: slots,
            free_casts,
        }
    }

    #[must_use]
    pub fn spellcasting_profiles(&self) -> Vec<SpellcastingProfile> {
        let mut profiles = Vec::new();
        if let Some(ability) = srd::class_spellcasting_ability(&self.character_class) {
            profiles.push(self.spellcasting_profile(
                format!("{} Spellcasting", self.character_class),
                ability,
                self.spell_slots(),
                Vec::new(),
            ));
        }
        profiles.extend(self.magic_initiate_choices.iter().map(|choice| {
            self.spellcasting_profile(
                format!("Magic Initiate ({})", choice.spell_list),
                &choice.spellcasting_ability,
                Vec::new(),
                vec![format!(
                    "{}: 1/Long Rest without a spell slot",
                    choice.level_one_spell
                )],
            )
        }));
        let species_ability = self
            .elf_spellcasting_ability
            .as_deref()
            .or(self.gnome_spellcasting_ability.as_deref())
            .or(self.tiefling_spellcasting_ability.as_deref());
        if let Some(ability) = species_ability {
            let source = if let Some(lineage) = &self.elf_lineage {
                format!("Elven Lineage ({lineage})")
            } else if let Some(lineage) = &self.gnome_lineage {
                format!("Gnomish Lineage ({lineage})")
            } else if let Some(legacy) = &self.tiefling_legacy {
                format!("Fiendish Legacy ({legacy})")
            } else {
                "Species Spellcasting".to_owned()
            };
            let free_casts = if self.gnome_lineage.as_deref() == Some("Forest Gnome") {
                vec![format!(
                    "Speak with Animals: {}/Long Rest without a spell slot",
                    self.proficiency_bonus()
                )]
            } else {
                Vec::new()
            };
            profiles.push(self.spellcasting_profile(source, ability, Vec::new(), free_casts));
        }
        profiles
    }

    #[must_use]
    pub fn spellcasting_ability(&self) -> Option<String> {
        self.spellcasting_profiles()
            .first()
            .map(|profile| profile.ability.clone())
    }

    #[must_use]
    pub fn spell_save_dc(&self) -> Option<i16> {
        self.spellcasting_profiles()
            .first()
            .map(|profile| profile.save_dc)
    }

    #[must_use]
    pub fn spell_attack_bonus(&self) -> Option<i16> {
        self.spellcasting_profiles()
            .first()
            .map(|profile| profile.attack_bonus)
    }

    #[must_use]
    pub fn all_cantrips(&self) -> Vec<String> {
        let mut spells = Vec::new();
        let species: Vec<&str> = if let Some(lineage) = self.elf_lineage.as_deref() {
            vec![match lineage {
                "Drow" => "Dancing Lights",
                "High Elf" => "Prestidigitation",
                "Wood Elf" => "Druidcraft",
                _ => "",
            }]
        } else if let Some(lineage) = self.gnome_lineage.as_deref() {
            if lineage == "Forest Gnome" {
                vec!["Minor Illusion"]
            } else {
                vec!["Mending", "Prestidigitation"]
            }
        } else if let Some(legacy) = self.tiefling_legacy.as_deref() {
            vec![srd::tiefling_cantrip(legacy).unwrap_or(""), "Thaumaturgy"]
        } else {
            Vec::new()
        };
        for spell in species
            .into_iter()
            .map(str::to_owned)
            .chain(
                self.magic_initiate_choices
                    .iter()
                    .flat_map(|choice| choice.cantrips.iter().cloned()),
            )
            .chain(self.class_choices.cantrips.iter().cloned())
        {
            if !spell.is_empty() && !spells.contains(&spell) {
                spells.push(spell);
            }
        }
        spells
    }

    #[must_use]
    pub fn all_prepared_spells(&self) -> Vec<String> {
        let mut spells = Vec::new();
        if self.gnome_lineage.as_deref() == Some("Forest Gnome") {
            spells.push("Speak with Animals".to_owned());
        }
        for spell in self
            .magic_initiate_choices
            .iter()
            .map(|choice| choice.level_one_spell.clone())
            .chain(self.class_choices.prepared_spells.iter().cloned())
            .chain(
                srd::class_always_prepared(&self.character_class)
                    .iter()
                    .map(|value| (*value).to_owned()),
            )
        {
            if !spells.contains(&spell) {
                spells.push(spell);
            }
        }
        spells
    }

    #[must_use]
    pub fn spell_table_entries(&self) -> Vec<SpellTableEntry> {
        self.all_cantrips()
            .into_iter()
            .map(|spell| (0, spell))
            .chain(
                self.all_prepared_spells()
                    .into_iter()
                    .map(|spell| (1, spell)),
            )
            .filter_map(|(level, name)| {
                let rule = srd::spell_rule(&name)?;
                Some(SpellTableEntry {
                    level,
                    name,
                    casting_time: rule.casting_time.clone(),
                    range: rule.range.clone(),
                    concentration: rule.concentration,
                    ritual: rule.ritual,
                    required_material: rule.required_material.is_some(),
                    notes: rule.notes.clone(),
                })
            })
            .collect()
    }

    #[must_use]
    pub fn armor_training(&self) -> String {
        if self.class_choices.divine_order.as_deref() == Some("Protector") {
            "Light, Medium, Heavy, Shields".to_owned()
        } else if self.class_choices.primal_order.as_deref() == Some("Warden") {
            "Light, Medium, Shields".to_owned()
        } else {
            srd::class_rule(&self.character_class)
                .map_or("", |rule| rule.armor)
                .to_owned()
        }
    }

    #[must_use]
    pub fn weapon_proficiencies(&self) -> String {
        if self.class_choices.divine_order.as_deref() == Some("Protector")
            || self.class_choices.primal_order.as_deref() == Some("Warden")
        {
            "Simple and Martial".to_owned()
        } else {
            srd::class_rule(&self.character_class)
                .map_or("", |rule| rule.weapons)
                .to_owned()
        }
    }

    #[must_use]
    pub fn all_tool_proficiencies(&self) -> Vec<String> {
        let mut values = vec![
            srd::background_rule(&self.background)
                .map_or("", |rule| rule.tool)
                .to_owned(),
        ];
        for tool in self
            .class_choices
            .tools
            .iter()
            .chain(&self.tool_proficiencies)
        {
            if !values.contains(tool) {
                values.push(tool.clone());
            }
        }
        values
    }

    #[must_use]
    pub fn class_traits(&self) -> Vec<String> {
        let mut traits: Vec<String> = srd::class_features(&self.character_class)
            .iter()
            .map(|value| (*value).to_owned())
            .collect();
        if !self.class_choices.weapon_masteries.is_empty() {
            let selected = self
                .class_choices
                .weapon_masteries
                .iter()
                .map(|weapon| {
                    format!(
                        "{weapon} ({})",
                        srd::weapon_rule(weapon).map_or("", |rule| rule.mastery)
                    )
                })
                .collect::<Vec<_>>()
                .join(", ");
            traits.push(format!("Weapon Mastery: {selected}"));
        }
        if !self.class_choices.tools.is_empty() {
            traits.push(format!(
                "Class Tools: {}",
                self.class_choices
                    .tools
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if !self.class_choices.expertise.is_empty() {
            traits.push(format!(
                "Expertise: {}",
                self.class_choices
                    .expertise
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if let Some(value) = &self.class_choices.fighting_style {
            traits.push(format!("Fighting Style: {value}"));
        }
        if let Some(value) = &self.class_choices.eldritch_invocation {
            traits.push(format!("Eldritch Invocation: {value}"));
        }
        if let Some(value) = &self.class_choices.additional_language {
            traits.push(format!("Thieves' Cant: additional language ({value})"));
        }
        if !self.class_choices.cantrips.is_empty() {
            traits.push(format!(
                "Cantrips: {}",
                self.class_choices
                    .cantrips
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if !self.class_choices.spellbook_spells.is_empty() {
            traits.push(format!(
                "Spellbook: {}",
                self.class_choices
                    .spellbook_spells
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if !self.class_choices.prepared_spells.is_empty() {
            traits.push(format!(
                "Prepared Spells: {}",
                self.class_choices
                    .prepared_spells
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        traits
    }

    #[must_use]
    pub fn species_traits(&self) -> Vec<String> {
        let mut traits: Vec<String> = srd::species_traits(&self.species)
            .iter()
            .map(|value| (*value).to_owned())
            .collect();
        if let Some(value) = &self.dragonborn_ancestry {
            traits.push(format!(
                "Draconic Ancestry: {value} ({})",
                srd::dragonborn_damage_type(value).unwrap_or("")
            ));
        }
        if let Some(value) = &self.elf_lineage {
            traits.push(format!("Elven Lineage: {value}"));
            traits.push(format!(
                "Keen Senses: {}",
                self.elf_keen_senses_skill.as_deref().unwrap_or("")
            ));
        }
        if let Some(value) = &self.gnome_lineage {
            traits.push(format!("Gnomish Lineage: {value}"));
        }
        if let Some(value) = &self.goliath_ancestry {
            traits.push(format!("Giant Ancestry: {value}"));
        }
        if let Some(value) = &self.human_skill {
            traits.push(format!("Skillful: {value}"));
        }
        if let Some(value) = &self.human_origin_feat {
            traits.push(format!("Versatile: {value}"));
        }
        if let Some(value) = &self.tiefling_legacy {
            traits.push(format!("Fiendish Legacy: {value}"));
        }
        if let Some(value) = self.darkvision_range() {
            traits.push(format!("Darkvision: {value} ft."));
        }
        if !self.damage_resistances().is_empty() {
            traits.push(format!(
                "Damage Resistance: {}",
                self.damage_resistances().join(", ")
            ));
        }
        let species_source = ["Elven Lineage", "Gnomish Lineage", "Fiendish Legacy"];
        if let Some(profile) = self.spellcasting_profiles().into_iter().find(|profile| {
            species_source
                .iter()
                .any(|source| profile.source.starts_with(source))
        }) {
            traits.push(profile.summary());
        }
        let species_cantrips: Vec<String> = if self.elf_lineage.is_some()
            || self.gnome_lineage.is_some()
            || self.tiefling_legacy.is_some()
        {
            let class_and_feat: BTreeSet<String> = self
                .class_choices
                .cantrips
                .iter()
                .cloned()
                .chain(
                    self.magic_initiate_choices
                        .iter()
                        .flat_map(|choice| choice.cantrips.iter().cloned()),
                )
                .collect();
            self.all_cantrips()
                .into_iter()
                .filter(|spell| !class_and_feat.contains(spell))
                .collect()
        } else {
            Vec::new()
        };
        if !species_cantrips.is_empty() {
            traits.push(format!("Cantrips: {}", species_cantrips.join(", ")));
        }
        traits
    }

    #[must_use]
    pub fn origin_feat_traits(&self) -> Vec<String> {
        let mut traits = Vec::new();
        let background = srd::background_rule(&self.background);
        if background.is_some_and(|rule| rule.feat == "Alert")
            || self.human_origin_feat.as_deref() == Some("Alert")
        {
            traits.push("Alert: Initiative Proficiency; Initiative Swap".to_owned());
        }
        if background.is_some_and(|rule| rule.feat == "Savage Attacker")
            || self.human_origin_feat.as_deref() == Some("Savage Attacker")
        {
            traits.push("Savage Attacker: roll weapon damage dice twice once per turn".to_owned());
        }
        if !self.skilled_proficiencies.is_empty() {
            traits.push(format!(
                "Skilled: {}",
                self.skilled_proficiencies
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        traits
    }

    #[must_use]
    pub fn class_resources(&self) -> Vec<ClassResource> {
        let resource = match self.character_class.as_str() {
            "Barbarian" => ClassResource {
                name: "Rage".to_owned(),
                maximum: 2,
                unit: "uses".to_owned(),
                detail: Some("+2 Rage damage".to_owned()),
                recovery: "regain 1 on Short Rest; all on Long Rest".to_owned(),
            },
            "Bard" => ClassResource {
                name: "Bardic Inspiration".to_owned(),
                maximum: self.abilities.modifier("charisma").max(1),
                unit: "d6 uses".to_owned(),
                detail: None,
                recovery: "regain all on Long Rest".to_owned(),
            },
            "Fighter" => ClassResource {
                name: "Second Wind".to_owned(),
                maximum: 2,
                unit: "uses".to_owned(),
                detail: Some(format!("heal 1d10+{} HP", self.level)),
                recovery: "regain 1 on Short Rest; all on Long Rest".to_owned(),
            },
            "Paladin" => ClassResource {
                name: "Lay on Hands".to_owned(),
                maximum: i16::from(5 * self.level),
                unit: "HP".to_owned(),
                detail: None,
                recovery: "replenishes on Long Rest".to_owned(),
            },
            "Ranger" => ClassResource {
                name: "Favored Enemy".to_owned(),
                maximum: 2,
                unit: "free Hunter's Mark casts".to_owned(),
                detail: None,
                recovery: "regain all on Long Rest".to_owned(),
            },
            "Sorcerer" => ClassResource {
                name: "Innate Sorcery".to_owned(),
                maximum: 2,
                unit: "uses".to_owned(),
                detail: None,
                recovery: "regain all on Long Rest".to_owned(),
            },
            "Warlock" => ClassResource {
                name: "Pact Magic".to_owned(),
                maximum: 1,
                unit: "level-1 slot".to_owned(),
                detail: None,
                recovery: "regain on Short or Long Rest".to_owned(),
            },
            "Wizard" => ClassResource {
                name: "Arcane Recovery".to_owned(),
                maximum: 1,
                unit: "use".to_owned(),
                detail: Some(format!(
                    "recover {} level(s) of spell slots",
                    self.level.div_ceil(2)
                )),
                recovery: "regain on Long Rest".to_owned(),
            },
            _ => return Vec::new(),
        };
        vec![resource]
    }

    #[must_use]
    pub fn passive_perception(&self) -> i16 {
        10 + self.skill_modifier("Perception")
    }

    /// Serialize the canonical record with stable pretty formatting.
    ///
    /// # Errors
    ///
    /// Returns an error if the record cannot be represented as JSON.
    pub fn to_json(&self) -> Result<String, String> {
        serde_json::to_string_pretty(self)
            .map(|mut value| {
                value.push('\n');
                value
            })
            .map_err(|error| error.to_string())
    }

    #[must_use]
    pub fn proficiency_bonus(&self) -> u8 {
        2 + (self.level - 1) / 4
    }
}

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

    #[test]
    fn derives_combat_values_from_the_canonical_fixture() {
        let character =
            Character::from_json(include_str!("../../fixtures/complete-character.json"))
                .expect("valid fixture");
        assert_eq!(character.hit_points(), 9);
        assert_eq!(character.armor_class(), 14);
        assert_eq!(character.passive_perception(), 12);
    }
}