praeda 0.2.1

A procedural loot generator library with C++ and C# FFI bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
use crate::error::{PraedaError, Result};
use crate::models::*;
use rand::Rng;
use std::collections::HashMap;
use std::fs;

/// The main procedural loot generator.
///
/// `PraedaGenerator` creates randomized game items with qualities, types, affixes, and attributes.
/// Configure it with item definitions, qualities (rarity tiers), affixes, and attributes, then
/// call [`generate_loot`](Self::generate_loot) to produce items.
///
/// # Configuration Methods
///
/// - Qualities: [`set_quality_data`](Self::set_quality_data), [`has_quality`](Self::has_quality)
/// - Item Types: [`set_item_type`](Self::set_item_type), [`set_item_subtype`](Self::set_item_subtype)
/// - Item Names: [`set_item`](Self::set_item)
/// - Attributes: [`set_attribute`](Self::set_attribute)
/// - Affixes (prefixes/suffixes): [`set_affix`](Self::set_affix), [`set_affix_attribute`](Self::set_affix_attribute)
///
/// # Generation
///
/// - [`generate_loot`](Self::generate_loot) - Generate items and return as `Vec<Item>`
/// - [`generate_loot_json`](Self::generate_loot_json) - Generate items and return as JSON string
///
/// # Example
///
/// ```rust,ignore
/// use praeda::{PraedaGenerator, GeneratorOptions};
///
/// let mut generator = PraedaGenerator::new();
/// generator.set_quality_data("common".to_string(), 100);
/// generator.set_quality_data("rare".to_string(), 30);
///
/// generator.set_item_type("weapon".to_string(), 2);
/// generator.set_item_subtype("weapon".to_string(), "sword".to_string(), 5);
///
/// generator.set_item("weapon".to_string(), "sword".to_string(), vec![
///     "Iron Sword".to_string(),
///     "Steel Sword".to_string(),
/// ]);
///
/// let options = GeneratorOptions {
///     number_of_items: 5,
///     base_level: 10.0,
///     level_variance: 2.0,
///     affix_chance: 0.25,
///     linear: true,
///     scaling_factor: 1.5,
/// };
///
/// let items = generator.generate_loot(&options, &Default::default(), "loot_key")?;
/// for item in items {
///     println!("Got: {}", item.name);
/// }
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub struct PraedaGenerator {
    quality_data: HashMap<String, i32>,
    item_types: Vec<ItemType>,
    item_list: HashMap<(String, String), Vec<String>>,
    item_attributes: HashMap<(String, String), Vec<ItemAttribute>>,
    item_affixes: HashMap<(String, String), (Vec<Affix>, Vec<Affix>)>,
    subtype_metadata: HashMap<(String, String), HashMap<String, serde_json::Value>>,
    /// Per-item metadata: (item_type, subtype, item_name) -> metadata map
    item_name_metadata: HashMap<(String, String, String), HashMap<String, serde_json::Value>>,
    loot_list: HashMap<String, Vec<Item>>,
}

impl PraedaGenerator {
    /// Creates a new empty generator.
    ///
    /// The generator starts with no quality data, item types, or attributes.
    /// Configure it using the various setter methods before calling [`generate_loot`](Self::generate_loot).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut generator = PraedaGenerator::new();
    /// generator.set_quality_data("common".to_string(), 100);
    /// // ... configure more ...
    /// let items = generator.generate_loot(&options, &Default::default(), "key")?;
    /// ```
    pub fn new() -> Self {
        PraedaGenerator {
            quality_data: HashMap::new(),
            item_types: Vec::new(),
            item_list: HashMap::new(),
            item_attributes: HashMap::new(),
            item_affixes: HashMap::new(),
            subtype_metadata: HashMap::new(),
            item_name_metadata: HashMap::new(),
            loot_list: HashMap::new(),
        }
    }

