bl4 0.8.4

Borderlands 4 save editor library - encryption, decryption, and parsing
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
//! Manifest data for Borderlands 4 items
//!
//! Provides lookup functions for part names, category names, manufacturers, etc.
//! Data is embedded at compile time from share/manifest/ files.
//!
//! Parts and category names are stored as TSV (tab-separated values).
//! Manufacturers and weapon types remain JSON (hand-curated reference data).

use once_cell::sync::Lazy;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};

// Embed manifest files at compile time
const CATEGORY_NAMES_TSV: &str = include_str!(concat!(env!("OUT_DIR"), "/category_names.tsv"));
const PARTS_DATABASE_TSV: &str = include_str!(concat!(env!("OUT_DIR"), "/parts_database.tsv"));
const MANUFACTURERS_JSON: &str = include_str!(concat!(env!("OUT_DIR"), "/manufacturers.json"));
const WEAPON_TYPES_JSON: &str = include_str!(concat!(env!("OUT_DIR"), "/weapon_types.json"));
const DROP_POOLS_TSV: &str = include_str!(concat!(env!("OUT_DIR"), "/drop_pools.tsv"));
const PART_POOLS_TSV: &str = include_str!(concat!(env!("OUT_DIR"), "/part_pools.tsv"));
const BOSS_REPLAY_COSTS_TSV: &str =
    include_str!(concat!(env!("OUT_DIR"), "/table_bossreplay_costs.tsv"));
const ITEM_NAMES_TSV: &str = include_str!(concat!(env!("OUT_DIR"), "/item_names.tsv"));

// ============================================================================
// Data Structures (JSON-based reference data only)
// ============================================================================

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct Manufacturer {
    code: String,
    name: String,
    #[serde(default)]
    path: Option<String>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct WeaponType {
    name: String,
    #[serde(default)]
    manufacturers: Vec<Manufacturer>,
}

// ============================================================================
// Parsed Data (Lazy Initialized)
// ============================================================================

/// Category ID -> Category Name (parsed from TSV)
static CATEGORY_NAMES: Lazy<HashMap<i64, String>> =
    Lazy::new(|| parse_tsv_pairs(CATEGORY_NAMES_TSV));

/// (Category, Index) -> (Part Name, Slot) parsed from TSV
static PARTS_BY_ID: Lazy<HashMap<(i64, i64), (String, String)>> =
    Lazy::new(|| parse_tsv_parts(PARTS_DATABASE_TSV));

/// (Category, Normalized Part Name) -> Index (reverse lookup)
static PARTS_BY_NAME: Lazy<HashMap<(i64, String), i64>> = Lazy::new(|| {
    PARTS_BY_ID
        .iter()
        .map(|(&(cat, idx), (name, _))| {
            let bare = normalize_part_name(name).to_string();
            ((cat, bare), idx)
        })
        .collect()
});

fn parse_tsv_pairs(tsv: &str) -> HashMap<i64, String> {
    tsv.lines()
        .skip(1)
        .filter_map(|line| {
            let mut cols = line.splitn(2, '\t');
            let id = cols.next()?.parse::<i64>().ok()?;
            let name = cols.next()?.to_string();
            Some((id, name))
        })
        .collect()
}

fn parse_tsv_parts(tsv: &str) -> HashMap<(i64, i64), (String, String)> {
    tsv.lines()
        .skip(1)
        .filter_map(|line| {
            let mut cols = line.splitn(4, '\t');
            let category = cols.next()?.parse::<i64>().ok()?;
            let index = cols.next()?.parse::<i64>().ok()?;
            let name = cols.next()?.to_string();
            let slot = cols.next().unwrap_or("unknown").to_string();
            Some(((category, index), (name, slot)))
        })
        .collect()
}

/// Drop pool data for legendary items per (manufacturer, gear_type) pair
#[derive(Debug, Clone)]
pub struct DropPool {
    pub manufacturer_code: String,
    pub gear_type_code: String,
    pub legendary_count: u32,
    pub boss_source_count: u32,
    pub world_pool_name: String,
}

/// (ManufacturerCode, GearTypeCode) -> DropPool
static DROP_POOLS: Lazy<HashMap<(String, String), DropPool>> = Lazy::new(|| {
    DROP_POOLS_TSV
        .lines()
        .skip(1)
        .filter_map(|line| {
            let cols: Vec<&str> = line.splitn(5, '\t').collect();
            if cols.len() < 5 {
                return None;
            }
            let pool = DropPool {
                manufacturer_code: cols[0].to_string(),
                gear_type_code: cols[1].to_string(),
                legendary_count: cols[2].parse().ok()?,
                boss_source_count: cols[3].parse().ok()?,
                world_pool_name: cols[4].to_string(),
            };
            Some(((cols[0].to_string(), cols[1].to_string()), pool))
        })
        .collect()
});

/// Internal boss name -> display name (parsed from boss replay costs TSV)
static BOSS_NAMES: Lazy<HashMap<String, String>> = Lazy::new(|| {
    let mut names = HashMap::new();
    for line in BOSS_REPLAY_COSTS_TSV.lines().skip(1) {
        let cols: Vec<&str> = line.splitn(5, '\t').collect();
        if cols.len() < 2 {
            continue;
        }
        let row_name = cols[0];
        let comment = cols[1];
        // Parse comment: "Table_BossReplay_Costs, <UUID>, <DisplayName>"
        if let Some(display_name) = parse_boss_comment(comment) {
            names.insert(row_name.to_string(), display_name.to_string());
        }
    }
    names
});

fn parse_boss_comment(comment: &str) -> Option<&str> {
    if comment.is_empty() {
        return None;
    }
    let mut parts = comment.splitn(3, ", ");
    let _table = parts.next()?;
    let uuid = parts.next()?;
    if uuid.len() != 32 || !uuid.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    parts.next()
}

/// Strip manufacturer prefix from a part name.
///
/// `"DAD_PS.part_barrel_01"` → `"part_barrel_01"`, `"part_body"` → `"part_body"`
fn normalize_part_name(name: &str) -> &str {
    name.split('.').next_back().unwrap_or(name)
}

/// Category ID -> Set of normalized part names known in that category's pool
static PART_POOL_MEMBERS: Lazy<HashMap<i64, HashSet<String>>> = Lazy::new(|| {
    let mut pools: HashMap<i64, HashSet<String>> = HashMap::new();
    for line in PART_POOLS_TSV.lines().skip(1) {
        let mut cols = line.splitn(2, '\t');
        let Some(cat) = cols.next().and_then(|s| s.parse::<i64>().ok()) else {
            continue;
        };
        let Some(name) = cols.next() else { continue };
        pools
            .entry(cat)
            .or_default()
            .insert(normalize_part_name(name).to_string());
    }
    pools
});

/// Manufacturer Code -> Full Name
static MANUFACTURERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
    let mfrs: HashMap<String, Manufacturer> =
        serde_json::from_str(MANUFACTURERS_JSON).expect("Failed to parse manufacturers.json");

    mfrs.into_iter().map(|(code, m)| (code, m.name)).collect()
});

/// Weapon Type Name -> Manufacturer Codes
static WEAPON_TYPES: Lazy<HashMap<String, Vec<String>>> = Lazy::new(|| {
    let types: HashMap<String, WeaponType> =
        serde_json::from_str(WEAPON_TYPES_JSON).expect("Failed to parse weapon_types.json");

    types
        .into_iter()
        .map(|(name, wt)| {
            let codes: Vec<String> = wt.manufacturers.into_iter().map(|m| m.code).collect();
            (name, codes)
        })
        .collect()
});

/// NCS naming key (np_*) -> Display name
static ITEM_NAMES: Lazy<HashMap<String, String>> = Lazy::new(|| {
    ITEM_NAMES_TSV
        .lines()
        .filter_map(|line| {
            let mut cols = line.splitn(2, '\t');
            let key = cols.next()?.to_string();
            let name = cols.next()?.to_string();
            Some((key, name))
        })
        .collect()
});

// ============================================================================
// Public API
// ============================================================================

/// Get the name of a category by ID
pub fn category_name(category_id: i64) -> Option<&'static str> {
    CATEGORY_NAMES.get(&category_id).map(|s| s.as_str())
}

/// Get a part name by category and index
pub fn part_name(category: i64, index: i64) -> Option<&'static str> {
    PARTS_BY_ID
        .get(&(category, index))
        .map(|(name, _)| name.as_str())
}

/// Get the slot (vertical) name for a part by category and index
pub fn part_slot(category: i64, index: i64) -> Option<&'static str> {
    PARTS_BY_ID
        .get(&(category, index))
        .map(|(_, slot)| slot.as_str())
}