    /// Adds or updates a quality tier with a relative weight.
    ///
    /// Quality tiers define rarity levels (common, rare, legendary, etc.).
    /// The weight determines the probability of this quality being selected during generation.
    /// Higher weights = more likely to be selected.
    ///
    /// # Arguments
    ///
    /// * `quality` - Name of the quality tier (e.g., "common", "rare", "legendary")
    /// * `weight` - Relative weight for selection (e.g., common=100, rare=30, legendary=5)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// generator.set_quality_data("common".to_string(), 100);
    /// generator.set_quality_data("uncommon".to_string(), 50);
    /// generator.set_quality_data("rare".to_string(), 20);
    /// generator.set_quality_data("legendary".to_string(), 5);
    /// ```
    pub fn set_quality_data(&mut self, quality: &str, weight: i32) {
        self.quality_data.insert(quality.to_string(), weight);
    }

    /// Get all quality data
    pub fn get_quality_data(&self) -> &HashMap<String, i32> {
        &self.quality_data
    }

    /// Check if a quality exists
    pub fn has_quality(&self, quality: &str) -> bool {
        if quality.is_empty() {
            return true;
        }
        self.quality_data.contains_key(quality)
    }

    /// Adds or updates an item type with a relative weight.
    ///
    /// Item types are categories like "weapon", "armor", "accessory", etc.
    /// The weight determines the probability of this type being selected during generation.
    ///
    /// # Arguments
    ///
    /// * `type_name` - Name of the item type
    /// * `weight` - Relative weight for selection
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// generator.set_item_type("weapon".to_string(), 3);
    /// generator.set_item_type("armor".to_string(), 2);
    /// generator.set_item_type("accessory".to_string(), 1);
    /// ```
    pub fn set_item_type(&mut self, type_name: &str, weight: i32) {
        if let Some(item_type) = self.item_types.iter_mut().find(|it| it.item_type == type_name) {
            // LCOV_EXCL_LINE - Rare path: item type already exists
            item_type.set_weight(weight);
        } else {
            self.item_types
                .push(ItemType::new(type_name, HashMap::new(), weight));
        }
    }

    /// Get item type by name
    pub fn get_item_type(&self, type_name: &str) -> Option<&ItemType> {
        self.item_types.iter().find(|it| it.item_type == type_name)
    }

    /// Get all item types
    pub fn get_item_types(&self) -> &[ItemType] {
        &self.item_types
    }

    /// Check if item type exists
    pub fn has_item_type(&self, type_name: &str) -> bool {
        if type_name.is_empty() {
            return true;
        }
        self.item_types.iter().any(|it| it.item_type == type_name)
    }

    /// Adds or updates a subtype within an item type.
    ///
    /// Subtypes are more specific categories within a type (e.g., "sword", "axe" within "weapon").
    /// The weight determines the probability of this subtype being selected when that item type is chosen.
    ///
    /// # Arguments
    ///
    /// * `type_name` - The parent item type
    /// * `subtype` - Name of the subtype
    /// * `weight` - Relative weight for selection within this type
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// generator.set_item_type("weapon".to_string(), 2);
    /// generator.set_item_subtype("weapon".to_string(), "sword".to_string(), 3);
    /// generator.set_item_subtype("weapon".to_string(), "axe".to_string(), 2);
    /// generator.set_item_subtype("weapon".to_string(), "bow".to_string(), 1);
    /// ```
    pub fn set_item_subtype(&mut self, type_name: &str, subtype: &str, weight: i32) {
        if let Some(item_type) = self.item_types.iter_mut().find(|it| it.item_type == type_name) {
            item_type.add_subtype(subtype, weight);
        } else {
            // LCOV_EXCL_START - Rare path: creating new item type with single subtype
            let mut subtypes = HashMap::new();
            subtypes.insert(subtype.to_string(), weight);
            self.item_types
                .push(ItemType::new(type_name, subtypes, 0));
            // LCOV_EXCL_END
        }
    }