/// Get a manufacturer's full name from its code
pub fn manufacturer_name(code: &str) -> Option<&'static str> {
    MANUFACTURERS.get(code).map(|s| s.as_str())
}

/// Get drop pool data for a (manufacturer, gear_type) pair
pub fn drop_pool(manufacturer_code: &str, gear_type_code: &str) -> Option<&'static DropPool> {
    DROP_POOLS.get(&(manufacturer_code.to_string(), gear_type_code.to_string()))
}

/// Check if a part name exists in the known pool for a category.
///
/// Names are normalized (manufacturer prefix stripped) before comparison.
/// Returns `None` if the category has no pool data, `Some(bool)` otherwise.
pub fn is_part_in_pool(category: i64, name: &str) -> Option<bool> {
    let pool = PART_POOL_MEMBERS.get(&category)?;
    Some(pool.contains(normalize_part_name(name)))
}

/// Get the total number of legendaries in a world drop pool (e.g., all "Pistols")
pub fn world_pool_legendary_count(world_pool_name: &str) -> u32 {
    DROP_POOLS
        .values()
        .filter(|p| p.world_pool_name == world_pool_name)
        .map(|p| p.legendary_count)
        .sum()
}

/// Get the display name for a boss by its internal name
pub fn boss_display_name(internal_name: &str) -> Option<&'static str> {
    BOSS_NAMES.get(internal_name).map(|s| s.as_str())
}

/// Get all boss name mappings (internal_name -> display_name)
pub fn all_boss_names() -> &'static HashMap<String, String> {
    &BOSS_NAMES
}

/// Look up an item display name by its NCS naming key (e.g., "np_anarchy" → "Anarchy")
pub fn item_display_name(np_key: &str) -> Option<&'static str> {
    ITEM_NAMES.get(np_key).map(|s| s.as_str())
}

/// Resolve an item display name from a part name and category.
///
/// Tries multiple strategies to derive the NCS naming key:
/// 1. Legendary comp: `comp_05_legendary_anarchy` → `np_anarchy`
/// 2. Unique barrel: `part_barrel_01_anarchy` → `np_anarchy`
/// 3. Generic barrel: `part_barrel_01` + category 3 (Jakobs Pistol) → `np_weap_jak_ps_b01`
pub fn item_name_from_part(part_name: &str, category: Option<i64>) -> Option<&'static str> {
    // Strategy 1: Legendary comp part (comp_05_legendary_<suffix>)
    if let Some(suffix) = part_name.strip_prefix("comp_05_legendary_") {
        let key = format!("np_{}", suffix.to_lowercase());
        if let Some(name) = item_display_name(&key) {
            return Some(name);
        }
    }

    // Strategy 2: Unique barrel (part_barrel_NN_<suffix> where suffix isn't just digits)
    if let Some(after_barrel) = part_name.strip_prefix("part_barrel_") {
        if let Some(pos) = after_barrel.find('_') {
            let suffix = &after_barrel[pos + 1..];
            // Skip single-letter sub-variants (a, b, c, d)
            if suffix.len() > 1 && !suffix.chars().all(|c| c.is_ascii_digit()) {
                let key = format!("np_{}", suffix.to_lowercase());
                if let Some(name) = item_display_name(&key) {
                    return Some(name);
                }
            }
        }

        // Strategy 3: Generic barrel via category → NCS prefix
        if let Some(cat) = category {
            if let Some(ncs_prefix) = category_ncs_prefix(cat) {
                let barrel_num = if after_barrel == "01" || after_barrel == "02" {
                    after_barrel
                } else {
                    let num_end = after_barrel.find('_').unwrap_or(after_barrel.len());
                    &after_barrel[..num_end]
                };
                if !barrel_num.is_empty() && barrel_num.chars().all(|c| c.is_ascii_digit()) {
                    let key = format!("np_weap_{}_b{}", ncs_prefix, barrel_num);
                    if let Some(name) = item_display_name(&key) {
                        return Some(name);
                    }
                }
            }
        }
    }

    None
}

/// Map category IDs to NCS manufacturer+type prefix codes.
///
/// These are the codes used in NCS naming keys like `np_weap_jak_ps_b01`.
fn category_ncs_prefix(category: i64) -> Option<&'static str> {
    match category {
        // Shotguns
        7 => Some("bor_sg"),
        8 => Some("dad_sg"),
        9 => Some("jak_sg"),
        10 => Some("mal_sg"),
        11 => Some("ted_sg"),
        12 => Some("tor_sg"),
        // Pistols
        2 => Some("dad_ps"),
        3 => Some("jak_ps"),
        4 => Some("ord_ps"),
        5 => Some("ted_ps"),
        6 => Some("tor_ps"),
        // ARs
        13 => Some("dad_ar"),
        14 => Some("ted_ar"),
        15 => Some("ord_ar"),
        17 => Some("tor_ar"),
        18 => Some("vla_ar"),
        27 => Some("jak_ar"),
        // Snipers
        16 => Some("vla_sr"),
        23 => Some("bor_sr"),
        24 => Some("jak_sr"),
        25 => Some("mal_sr"),
        26 => Some("ord_sr"),
        // SMGs
        19 => Some("bor_sm"),
        20 => Some("dad_sm"),
        21 => Some("mal_sm"),
        22 => Some("vla_sm"),
        _ => None,
    }
}

/// Get all item name mappings
pub fn all_item_names() -> &'static HashMap<String, String> {
    &ITEM_NAMES
}

/// Get all manufacturer codes for a weapon type
pub fn weapon_type_manufacturers(weapon_type: &str) -> Option<&'static [String]> {
    WEAPON_TYPES.get(weapon_type).map(|v| v.as_slice())
}

/// Get all category IDs and names
pub fn all_categories() -> impl Iterator<Item = (i64, &'static str)> {
    CATEGORY_NAMES.iter().map(|(&id, name)| (id, name.as_str()))
}

/// Get all manufacturer codes and names
pub fn all_manufacturers() -> impl Iterator<Item = (&'static str, &'static str)> {
    MANUFACTURERS
        .iter()
        .map(|(code, name)| (code.as_str(), name.as_str()))
}

/// Known slot prefixes for `part_*` names, ordered longest-first for matching.
const SLOT_PREFIXES: &[&str] = &[
    "secondary_elem",
    "secondary_ammo",
    "body_element",
    "body_armor",
    "body_bolt",
    "body_energy",
    "body_mag",
    "barrel",
    "body",
    "firmware",
    "foregrip",
    "grip",
    "mag",
    "multi",
    "passive",
    "scope",
    "secondary",
    "shield",
    "stat2",
    "stat3",
    "stat",
    "underbarrel",
    "unique",
];

/// Extract slot name from a manifest part name.
///
/// Matches against known slot prefixes after stripping manufacturer prefix
/// and `part_`. For `comp_*` / `base_comp_*` parts, returns `"rarity"`.
/// For bare element names (fire, cryo, etc.), returns `"element"`.
///
/// Examples:
/// - `"DAD_PS.part_barrel_02_finnty"` → `"barrel"`
/// - `"part_stat2_wt_ps_equipspeed"` → `"stat2"`
/// - `"part_body_b"` → `"body"`
/// - `"comp_05_legendary_stopgap"` → `"rarity"`
/// - `"radiation"` → `"element"`
pub fn slot_from_part_name(name: &str) -> &'static str {
    let segment = name.split('.').next_back().unwrap_or(name);

    if segment.starts_with("comp_") || segment.starts_with("base_comp_") {
        return "rarity";
    }

    match segment {
        "fire" | "cryo" | "shock" | "corrosive" | "radiation" | "sonic" => return "element",
        _ => {}
    }

    if segment.starts_with("exosoldier_") {
        return "class_mod";
    }

    let stripped = match segment.strip_prefix("part_") {
        Some(rest) => rest,
        None => return "unknown",
    };

    for prefix in SLOT_PREFIXES {
        if let Some(rest) = stripped.strip_prefix(prefix) {
            if rest.is_empty() || rest.starts_with('_') {
                return prefix;
            }
        }
    }

    "unknown"
}

/// Category ID -> Maximum known part index in that category
static MAX_PART_INDEX: Lazy<HashMap<i64, i64>> = Lazy::new(|| {
    let mut max_by_cat: HashMap<i64, i64> = HashMap::new();
    for &(cat, idx) in PARTS_BY_ID.keys() {
        let entry = max_by_cat.entry(cat).or_insert(0);
        if idx > *entry {
            *entry = idx;
        }
    }
    max_by_cat
});