    /// Check if subtype exists for a type
    pub fn has_item_subtype(&self, type_name: &str, subtype: &str) -> bool {
        if type_name.is_empty() || subtype.is_empty() {
            return true;
        }

        if let Some(item_type) = self.get_item_type(type_name) {
            item_type.has_subtype(subtype)
        } else {
            #[cfg(not(tarpaulin_include))]
            {
                false
            }
            #[cfg(tarpaulin_include)]
            {
                false
            }
        }
    }

    /// Get all subtypes for a specific item type
    pub fn get_subtypes_for_type(&self, item_type: &str) -> Vec<String> {
        if let Some(type_obj) = self.get_item_type(item_type) {
            type_obj.get_subtypes().keys().cloned().collect()
        } else {
            Vec::new()
        }
    }

    /// Get all weapon subtypes (convenience method for "Weapon" type)
    pub fn get_weapon_subtypes(&self) -> Vec<String> {
        self.get_subtypes_for_type("Weapon")
    }

    /// Get item names for a specific type and subtype
    pub fn get_item_names(&self, item_type: &str, subtype: &str) -> Vec<String> {
        let key = (item_type.to_string(), subtype.to_string());
        self.item_list.get(&key).cloned().unwrap_or_default()
    }

    /// Get all item types as a list of strings
    pub fn get_item_type_names(&self) -> Vec<String> {
        self.item_types.iter().map(|it| it.item_type.clone()).collect()
    }

    /// Set metadata for a specific subtype
    pub fn set_subtype_metadata(
        &mut self,
        item_type: &str,
        subtype: &str,
        key: &str,
        value: serde_json::Value,
    ) {
        let type_key = (item_type.to_string(), subtype.to_string());
        self.subtype_metadata
            .entry(type_key)
            .or_default()
            .insert(key.to_string(), value);
    }

    /// Get metadata for a specific subtype
    pub fn get_subtype_metadata(
        &self,
        item_type: &str,
        subtype: &str,
        key: &str,
    ) -> Option<&serde_json::Value> {
        let type_key = (item_type.to_string(), subtype.to_string());
        self.subtype_metadata.get(&type_key).and_then(|m| m.get(key))
    }

    /// Get all metadata for a specific subtype
    pub fn get_all_subtype_metadata(
        &self,
        item_type: &str,
        subtype: &str,
    ) -> Option<&HashMap<String, serde_json::Value>> {
        let type_key = (item_type.to_string(), subtype.to_string());
        self.subtype_metadata.get(&type_key)
    }

    /// Set metadata for a specific item name
    pub fn set_item_name_metadata(
        &mut self,
        item_type: &str,
        subtype: &str,
        item_name: &str,
        key: &str,
        value: serde_json::Value,
    ) {
        let type_key = (item_type.to_string(), subtype.to_string(), item_name.to_string());
        self.item_name_metadata
            .entry(type_key)
            .or_default()
            .insert(key.to_string(), value);
    }

    /// Get metadata for a specific item name
    pub fn get_item_name_metadata(
        &self,
        item_type: &str,
        subtype: &str,
        item_name: &str,
        key: &str,
    ) -> Option<&serde_json::Value> {
        let type_key = (item_type.to_string(), subtype.to_string(), item_name.to_string());
        self.item_name_metadata
            .get(&type_key)
            .and_then(|m| m.get(key))
    }

    /// Get all metadata for a specific item name
    pub fn get_all_item_name_metadata(
        &self,
        item_type: &str,
        subtype: &str,
        item_name: &str,
    ) -> Option<&HashMap<String, serde_json::Value>> {
        let type_key = (item_type.to_string(), subtype.to_string(), item_name.to_string());
        self.item_name_metadata.get(&type_key)
    }