/// Get the maximum known part index for a category.
/// Returns None if the category has no parts in the manifest.
pub fn max_part_index(category: i64) -> Option<i64> {
    MAX_PART_INDEX.get(&category).copied()
}

/// Shared vertical category IDs for fallback part lookup.
///
/// When a part index doesn't resolve in the item's per-category parts,
/// it may belong to a shared vertical (stat mods, barrels, grips, etc.)
/// that uses the same index space across multiple item categories.
pub const SHARED_VERTICAL_CATEGORIES: &[i64] = &[
    10001, // stat_group2 (176-247) + barrel pool (1-94)
    10002, // stat_group3 (104-175) + barrel_acc (61-78)
    10003, // rarity_component (1-541) + tediore_acc (9-55)
    10004, // firmware (27-248) + foregrip (21-82)
    10005, // barrel pool alt (1-94) + grip (42-83)
    10006, // barrel_acc alt (1-78) + magazine (1-87)
    10007, // magazine_acc (27-89) + tediore_acc (9-55)
    10008, // foregrip alt (21-82) + tediore_secondary_acc (14-17)
    10009, // grip alt (42-83) + secondary_ammo (61-64)
    1,     // base shared parts (rarity, elements, secondary elements)
];

/// Get a part's index by category and name (reverse lookup).
///
/// Tries the item's own category first, then falls back to shared
/// vertical categories. Names are normalized (manufacturer prefix stripped).
pub fn part_index(category: i64, name: &str) -> Option<i64> {
    let bare = normalize_part_name(name).to_string();
    if let Some(&idx) = PARTS_BY_NAME.get(&(category, bare.clone())) {
        return Some(idx);
    }
    for &shared_cat in SHARED_VERTICAL_CATEGORIES {
        if shared_cat == category {
            continue;
        }
        if let Some(&idx) = PARTS_BY_NAME.get(&(shared_cat, bare.clone())) {
            return Some(idx);
        }
    }
    None
}

/// Get the number of known parts for a category.
pub fn category_part_count(category: i64) -> usize {
    PARTS_BY_ID
        .keys()
        .filter(|(cat, _)| *cat == category)
        .count()
}

/// Find a legendary barrel alias in per-category NCS metadata.
///
/// Some legendaries (e.g., Seventh Sense) use a generic barrel in their serial
/// encoding but have a legendary-specific entry in the per-category NCS data.
/// Given category 3 and `barrel_base = "barrel_01"`, this finds
/// `"part_barrel_01_seventh_sense"` at NCS index 80.
///
/// Returns None if no legendary alias exists for the given barrel base.
pub fn legendary_barrel_alias(category: i64, barrel_base: &str) -> Option<&'static str> {
    let target_prefix = format!("part_{}_", barrel_base);
    PARTS_BY_ID
        .iter()
        .filter(|(&(cat, _), _)| cat == category)
        .find_map(|(&(_, _), (name, _))| {
            if name.starts_with(&target_prefix) && name.len() > target_prefix.len() {
                let suffix = &name[target_prefix.len()..];
                // Skip single-letter sub-variants (a, b, c, d)
                if suffix.len() == 1 && suffix.chars().all(|c| c.is_ascii_lowercase()) {
                    None
                } else {
                    Some(name.as_str())
                }
            } else {
                None
            }
        })
}

/// Check if manifest data is loaded (forces initialization)
pub fn is_loaded() -> bool {
    // Access lazy statics to force initialization
    let _ = CATEGORY_NAMES.len();
    let _ = PARTS_BY_ID.len();
    let _ = MANUFACTURERS.len();
    true
}

/// Get statistics about loaded manifest data
pub fn stats() -> ManifestStats {
    ManifestStats {
        categories: CATEGORY_NAMES.len(),
        parts: PARTS_BY_ID.len(),
        manufacturers: MANUFACTURERS.len(),
        weapon_types: WEAPON_TYPES.len(),
    }
}