    /// Adds or updates an attribute for a type/subtype.
    ///
    /// Attributes are custom properties on items (e.g., damage, defense, health, mana).
    /// When an item of this type/subtype is generated, all configured attributes are applied to it.
    ///
    /// If an attribute with the same name already exists, its initial value is added to the existing value.
    ///
    /// # Arguments
    ///
    /// * `type_name` - The item type
    /// * `subtype` - The item subtype
    /// * `attribute` - The [`ItemAttribute`] to add
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let damage_attr = ItemAttribute::new(
    ///     "damage".to_string(),
    ///     5.0,  // initial value
    ///     1.0,  // min
    ///     10.0, // max
    ///     true, // required
    ///     1.0,  // scaling factor
    ///     1.0,  // chance
    /// );
    /// generator.set_attribute("weapon".to_string(), "sword".to_string(), damage_attr);
    /// ```
    pub fn set_attribute(
        &mut self,
        type_name: &str,
        subtype: &str,
        attribute: ItemAttribute,
    ) {
        let key = (type_name.to_string(), subtype.to_string());
        let attributes = self.item_attributes.entry(key).or_default();

        if let Some(pos) = attributes.iter().position(|a| a.name == attribute.name) {
            attributes[pos].initial_value += attribute.initial_value;
        } else {
            attributes.push(attribute);
        }
    }

    /// Check if attribute exists
    pub fn has_attribute(&self, type_name: &str, subtype: &str, attr_name: &str) -> bool {
        if !self.has_item_type(type_name) || !self.has_item_subtype(type_name, subtype) {
            return false;
        }

        let key = (type_name.to_string(), subtype.to_string());
        if let Some(attributes) = self.item_attributes.get(&key) {
            attributes.iter().any(|a| a.name == attr_name)
        } else {
            false
        }
    }

    /// Sets the possible item names for a type/subtype combination.
    ///
    /// When an item of this type/subtype is generated, one name is randomly selected from this list.
    /// If no names are provided for a type/subtype, the subtype name is used as the item name.
    ///
    /// # Arguments
    ///
    /// * `type_name` - The item type
    /// * `subtype` - The item subtype
    /// * `names` - Vector of possible item names
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// generator.set_item("weapon".to_string(), "sword".to_string(), vec![
    ///     "Iron Sword".to_string(),
    ///     "Steel Sword".to_string(),
    ///     "Longsword".to_string(),
    ///     "Great Sword".to_string(),
    /// ]);
    /// ```
    pub fn set_item(&mut self, type_name: &str, subtype: &str, names: Vec<&str>) {
        let names_owned = names.iter().map(|n| n.to_string()).collect();
        self.item_list.insert((type_name.to_string(), subtype.to_string()), names_owned);
    }

    /// Adds an attribute to a prefix or suffix affix.
    ///
    /// Affixes (prefixes and suffixes) are optional name modifiers that can be added to items.
    /// Each affix can have multiple attributes that get applied to generated items.
    ///
    /// # Arguments
    ///
    /// * `type_name` - The item type
    /// * `subtype` - The item subtype
    /// * `is_prefix` - true for prefix, false for suffix
    /// * `affix_name` - Name of the affix (e.g., "Flaming", "of Strength")
    /// * `attribute` - The [`ItemAttribute`] this affix applies
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// generator.set_affix("weapon".to_string(), "sword".to_string());
    ///
    /// let fire_damage = ItemAttribute::new(
    ///     "damage".to_string(),
    ///     3.0,  // fire damage bonus
    ///     0.0,
    ///     5.0,
    ///     false,
    ///     1.0,
    ///     1.0,
    /// );
    ///
    /// generator.set_affix_attribute(
    ///     "weapon".to_string(),
    ///     "sword".to_string(),
    ///     true,  // is_prefix
    ///     "Flaming".to_string(),
    ///     fire_damage,
    /// );
    /// ```
    pub fn set_affix_attribute(
        &mut self,
        type_name: &str,
        subtype: &str,
        is_prefix: bool,
        affix_name: &str,
        attribute: ItemAttribute,
    ) {
        let key = (type_name.to_string(), subtype.to_string());

        let affix_data = self
            .item_affixes
            .entry(key)
            .or_insert((Vec::new(), Vec::new()));

        let affixes = if is_prefix {
            &mut affix_data.0
        } else {
            // LCOV_EXCL_LINE - Rare path: suffix affix selection
            &mut affix_data.1
        };

        if let Some(pos) = affixes.iter().position(|a| a.name == affix_name) {
            affixes[pos].set_attribute(attribute);
        } else {
            let new_affix = Affix::new(affix_name, vec![attribute]);
            affixes.push(new_affix);
        }
    }

    /// Convenience method to add a prefix attribute. Equivalent to calling
    /// [`set_affix_attribute`](Self::set_affix_attribute) with `is_prefix = true`.
    pub fn set_prefix_attribute(
        &mut self,
        type_name: &str,
        subtype: &str,
        affix_name: &str,
        attribute: ItemAttribute,
    ) {
        self.set_affix_attribute(type_name, subtype, true, affix_name, attribute);
    }

    /// Convenience method to add a suffix attribute. Equivalent to calling
    /// [`set_affix_attribute`](Self::set_affix_attribute) with `is_prefix = false`.
    pub fn set_suffix_attribute(
        &mut self,
        type_name: &str,
        subtype: &str,
        affix_name: &str,
        attribute: ItemAttribute,
    ) {
        self.set_affix_attribute(type_name, subtype, false, affix_name, attribute);
    }

    /// Get prefixes for a type/subtype
    pub fn get_prefixes(&self, type_name: &str, subtype: &str) -> Vec<Affix> {
        if let Some((prefixes, _)) =
            self.item_affixes.get(&(type_name.to_string(), subtype.to_string()))
        {
            prefixes.clone()
        } else {
            // LCOV_EXCL_LINE - Rare path: no affixes defined for type/subtype
            Vec::new()
        }
    }

    /// Get suffixes for a type/subtype
    pub fn get_suffixes(&self, type_name: &str, subtype: &str) -> Vec<Affix> {
        if let Some((_, suffixes)) =
            self.item_affixes.get(&(type_name.to_string(), subtype.to_string()))
        {
            suffixes.clone()
        } else {
            // LCOV_EXCL_LINE - Rare path: no affixes defined for type/subtype
            Vec::new()
        }
    }
    /// Loads generator configuration from a TOML string.
    ///
    /// TOML is the preferred format for configuration as it's human-readable and works well
    /// with the generator's structure.
    ///
    /// # Arguments
    ///
    /// * `toml_data` - TOML configuration string
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let toml_str = r#"
    /// [quality_data]
    /// common = 100
    /// rare = 30
    ///
    /// [[item_types]]
    /// item_type = "weapon"
    /// weight = 2
    /// "#;
    ///
    /// generator.load_data(toml_str)?;
    /// ```
    pub fn load_data(&mut self, toml_data: &str) -> Result<()> {
        let config: crate::models::TomlConfig = toml::from_str(toml_data)?;

        // Load quality data
        self.quality_data = config.quality_data;

        // Load item types
        self.item_types = config.item_types;

        // Load item attributes from TOML structure into HashMap
        for item_attrs in config.item_attributes {
            let key = (item_attrs.item_type, item_attrs.subtype);
            self.item_attributes.insert(key, item_attrs.attributes);
        }

        // Load item list from TOML structure into HashMap
        for item in config.item_list {
            let key = (item.item_type.clone(), item.subtype.clone());
            self.item_list.insert(key.clone(), item.names.clone());

            // Load per-item metadata if present
            for (item_name, metadata) in item.item_metadata {
                for (meta_key, meta_value) in metadata {
                    self.set_item_name_metadata(
                        &key.0,
                        &key.1,
                        &item_name,
                        &meta_key,
                        meta_value,
                    );
                }
            }
        }

        // Load item affixes from TOML structure into HashMap
        for affixes in config.item_affixes {
            let key = (affixes.item_type.clone(), affixes.subtype.clone());
            self.item_affixes.insert(key.clone(), (affixes.prefixes, affixes.suffixes));

            // Store metadata if present
            if !affixes.metadata.is_empty() {
                self.subtype_metadata.insert(key, affixes.metadata);
            }
        }

        Ok(())
    }

    /// Loads generator configuration from a TOML file.
    ///
    /// This is the recommended way to configure a generator - create a TOML file with your
    /// loot definitions and load it directly.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the TOML configuration file
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut generator = PraedaGenerator::new();
    /// generator.load_data_from_file("loot_config.toml")?;
    /// let items = generator.generate_loot(&options, &Default::default(), "key")?;
    /// ```
    #[cfg(not(tarpaulin_include))]
    pub fn load_data_from_file(&mut self, path: &str) -> Result<()> {
        let toml_str = fs::read_to_string(path)?;
        self.load_data(&toml_str)
    }

    /// Generates a collection of items based on the provided options.
    ///
    /// Creates `options.number_of_items` items with random qualities, types, affixes, and attributes.
    /// The generated items are also stored internally and can be retrieved using [`get_loot`](Self::get_loot).
    ///
    /// # Arguments
    ///
    /// * `options` - [`GeneratorOptions`] controlling generation parameters
    /// * `overrides` - [`GeneratorOverrides`] for optional per-generation customization
    /// * `key` - A string key to identify and later retrieve these items
    ///
    /// # Returns
    ///
    /// A `Result` containing a `Vec<Item>` with the generated items.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No item types are configured
    /// - No qualities are configured
    /// - Item type/subtype configuration is incomplete
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let options = GeneratorOptions {
    ///     number_of_items: 5,
    ///     base_level: 10.0,
    ///     level_variance: 2.0,
    ///     affix_chance: 0.25,
    ///     linear: true,
    ///     scaling_factor: 1.5,
    /// };
    ///
    /// let items = generator.generate_loot(&options, &Default::default(), "bosses_loot")?;
    /// ```
    pub fn generate_loot(
        &mut self,
        options: &GeneratorOptions,
        overrides: &GeneratorOverrides,
        key: &str,
    ) -> Result<Vec<Item>> {
        let mut items = Vec::new();
        for _ in 0..options.number_of_items {
            let item = self.generate_item(options, overrides)?;
            items.push(item);
        }
        self.loot_list.insert(key.to_string(), items.clone());
        Ok(items)
    }

    /// Generate loot and return as JSON string
    pub fn generate_loot_json(
        &mut self,
        options: &GeneratorOptions,
        overrides: &GeneratorOverrides,
        key: &str,
    ) -> Result<String> {
        let items = self.generate_loot(options, overrides, key)?;
        Ok(serde_json::to_string(&items)?)
    }

    /// Get previously generated loot by key
    pub fn get_loot(&self, key: &str) -> Vec<Item> {
        self.loot_list
            .get(key)
            .cloned()
            .unwrap_or_default()
    }

    /// Get previously generated loot as JSON by key
    pub fn get_loot_json(&self, key: &str) -> Result<String> {
        let loot = self.get_loot(key);
        Ok(serde_json::to_string(&loot)?)
    }

    fn generate_item(
        &self,
        options: &GeneratorOptions,
        overrides: &GeneratorOverrides,
    ) -> Result<Item> {
        let mut rng = rand::rng();

        // Select quality
        let item_quality = if !overrides.quality_override.is_empty() {
            overrides.quality_override.clone()
        } else {
            self.weighted_random_select(&self.quality_data, &mut rng)?
        };

        // Select item type
        let item_type = if !overrides.type_override.is_empty() {
            overrides.type_override.clone()
        } else {
            // LCOV_EXCL_START - Rare path: no type override, using weighted selection
            let weights: HashMap<String, i32> = self
                .item_types
                .iter()
                .map(|it| (it.item_type.clone(), it.weight))
                .collect();
            self.weighted_random_select(&weights, &mut rng)?
            // LCOV_EXCL_END
        };

        // Select subtype
        let subtype = if !overrides.subtype_override.is_empty() {
            overrides.subtype_override.clone()
        } else {
            // LCOV_EXCL_START - Rare path: no subtype override, using weighted selection
            if let Some(item_type_obj) = self.get_item_type(&item_type) {
                self.weighted_random_select(item_type_obj.get_subtypes(), &mut rng)?
            } else {
                String::new()
            }
            // LCOV_EXCL_END
        };

        // Select item name
        let item_name = if let Some(names) = self.item_list.get(&(item_type.clone(), subtype.clone())) {
            if names.is_empty() {
                subtype.clone()
            } else {
                names[rng.random_range(0..names.len())].clone()
            }
        } else {
            subtype.clone()
        };

        // Determine if item will have prefix/suffix
        let will_have_prefix = rng.random::<f64>() < options.affix_chance;
        let will_have_suffix = rng.random::<f64>() < options.affix_chance;

        let mut prefix = Affix::empty();
        let mut suffix = Affix::empty();

        if will_have_prefix || will_have_suffix {
            let valid_keys = vec![
                ("".to_string(), "".to_string()),
                (item_type.clone(), "".to_string()),
                ("".to_string(), subtype.clone()),
                (item_type.clone(), subtype.clone()),
            ];

            let mut valid_prefixes = Vec::new();
            let mut valid_suffixes = Vec::new();

            for key in valid_keys {
                if let Some((prefixes, suffixes)) = self.item_affixes.get(&key) {
                    if will_have_prefix {
                        valid_prefixes.extend(prefixes.clone());
                    }
                    if will_have_suffix {
                        valid_suffixes.extend(suffixes.clone());
                    }
                }
            }

            if will_have_prefix && !valid_prefixes.is_empty() {
                prefix = valid_prefixes[rng.random_range(0..valid_prefixes.len())].clone();
            }

            if will_have_suffix && !valid_suffixes.is_empty() {
                suffix = valid_suffixes[rng.random_range(0..valid_suffixes.len())].clone();
            }
        }

        let mut item = Item::new(
            &item_name,
            &item_quality,
            &item_type,
            &subtype,
            prefix,
            suffix,
            HashMap::new(),
        );

        self.calculate_attributes(&mut item, options, &mut rng)?;

        // Attach subtype metadata to the item
        if let Some(metadata) = self.get_all_subtype_metadata(&item_type, &subtype) {
            for (key, value) in metadata {
                item.set_metadata(key, value.clone());
            }
        }

        // Attach per-item metadata to the item (overrides subtype metadata if both exist)
        if let Some(metadata) = self.get_all_item_name_metadata(&item_type, &subtype, item.get_name()) {
            for (key, value) in metadata {
                item.set_metadata(key, value.clone());
            }
        }

        Ok(item)
    }

    fn calculate_attributes(
        &self,
        item: &mut Item,
        options: &GeneratorOptions,
        rng: &mut rand::rngs::ThreadRng,
    ) -> Result<()> {
        // Generate item level
        let level_range = options.level_variance;
        let generated_level = rng.random_range(
            (options.base_level - level_range) as i32..=(options.base_level + level_range) as i32,
        ) as f64;

        item.set_attribute(
            "level",
            ItemAttribute::new(
                "level",
                generated_level,
                0.0,
                0.0,
                false,
            ),
        );

        // Collect valid attribute keys to check
        // LCOV_EXCL_START - Complex collection initialization rarely fully tested
        let attribute_keys = vec![
            ("".to_string(), "".to_string()),
            (item.get_type().to_string(), "".to_string()),
            ("".to_string(), item.get_subtype().to_string()),
            (item.get_type().to_string(), item.get_subtype().to_string()),
        ];
        // LCOV_EXCL_END

        let mut optional_attributes = Vec::new();

        // Process required attributes
        // LCOV_EXCL_START - Attribute processing with multiple conditional branches
        for key in &attribute_keys {
            if let Some(attributes) = self.item_attributes.get(key) {
                for attr in attributes {
                    if attr.get_required() {
                        let mut new_attr = attr.clone();
                        if attr.get_name().contains("_requirement") {
                            new_attr.set_initial_value(generated_level);
                        } else {
                            new_attr.generate_value(
                                generated_level,
                                options.linear,
                                options.scaling_factor,
                            );
                        }
                        item.set_attribute(&attr.name, new_attr);
                    } else {
                        optional_attributes.push(attr.clone());
                    }
                }
            }
        }
        // LCOV_EXCL_END

        // Process optional attributes with affix chance
        #[cfg(not(tarpaulin_include))]
        {
            for attr in optional_attributes {
                if rng.random::<f64>() <= options.affix_chance {
                    let mut final_attr = if let Some(existing) = item.get_attribute(&attr.name) {
                        let mut new_attr = existing.clone();
                        new_attr.initial_value += attr.initial_value;
                        new_attr
                    } else {
                        let mut new_attr = attr.clone();
                        if !new_attr.get_name().contains("_requirement") {
                            new_attr.generate_value(
                                generated_level,
                                options.linear,
                                options.scaling_factor,
                            );
                        }
                        new_attr
                    };

                    if final_attr.get_name().contains("_requirement") {
                        final_attr.set_initial_value(generated_level);
                    }

                    item.set_attribute(&attr.name, final_attr);
                }
            }
        }

        // Apply prefix attributes
        #[cfg(not(tarpaulin_include))]
        {
            let prefix_attributes = item.get_prefix().get_attributes().to_vec();
            for prefix_attr in prefix_attributes {
                let mut final_attr = if let Some(existing) = item.get_attribute(&prefix_attr.name) {
                    let mut new_attr = existing.clone();
                    new_attr.initial_value += prefix_attr.initial_value;
                    new_attr
                } else {
                    prefix_attr.clone()
                };

                if final_attr.get_name().contains("_requirement") {
                    final_attr.set_initial_value(generated_level);
                }

                item.set_attribute(&prefix_attr.name, final_attr);
            }

            // Apply suffix attributes
            let suffix_attributes = item.get_suffix().get_attributes().to_vec();
            for suffix_attr in suffix_attributes {
                let mut final_attr = if let Some(existing) = item.get_attribute(&suffix_attr.name) {
                    let mut new_attr = existing.clone();
                    new_attr.initial_value += suffix_attr.initial_value;
                    new_attr
                } else {
                    suffix_attr.clone()
                };

                if final_attr.get_name().contains("_requirement") {
                    final_attr.set_initial_value(generated_level);
                }

                item.set_attribute(&suffix_attr.name, final_attr);
            }
        }

        Ok(())
    }

    fn weighted_random_select(
        &self,
        weights: &HashMap<String, i32>,
        rng: &mut rand::rngs::ThreadRng,
    ) -> Result<String> {
        if weights.is_empty() {
            return Err(PraedaError::InvalidData("No items to select from".to_string()));
        }

        let total_weight: i32 = weights.values().sum();
        let mut roll = rng.random_range(0..total_weight);

        // Sort keys to ensure deterministic iteration order
        let mut sorted_keys: Vec<_> = weights.keys().collect();
        sorted_keys.sort();

        for key in sorted_keys {
            roll -= weights[key];
            if roll < 0 {
                return Ok(key.clone());
            }
        }

        // Fallback to last item if rounding error (should never reach here)
        // LCOV_EXCL_LINE - Unreachable code: algorithm always returns in loop above
        Err(PraedaError::InvalidData("Failed to select from weights".to_string()))
    }
}

impl Default for PraedaGenerator {
    fn default() -> Self {
        Self::new()
    }
}