#[derive(Debug, Clone)]
pub struct ManifestStats {
    pub categories: usize,
    pub parts: usize,
    pub manufacturers: usize,
    pub weapon_types: usize,
}

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

    #[test]
    fn test_category_name() {
        // Should find known categories
        assert!(category_name(2).is_some()); // Daedalus Pistol
        assert!(category_name(9).is_some()); // Jakobs Shotgun
    }

    #[test]
    fn test_part_name() {
        // This depends on having actual parts in the database
        // Just verify it doesn't panic
        let _ = part_name(2, 1);
    }

    #[test]
    fn test_manufacturer_name() {
        assert_eq!(manufacturer_name("JAK"), Some("Jakobs"));
        assert_eq!(manufacturer_name("TOR"), Some("Torgue"));
        assert_eq!(manufacturer_name("BOR"), Some("Ripper")); // NCS NexusSerialized: BOR = Ripper
        assert_eq!(manufacturer_name("XXX"), None);
    }

    #[test]
    fn test_stats() {
        let s = stats();
        assert!(s.categories > 0);
        // Parts database may be empty until populated via NCS extraction
        // assert!(s.parts > 0);
        assert!(s.manufacturers > 0);
    }

    #[test]
    fn test_weapon_type_manufacturers() {
        // Pistols should have manufacturers
        let pistol_mfrs = weapon_type_manufacturers("Pistols");
        assert!(pistol_mfrs.is_some());
        assert!(!pistol_mfrs.unwrap().is_empty());

        // SMG should have manufacturers
        let smg_mfrs = weapon_type_manufacturers("SMG");
        assert!(smg_mfrs.is_some());

        // Shotguns should have manufacturers
        let shotgun_mfrs = weapon_type_manufacturers("Shotguns");
        assert!(shotgun_mfrs.is_some());

        // Unknown type returns None
        assert!(weapon_type_manufacturers("LaserBlaster3000").is_none());
    }

    #[test]
    fn test_all_categories() {
        let categories: Vec<_> = all_categories().collect();
        assert!(!categories.is_empty());

        // All IDs should be positive
        for (id, name) in &categories {
            assert!(*id >= 0);
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_all_manufacturers() {
        let manufacturers: Vec<_> = all_manufacturers().collect();
        assert!(!manufacturers.is_empty());

        // Should include known manufacturers
        let codes: Vec<&str> = manufacturers.iter().map(|(c, _)| *c).collect();
        assert!(codes.contains(&"JAK")); // Jakobs
        assert!(codes.contains(&"TOR")); // Torgue

        // All entries should have non-empty values
        for (code, name) in &manufacturers {
            assert!(!code.is_empty());
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_is_loaded() {
        // is_loaded forces initialization and always returns true
        assert!(is_loaded());
        // Call again to ensure it's idempotent
        assert!(is_loaded());
    }

    #[test]
    fn test_drop_pool() {
        let pool = drop_pool("JAK", "PS");
        assert!(pool.is_some());
        let pool = pool.unwrap();
        assert_eq!(pool.manufacturer_code, "JAK");
        assert_eq!(pool.gear_type_code, "PS");
        assert!(pool.legendary_count > 0);
        assert_eq!(pool.world_pool_name, "Pistols");
    }

    #[test]
    fn test_drop_pool_unknown() {
        assert!(drop_pool("ZZZ", "XX").is_none());
    }

    #[test]
    fn test_world_pool_legendary_count() {
        let pistol_count = world_pool_legendary_count("Pistols");
        assert!(pistol_count > 0);
        assert!(world_pool_legendary_count("Nonexistent") == 0);
    }

    #[test]
    fn test_max_part_index() {
        // Categories with parts should return Some
        // Category 2 = Daedalus Pistol, should have parts
        let max = max_part_index(2);
        assert!(max.is_some());
        assert!(max.unwrap() > 0);

        // Non-existent category returns None
        assert!(max_part_index(99999).is_none());
    }

    #[test]
    fn test_category_part_count() {
        // Category with parts should have non-zero count
        let count = category_part_count(2);
        assert!(count > 0);

        // Non-existent category returns 0
        assert_eq!(category_part_count(99999), 0);
    }

    #[test]
    fn test_part_slot() {
        // Category 2 (Daedalus Pistol) should have slot info for its parts
        if let Some(slot) = part_slot(2, 1) {
            assert!(!slot.is_empty());
        }
    }

    #[test]
    fn test_slot_from_part_name() {
        // Basic slots
        assert_eq!(slot_from_part_name("DAD_PS.part_barrel_01"), "barrel");
        assert_eq!(slot_from_part_name("part_barrel_02_finnty"), "barrel");
        assert_eq!(
            slot_from_part_name("part_barrel_licensed_ted_shooting"),
            "barrel"
        );
        assert_eq!(slot_from_part_name("part_scope_02"), "scope");
        assert_eq!(slot_from_part_name("part_body"), "body");
        assert_eq!(slot_from_part_name("part_body_b"), "body");
        assert_eq!(slot_from_part_name("part_body_mag_sg"), "body_mag");
        assert_eq!(slot_from_part_name("JAK_SG.part_foregrip_03"), "foregrip");
        assert_eq!(slot_from_part_name("part_mag_1"), "mag");
        assert_eq!(slot_from_part_name("part_barrel"), "barrel");
        assert_eq!(slot_from_part_name("part_grip_04_hyp"), "grip");

        // Stat mods
        assert_eq!(slot_from_part_name("part_stat2_wt_ps_equipspeed"), "stat2");
        assert_eq!(
            slot_from_part_name("part_stat3_statuseffect_chance"),
            "stat3"
        );

        // Rarity / comp
        assert_eq!(slot_from_part_name("comp_05_legendary_stopgap"), "rarity");
        assert_eq!(slot_from_part_name("base_comp_02_uncommon"), "rarity");
        assert_eq!(slot_from_part_name("comp_03_rare"), "rarity");

        // Elements
        assert_eq!(slot_from_part_name("radiation"), "element");
        assert_eq!(slot_from_part_name("cryo"), "element");

        // Other
        assert_eq!(slot_from_part_name("part_firmware_baker"), "firmware");
        assert_eq!(
            slot_from_part_name("part_passive_blue_3_1_tier_1"),
            "passive"
        );
        assert_eq!(
            slot_from_part_name("part_secondary_ammo_sg"),
            "secondary_ammo"
        );
        assert_eq!(
            slot_from_part_name("part_secondary_elem_cryo_fire"),
            "secondary_elem"
        );
        assert_eq!(slot_from_part_name("part_shield_ammo"), "shield");
        assert_eq!(
            slot_from_part_name("part_underbarrel_04_atlas_ball"),
            "underbarrel"
        );
    }

    #[test]
    fn test_normalize_part_name() {
        assert_eq!(
            normalize_part_name("DAD_PS.part_barrel_01"),
            "part_barrel_01"
        );
        assert_eq!(normalize_part_name("part_body"), "part_body");
        assert_eq!(normalize_part_name("comp_01_common"), "comp_01_common");
        assert_eq!(normalize_part_name("BOR_REPAIR_KIT.part_borg"), "part_borg");
    }

    #[test]
    fn test_is_part_in_pool_known_category() {
        // Category 2 (Daedalus Pistol) should have pool data
        let result = is_part_in_pool(2, "part_barrel_01");
        assert!(result.is_some(), "Category 2 should have pool data");
    }

    #[test]
    fn test_is_part_in_pool_unknown_category() {
        assert!(is_part_in_pool(99999, "part_body").is_none());
    }

    #[test]
    fn test_is_part_in_pool_normalizes_prefix() {
        // Should find prefixed names by stripping the prefix
        let result = is_part_in_pool(2, "DAD_PS.part_barrel_01");
        assert!(result.is_some());
        // The normalized form "part_barrel_01" should be in the pool
        if let Some(found) = result {
            assert!(found, "DAD_PS.part_barrel_01 should be in category 2 pool");
        }
    }

    #[test]
    fn test_part_index_reverse_lookup() {
        // If we can find a name by (category, index), reverse lookup should return the same index
        if let Some(name) = part_name(2, 7) {
            let idx = part_index(2, name);
            assert_eq!(idx, Some(7), "Reverse lookup for '{}' in category 2", name);
        }
    }

    #[test]
    fn test_part_index_unknown() {
        assert!(part_index(2, "nonexistent_part_xyz").is_none());
    }

    #[test]
    fn test_part_index_normalizes_prefix() {
        // Should work with manufacturer-prefixed names
        if let Some(name) = part_name(2, 7) {
            let prefixed = format!("MFR_PS.{}", name);
            let idx = part_index(2, &prefixed);
            assert_eq!(idx, Some(7), "Should normalize prefix for '{}'", prefixed);
        }
    }

    #[test]
    fn test_part_pool_stats() {
        // Verify pool data loaded with reasonable counts
        let total_categories = PART_POOL_MEMBERS.len();
        assert!(
            total_categories > 50,
            "Expected 50+ categories, got {}",
            total_categories
        );
    }
}