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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
use crate::{
    assets::{self, AssetExt},
    calendar::{Calendar, CalendarEvent},
    comp::{
        arthropod, biped_large, biped_small, bird_large, bird_medium, crustacean, golem,
        inventory::{
            loadout::Loadout,
            slot::{ArmorSlot, EquipSlot},
        },
        item::{self, Item},
        object, quadruped_low, quadruped_medium, quadruped_small, theropod, Body,
    },
    resources::{Time, TimeOfDay},
    trade::SiteInformation,
};
use rand::{self, distributions::WeightedError, seq::SliceRandom, Rng};
use serde::{Deserialize, Serialize};
use strum::EnumIter;
use tracing::warn;

type Weight = u8;

#[derive(Debug)]
pub enum SpecError {
    LoadoutAssetError(assets::Error),
    ItemAssetError(assets::Error),
    ItemChoiceError(WeightedError),
    BaseChoiceError(WeightedError),
    ModularWeaponCreationError(item::modular::ModularWeaponCreationError),
}

#[derive(Debug)]
#[cfg(test)]
pub enum ValidationError {
    ItemAssetError(assets::Error),
    LoadoutAssetError(assets::Error),
    Loop(Vec<String>),
    ModularWeaponCreationError(item::modular::ModularWeaponCreationError),
}

#[derive(Debug, Deserialize, Clone)]
enum ItemSpec {
    Item(String),
    /// Parameters in this variant are used to randomly create a modular weapon
    /// that meets the provided parameters
    ModularWeapon {
        tool: item::tool::ToolKind,
        material: item::Material,
        hands: Option<item::tool::Hands>,
    },
    Choice(Vec<(Weight, Option<ItemSpec>)>),
    Seasonal(Vec<(Option<CalendarEvent>, ItemSpec)>),
}

impl ItemSpec {
    fn try_to_item(
        &self,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Result<Option<Item>, SpecError> {
        match self {
            ItemSpec::Item(item_asset) => {
                let item = Item::new_from_asset(item_asset).map_err(SpecError::ItemAssetError)?;
                Ok(Some(item))
            },
            ItemSpec::Choice(items) => {
                let (_, item_spec) = items
                    .choose_weighted(rng, |(weight, _)| *weight)
                    .map_err(SpecError::ItemChoiceError)?;

                let item = if let Some(item_spec) = item_spec {
                    item_spec.try_to_item(rng, time)?
                } else {
                    None
                };
                Ok(item)
            },
            ItemSpec::ModularWeapon {
                tool,
                material,
                hands,
            } => item::modular::random_weapon(*tool, *material, *hands, rng)
                .map(Some)
                .map_err(SpecError::ModularWeaponCreationError),
            ItemSpec::Seasonal(specs) => specs
                .iter()
                .find_map(|(season, spec)| match (season, time) {
                    (Some(season), Some((_time, calendar))) => {
                        if calendar.is_event(*season) {
                            Some(spec.try_to_item(rng, time))
                        } else {
                            None
                        }
                    },
                    (Some(_season), None) => None,
                    (None, _) => Some(spec.try_to_item(rng, time)),
                })
                .unwrap_or(Ok(None)),
        }
    }

    // Check if ItemSpec is valid and can be turned into Item
    #[cfg(test)]
    fn validate(&self) -> Result<(), ValidationError> {
        let mut rng = rand::thread_rng();
        match self {
            ItemSpec::Item(item_asset) => Item::new_from_asset(item_asset)
                .map(drop)
                .map_err(ValidationError::ItemAssetError),
            ItemSpec::Choice(choices) => {
                // TODO: check for sanity of weights?
                for (_weight, choice) in choices {
                    if let Some(item) = choice {
                        item.validate()?;
                    }
                }
                Ok(())
            },
            ItemSpec::ModularWeapon {
                tool,
                material,
                hands,
            } => item::modular::random_weapon(*tool, *material, *hands, &mut rng)
                .map(drop)
                .map_err(ValidationError::ModularWeaponCreationError),
            ItemSpec::Seasonal(specs) => {
                specs.iter().try_for_each(|(_season, spec)| spec.validate())
            },
        }
    }
}

#[derive(Debug, Deserialize, Clone)]
enum Hands {
    /// Allows to specify one pair
    InHands((Option<ItemSpec>, Option<ItemSpec>)),
    /// Allows specify range of choices
    Choice(Vec<(Weight, Hands)>),
}

impl Hands {
    fn try_to_pair(
        &self,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Result<(Option<Item>, Option<Item>), SpecError> {
        match self {
            Hands::InHands((mainhand, offhand)) => {
                let mut from_spec = |i: &ItemSpec| i.try_to_item(rng, time);

                let mainhand = mainhand.as_ref().map(&mut from_spec).transpose()?.flatten();
                let offhand = offhand.as_ref().map(&mut from_spec).transpose()?.flatten();
                Ok((mainhand, offhand))
            },
            Hands::Choice(pairs) => {
                let (_, pair_spec) = pairs
                    .choose_weighted(rng, |(weight, _)| *weight)
                    .map_err(SpecError::ItemChoiceError)?;

                pair_spec.try_to_pair(rng, time)
            },
        }
    }

    // Check if items in Hand are valid and can be turned into Item
    #[cfg(test)]
    fn validate(&self) -> Result<(), ValidationError> {
        match self {
            Self::InHands((left, right)) => {
                if let Some(hand) = left {
                    hand.validate()?;
                }
                if let Some(hand) = right {
                    hand.validate()?;
                }
                Ok(())
            },
            Self::Choice(choices) => {
                // TODO: check for sanity of weights?
                for (_weight, choice) in choices {
                    choice.validate()?;
                }
                Ok(())
            },
        }
    }
}

#[derive(Debug, Deserialize, Clone)]
enum Base {
    Asset(String),
    /// NOTE: If you have the same item in multiple configs,
    /// *first* one will have the priority
    Combine(Vec<Base>),
    Choice(Vec<(Weight, Base)>),
}

impl Base {
    // Turns Base to LoadoutSpec
    //
    // NOTE: Don't expect it to be fully evaluated, but in some cases
    // it may be so.
    fn to_spec(&self, rng: &mut impl Rng) -> Result<LoadoutSpec, SpecError> {
        match self {
            Base::Asset(asset_specifier) => {
                LoadoutSpec::load_cloned(asset_specifier).map_err(SpecError::LoadoutAssetError)
            },
            Base::Combine(bases) => {
                let bases = bases.iter().map(|b| b.to_spec(rng)?.eval(rng));
                // Get first base of combined
                let mut current = LoadoutSpec::default();
                for base in bases {
                    current = current.merge(base?);
                }

                Ok(current)
            },
            Base::Choice(choice) => {
                let (_, base) = choice
                    .choose_weighted(rng, |(weight, _)| *weight)
                    .map_err(SpecError::BaseChoiceError)?;

                base.to_spec(rng)
            },
        }
    }
}

// TODO: remove clone
/// Core struct of loadout asset.
///
/// If you want programing API of loadout creation,
/// use `LoadoutBuilder` instead.
///
/// For examples of assets, see `assets/test/loadout/ok` folder.
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub struct LoadoutSpec {
    // Meta fields
    inherit: Option<Base>,
    // Armor
    head: Option<ItemSpec>,
    neck: Option<ItemSpec>,
    shoulders: Option<ItemSpec>,
    chest: Option<ItemSpec>,
    gloves: Option<ItemSpec>,
    ring1: Option<ItemSpec>,
    ring2: Option<ItemSpec>,
    back: Option<ItemSpec>,
    belt: Option<ItemSpec>,
    legs: Option<ItemSpec>,
    feet: Option<ItemSpec>,
    tabard: Option<ItemSpec>,
    bag1: Option<ItemSpec>,
    bag2: Option<ItemSpec>,
    bag3: Option<ItemSpec>,
    bag4: Option<ItemSpec>,
    lantern: Option<ItemSpec>,
    glider: Option<ItemSpec>,
    // Weapons
    active_hands: Option<Hands>,
    inactive_hands: Option<Hands>,
}

impl LoadoutSpec {
    /// Merges `self` with `base`.
    /// If some field exists in `self` it will be used,
    /// if no, it will be taken from `base`.
    ///
    /// NOTE: it uses only inheritance chain from `base`
    /// without evaluating it.
    /// Inheritance chain from `self` is discarded.
    ///
    /// # Examples
    /// 1)
    /// You have your asset, let's call it "a". In this asset, you have
    /// inheritance from "b". In asset "b" you inherit from "c".
    ///
    /// If you load your "a" into LoadoutSpec A, and "b" into LoadoutSpec B,
    /// and then merge A into B, you will get new LoadoutSpec that will inherit
    /// from "c".
    ///
    /// 2)
    /// You have two assets, let's call them "a" and "b".
    /// "a" inherits from "n",
    /// "b" inherits from "m".
    ///
    /// If you load "a" into A, "b" into B and then will try to merge them
    /// you will get new LoadoutSpec that will inherit from "m".
    /// It's error, because chain to "n" is lost!!!
    ///
    /// Correct way to do this will be first evaluating at least "a" and then
    /// merge this new LoadoutSpec with "b".
    fn merge(self, base: Self) -> Self {
        Self {
            inherit: base.inherit,
            head: self.head.or(base.head),
            neck: self.neck.or(base.neck),
            shoulders: self.shoulders.or(base.shoulders),
            chest: self.chest.or(base.chest),
            gloves: self.gloves.or(base.gloves),
            ring1: self.ring1.or(base.ring1),
            ring2: self.ring2.or(base.ring2),
            back: self.back.or(base.back),
            belt: self.belt.or(base.belt),
            legs: self.legs.or(base.legs),
            feet: self.feet.or(base.feet),
            tabard: self.tabard.or(base.tabard),
            bag1: self.bag1.or(base.bag1),
            bag2: self.bag2.or(base.bag2),
            bag3: self.bag3.or(base.bag3),
            bag4: self.bag4.or(base.bag4),
            lantern: self.lantern.or(base.lantern),
            glider: self.glider.or(base.glider),
            active_hands: self.active_hands.or(base.active_hands),
            inactive_hands: self.inactive_hands.or(base.inactive_hands),
        }
    }

    /// Recursively evaluate all inheritance chain.
    /// For example with following structure.
    ///
    /// ```text
    /// A
    /// inherit: B,
    /// gloves: a,
    ///
    /// B
    /// inherit: C,
    /// ring1: b,
    ///
    /// C
    /// inherit: None,
    /// ring2: c
    /// ```
    ///
    /// result will be
    ///
    /// ```text
    /// inherit: None,
    /// gloves: a,
    /// ring1: b,
    /// ring2: c,
    /// ```
    fn eval(self, rng: &mut impl Rng) -> Result<Self, SpecError> {
        // Iherit loadout if needed
        if let Some(ref base) = self.inherit {
            let base = base.to_spec(rng)?.eval(rng);
            Ok(self.merge(base?))
        } else {
            Ok(self)
        }
    }

    // Validate loadout spec and check that it can be turned into real loadout.
    // Checks for possible loops too.
    //
    // NOTE: It is stricter than needed, it will check all items
    // even if they are overwritten.
    // We can avoid these redundant checks by building set of all possible
    // specs and then check them.
    // This algorithm will be much more complex and require more memory,
    // because if we Combine multiple Choice-s we will need to create
    // cartesian product of specs.
    //
    // Also we probably don't want garbage entries anyway, even if they are
    // unused.
    #[cfg(test)]
    pub fn validate(&self, history: Vec<String>) -> Result<(), ValidationError> {
        // Helper function to traverse base.
        //
        // Important invariant to hold.
        // Each time it finds new asset it appends it to history
        // and calls spec.validate()
        fn validate_base(base: &Base, mut history: Vec<String>) -> Result<(), ValidationError> {
            match base {
                Base::Asset(asset) => {
                    // read the spec
                    let based = LoadoutSpec::load_cloned(asset)
                        .map_err(ValidationError::LoadoutAssetError)?;

                    // expand history
                    history.push(asset.to_owned());

                    // validate our spec
                    based.validate(history)
                },
                Base::Combine(bases) => {
                    for base in bases {
                        validate_base(base, history.clone())?;
                    }
                    Ok(())
                },
                Base::Choice(choices) => {
                    // TODO: check for sanity of weights?
                    for (_weight, base) in choices {
                        validate_base(base, history.clone())?;
                    }
                    Ok(())
                },
            }
        }

        // Scarry logic
        //
        // We check for duplicates on each append, and because we append on each
        // call we can be sure we don't have any duplicates unless it's a last
        // element.
        // So we can check for duplicates by comparing
        // all elements with last element.
        // And if we found duplicate in our history we found a loop.
        if let Some((last, tail)) = history.split_last() {
            for asset in tail {
                if last == asset {
                    return Err(ValidationError::Loop(history));
                }
            }
        }

        match &self.inherit {
            Some(base) => validate_base(base, history)?,
            None => (),
        }

        self.validate_entries()
    }

    // Validate entries in loadout spec.
    //
    // NOTE: this only check for items, we assume that base
    // is validated separately.
    //
    // TODO: add some intelligent checks,
    // e.g. that `head` key corresponds to Item with ItemKind::Head(_)
    #[cfg(test)]
    fn validate_entries(&self) -> Result<(), ValidationError> {
        // Armor
        if let Some(item) = &self.head {
            item.validate()?;
        }
        if let Some(item) = &self.neck {
            item.validate()?;
        }
        if let Some(item) = &self.shoulders {
            item.validate()?;
        }
        if let Some(item) = &self.chest {
            item.validate()?;
        }
        if let Some(item) = &self.gloves {
            item.validate()?;
        }
        if let Some(item) = &self.ring1 {
            item.validate()?;
        }
        if let Some(item) = &self.ring2 {
            item.validate()?;
        }
        if let Some(item) = &self.back {
            item.validate()?;
        }
        if let Some(item) = &self.belt {
            item.validate()?;
        }
        if let Some(item) = &self.legs {
            item.validate()?;
        }
        if let Some(item) = &self.feet {
            item.validate()?;
        }
        if let Some(item) = &self.tabard {
            item.validate()?;
        }
        // Misc
        if let Some(item) = &self.bag1 {
            item.validate()?;
        }
        if let Some(item) = &self.bag2 {
            item.validate()?;
        }
        if let Some(item) = &self.bag3 {
            item.validate()?;
        }
        if let Some(item) = &self.bag4 {
            item.validate()?;
        }
        if let Some(item) = &self.lantern {
            item.validate()?;
        }
        if let Some(item) = &self.glider {
            item.validate()?;
        }
        // Hands, tools and weapons
        if let Some(hands) = &self.active_hands {
            hands.validate()?;
        }
        if let Some(hands) = &self.inactive_hands {
            hands.validate()?;
        }

        Ok(())
    }
}

impl assets::Asset for LoadoutSpec {
    type Loader = assets::RonLoader;

    const EXTENSION: &'static str = "ron";
}

#[must_use]
pub fn make_potion_bag(quantity: u32) -> Item {
    let mut bag = Item::new_from_asset_expect("common.items.armor.misc.bag.tiny_leather_pouch");
    if let Some(i) = bag.slots_mut().iter_mut().next() {
        let mut potions = Item::new_from_asset_expect("common.items.consumable.potion_big");
        if let Err(e) = potions.set_amount(quantity) {
            warn!("Failed to set potion quantity: {:?}", e);
        }
        *i = Some(potions);
    }
    bag
}

#[must_use]
pub fn make_food_bag(quantity: u32) -> Item {
    let mut bag = Item::new_from_asset_expect("common.items.armor.misc.bag.tiny_leather_pouch");
    if let Some(i) = bag.slots_mut().iter_mut().next() {
        let mut food = Item::new_from_asset_expect("common.items.food.apple_stick");
        if let Err(e) = food.set_amount(quantity) {
            warn!("Failed to set food quantity: {:?}", e);
        }
        *i = Some(food);
    }
    bag
}

#[must_use]
// We have many species so this function is long
// Also we are using default tools for un-specified species so
// it's fine to have wildcards
#[allow(clippy::too_many_lines, clippy::match_wildcard_for_single_variants)]
fn default_main_tool(body: &Body) -> Item {
    let maybe_tool = match body {
        Body::Golem(golem) => match golem.species {
            golem::Species::StoneGolem => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.stone_golems_fist",
            )),
            golem::Species::ClayGolem => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.clay_golem_fist",
            )),
            golem::Species::Gravewarden => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.gravewarden_fist",
            )),
            golem::Species::WoodGolem => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.wood_golem_fist",
            )),
            golem::Species::CoralGolem => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.coral_golem_fist",
            )),
            golem::Species::AncientEffigy => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.ancient_effigy_eyes",
            )),
            golem::Species::Mogwai => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.mogwai",
            )),
            golem::Species::IronGolem => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.iron_golem_fist",
            )),
            _ => None,
        },
        Body::QuadrupedMedium(quadruped_medium) => match quadruped_medium.species {
            quadruped_medium::Species::Wolf => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_medium.wolf",
            )),
            // Below uniques still follow quadmedhoof just with stat alterations
            quadruped_medium::Species::Alpaca | quadruped_medium::Species::Llama => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.quadruped_medium.alpaca",
                ))
            },
            quadruped_medium::Species::Antelope | quadruped_medium::Species::Deer => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.quadruped_medium.antelope",
                ))
            },
            quadruped_medium::Species::Donkey | quadruped_medium::Species::Zebra => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.quadruped_medium.donkey",
                ))
            },
            // Provide Kelpie with unique water-centered abilities
            quadruped_medium::Species::Horse | quadruped_medium::Species::Kelpie => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.quadruped_medium.horse",
                ))
            },
            quadruped_medium::Species::ClaySteed => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.claysteed",
            )),
            quadruped_medium::Species::Saber
            | quadruped_medium::Species::Bonerattler
            | quadruped_medium::Species::Lion
            | quadruped_medium::Species::Snowleopard => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadmedjump",
            )),
            quadruped_medium::Species::Darkhound => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.darkhound",
            )),
            // Below uniques still follow quadmedcharge just with stat alterations
            quadruped_medium::Species::Moose | quadruped_medium::Species::Tuskram => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.quadruped_medium.moose",
                ))
            },
            quadruped_medium::Species::Mouflon => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_medium.mouflon",
            )),
            quadruped_medium::Species::Akhlut
            | quadruped_medium::Species::Dreadhorn
            | quadruped_medium::Species::Mammoth
            | quadruped_medium::Species::Ngoubou => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadmedcharge",
            )),
            quadruped_medium::Species::Grolgar => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_medium.grolgar",
            )),
            quadruped_medium::Species::Roshwalr => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.roshwalr",
            )),
            quadruped_medium::Species::Cattle => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadmedbasicgentle",
            )),
            quadruped_medium::Species::Highland | quadruped_medium::Species::Yak => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.quadruped_medium.highland",
                ))
            },
            quadruped_medium::Species::Frostfang => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.frostfang",
            )),
            _ => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadmedbasic",
            )),
        },
        Body::QuadrupedLow(quadruped_low) => match quadruped_low.species {
            quadruped_low::Species::Maneater => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.maneater",
            )),
            quadruped_low::Species::Asp => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.asp",
            )),
            quadruped_low::Species::Dagon => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.dagon",
            )),
            quadruped_low::Species::Snaretongue => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.snaretongue",
            )),
            quadruped_low::Species::Crocodile
            | quadruped_low::Species::SeaCrocodile
            | quadruped_low::Species::Alligator
            | quadruped_low::Species::Salamander
            | quadruped_low::Species::Elbst => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadlowtail",
            )),
            quadruped_low::Species::Monitor | quadruped_low::Species::Pangolin => Some(
                Item::new_from_asset_expect("common.items.npc_weapons.unique.quadlowquick"),
            ),
            quadruped_low::Species::Lavadrake => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.lavadrake",
            )),
            quadruped_low::Species::Deadwood => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.deadwood",
            )),
            quadruped_low::Species::Basilisk => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.basilisk",
            )),
            quadruped_low::Species::Icedrake => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.icedrake",
            )),
            quadruped_low::Species::Hakulaq => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.hakulaq",
            )),
            quadruped_low::Species::Tortoise => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.tortoise",
            )),
            quadruped_low::Species::Driggle => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.driggle",
            )),
            quadruped_low::Species::Rocksnapper => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.rocksnapper",
            )),
            quadruped_low::Species::Hydra => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_low.hydra",
            )),
            _ => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadlowbasic",
            )),
        },
        Body::QuadrupedSmall(quadruped_small) => match quadruped_small.species {
            quadruped_small::Species::TreantSapling => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.treantsapling",
            )),
            quadruped_small::Species::MossySnail => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.mossysnail",
            )),
            quadruped_small::Species::Boar | quadruped_small::Species::Truffler => Some(
                Item::new_from_asset_expect("common.items.npc_weapons.unique.quadruped_small.boar"),
            ),
            quadruped_small::Species::Hyena => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_small.hyena",
            )),
            quadruped_small::Species::Beaver
            | quadruped_small::Species::Dog
            | quadruped_small::Species::Cat
            | quadruped_small::Species::Goat
            | quadruped_small::Species::Holladon
            | quadruped_small::Species::Sheep
            | quadruped_small::Species::Seal => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadsmallbasic",
            )),
            _ => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.quadruped_small.rodent",
            )),
        },
        Body::Theropod(theropod) => match theropod.species {
            theropod::Species::Sandraptor
            | theropod::Species::Snowraptor
            | theropod::Species::Woodraptor
            | theropod::Species::Axebeak
            | theropod::Species::Sunlizard => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.theropodbird",
            )),
            theropod::Species::Yale => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.theropod.yale",
            )),
            theropod::Species::Dodarock => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.theropodsmall",
            )),
            _ => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.theropodbasic",
            )),
        },
        Body::Arthropod(arthropod) => match arthropod.species {
            arthropod::Species::Hornbeetle | arthropod::Species::Stagbeetle => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.arthropods.hornbeetle",
                ))
            },
            arthropod::Species::Emberfly => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.emberfly",
            )),
            arthropod::Species::Cavespider => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.cavespider",
            )),
            arthropod::Species::Sandcrawler | arthropod::Species::Mosscrawler => {
                Some(Item::new_from_asset_expect(
                    "common.items.npc_weapons.unique.arthropods.mosscrawler",
                ))
            },
            arthropod::Species::Moltencrawler => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.moltencrawler",
            )),
            arthropod::Species::Weevil => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.weevil",
            )),
            arthropod::Species::Blackwidow => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.blackwidow",
            )),
            arthropod::Species::Tarantula => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.tarantula",
            )),
            arthropod::Species::Antlion => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.antlion",
            )),
            arthropod::Species::Dagonite => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.dagonite",
            )),
            arthropod::Species::Leafbeetle => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.arthropods.leafbeetle",
            )),
        },
        Body::BipedLarge(biped_large) => match (biped_large.species, biped_large.body_type) {
            (biped_large::Species::Occultsaurok, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.staff.saurok_staff",
            )),
            (biped_large::Species::Mightysaurok, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.sword.saurok_sword",
            )),
            (biped_large::Species::Slysaurok, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.bow.saurok_bow",
            )),
            (biped_large::Species::Ogre, biped_large::BodyType::Male) => Some(
                Item::new_from_asset_expect("common.items.npc_weapons.hammer.ogre_hammer"),
            ),
            (biped_large::Species::Ogre, biped_large::BodyType::Female) => Some(
                Item::new_from_asset_expect("common.items.npc_weapons.staff.ogre_staff"),
            ),
            (
                biped_large::Species::Mountaintroll
                | biped_large::Species::Swamptroll
                | biped_large::Species::Cavetroll,
                _,
            ) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.troll_hammer",
            )),
            (biped_large::Species::Wendigo, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.wendigo_magic",
            )),
            (biped_large::Species::Werewolf, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.beast_claws",
            )),
            (biped_large::Species::Tursus, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.tursus_claws",
            )),
            (biped_large::Species::Cyclops, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.cyclops_hammer",
            )),
            (biped_large::Species::Dullahan, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.sword.dullahan_sword",
            )),
            (biped_large::Species::Mindflayer, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.staff.mindflayer_staff",
            )),
            (biped_large::Species::Minotaur, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.axe.minotaur_axe",
            )),
            (biped_large::Species::Tidalwarrior, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.tidal_claws",
            )),
            (biped_large::Species::Yeti, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.yeti_hammer",
            )),
            (biped_large::Species::Harvester, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.harvester_scythe",
            )),
            (biped_large::Species::Blueoni, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.axe.oni_blue_axe",
            )),
            (biped_large::Species::Redoni, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.oni_red_hammer",
            )),
            (biped_large::Species::Cultistwarlord, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.sword.bipedlarge-cultist",
            )),
            (biped_large::Species::Cultistwarlock, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.staff.bipedlarge-cultist",
            )),
            (biped_large::Species::Huskbrute, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.husk_brute",
            )),
            (biped_large::Species::Strigoi, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.strigoi_claws",
            )),
            (biped_large::Species::Executioner, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.axe.executioner_axe",
            )),
            (biped_large::Species::Gigasfrost, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.axe.gigas_frost_axe",
            )),
            (biped_large::Species::AdletElder, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.sword.adlet_elder_sword",
            )),
            (biped_large::Species::SeaBishop, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.sea_bishop_sceptre",
            )),
            (biped_large::Species::HaniwaGeneral, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.sword.haniwa_general_sword",
            )),
            (biped_large::Species::TerracottaBesieger, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.bow.terracotta_besieger_bow",
            )),
            (biped_large::Species::TerracottaDemolisher, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.terracotta_demolisher_fist",
            )),
            (biped_large::Species::TerracottaPunisher, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.terracotta_punisher_club",
            )),
            (biped_large::Species::TerracottaPursuer, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.sword.terracotta_pursuer_sword",
            )),
            (biped_large::Species::Cursekeeper, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.cursekeeper_sceptre",
            )),
            (biped_large::Species::Forgemaster, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.hammer.forgemaster_hammer",
            )),
        },
        Body::Object(body) => match body {
            object::Body::Crossbow => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.turret",
            )),
            object::Body::Flamethrower | object::Body::Lavathrower => Some(
                Item::new_from_asset_expect("common.items.npc_weapons.unique.flamethrower"),
            ),
            object::Body::BarrelOrgan => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.organ",
            )),
            object::Body::TerracottaStatue => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.terracotta_statue",
            )),
            object::Body::HaniwaSentry => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.haniwa_sentry",
            )),
            object::Body::SeaLantern => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.tidal_totem",
            )),
            object::Body::Tornado => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.tornado",
            )),
            object::Body::FieryTornado => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.fiery_tornado",
            )),
            object::Body::GnarlingTotemRed => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.gnarling.redtotem",
            )),
            object::Body::GnarlingTotemGreen => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.gnarling.greentotem",
            )),
            object::Body::GnarlingTotemWhite => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.gnarling.whitetotem",
            )),
            _ => None,
        },
        Body::BipedSmall(biped_small) => match (biped_small.species, biped_small.body_type) {
            (biped_small::Species::Gnome, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.adlet.tracker",
            )),
            (biped_small::Species::Bushly, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.bushly",
            )),
            (biped_small::Species::Cactid, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.cactid",
            )),
            (biped_small::Species::Irrwurz, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.irrwurz",
            )),
            (biped_small::Species::Husk, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.husk",
            )),
            (biped_small::Species::Flamekeeper, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.flamekeeper_staff",
            )),
            (biped_small::Species::IronDwarf, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.iron_dwarf",
            )),
            (biped_small::Species::ShamanicSpirit, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.shamanic_spirit",
            )),
            (biped_small::Species::Jiangshi, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.jiangshi",
            )),
            (biped_small::Species::BloodmoonHeiress, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.vampire.bloodmoon_heiress_sword",
            )),
            (biped_small::Species::Bloodservant, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.vampire.bloodservant_axe",
            )),
            (biped_small::Species::Harlequin, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.vampire.harlequin_dagger",
            )),
            (biped_small::Species::GoblinThug, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.goblin_thug_club",
            )),
            (biped_small::Species::GoblinChucker, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.goblin_chucker",
            )),
            (biped_small::Species::GoblinRuffian, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.goblin_ruffian_knife",
            )),
            (biped_small::Species::GreenLegoom, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.green_legoom_rake",
            )),
            (biped_small::Species::OchreLegoom, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.ochre_legoom_spade",
            )),
            (biped_small::Species::PurpleLegoom, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.purple_legoom_pitchfork",
            )),
            (biped_small::Species::RedLegoom, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.red_legoom_hoe",
            )),
            _ => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.biped_small.adlet.hunter",
            )),
        },
        Body::BirdLarge(bird_large) => match (bird_large.species, bird_large.body_type) {
            (bird_large::Species::Cockatrice, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.birdlargebreathe",
            )),
            (bird_large::Species::Phoenix, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.birdlargefire",
            )),
            (bird_large::Species::Roc, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.birdlargebasic",
            )),
            (bird_large::Species::FlameWyvern, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.flamewyvern",
            )),
            (bird_large::Species::FrostWyvern, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.frostwyvern",
            )),
            (bird_large::Species::CloudWyvern, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.cloudwyvern",
            )),
            (bird_large::Species::SeaWyvern, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.seawyvern",
            )),
            (bird_large::Species::WealdWyvern, _) => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.wealdwyvern",
            )),
        },
        Body::BirdMedium(bird_medium) => match bird_medium.species {
            bird_medium::Species::Cockatiel
            | bird_medium::Species::Bat
            | bird_medium::Species::Parrot
            | bird_medium::Species::Crow
            | bird_medium::Species::Parakeet => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.simpleflyingbasic",
            )),
            bird_medium::Species::VampireBat => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.vampire_bat",
            )),
            bird_medium::Species::BloodmoonBat => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.bloodmoon_bat",
            )),
            _ => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.birdmediumbasic",
            )),
        },
        Body::Crustacean(crustacean) => match crustacean.species {
            crustacean::Species::Crab | crustacean::Species::SoldierCrab => Some(
                Item::new_from_asset_expect("common.items.npc_weapons.unique.crab_pincer"),
            ),
            crustacean::Species::Karkatha => Some(Item::new_from_asset_expect(
                "common.items.npc_weapons.unique.karkatha_pincer",
            )),
        },
        _ => None,
    };

    maybe_tool.unwrap_or_else(Item::empty)
}

/// Builder for character Loadouts, containing weapon and armour items belonging
/// to a character, along with some helper methods for loading `Item`-s and
/// `ItemConfig`
///
/// ```
/// use veloren_common::{comp::Item, LoadoutBuilder};
///
/// // Build a loadout with character starter defaults
/// // and a specific sword with default sword abilities
/// let sword = Item::new_from_asset_expect("common.items.weapons.sword.starter");
/// let loadout = LoadoutBuilder::empty()
///     .defaults()
///     .active_mainhand(Some(sword))
///     .build();
/// ```
#[derive(Clone)]
pub struct LoadoutBuilder(Loadout);

#[derive(Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Debug, EnumIter)]
pub enum Preset {
    HuskSummon,
    BorealSummon,
    IronDwarfSummon,
    ShamanicSpiritSummon,
    JiangshiSummon,
    BloodservantSummon,
}

impl LoadoutBuilder {
    #[must_use]
    pub fn empty() -> Self { Self(Loadout::new_empty()) }

    #[must_use]
    /// Construct new `LoadoutBuilder` from `asset_specifier`
    /// Will panic if asset is broken
    pub fn from_asset_expect(
        asset_specifier: &str,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Self {
        Self::from_asset(asset_specifier, rng, time).expect("failed to load loadut config")
    }

    /// Construct new `LoadoutBuilder` from `asset_specifier`
    pub fn from_asset(
        asset_specifier: &str,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Result<Self, SpecError> {
        let loadout = Self::empty();
        loadout.with_asset(asset_specifier, rng, time)
    }

    #[must_use]
    /// Construct new default `LoadoutBuilder` for corresponding `body`
    ///
    /// NOTE: make sure that you check what is default for this body
    /// Use it if you don't care much about it, for example in "/spawn" command
    pub fn from_default(body: &Body) -> Self {
        let loadout = Self::empty();
        loadout
            .with_default_maintool(body)
            .with_default_equipment(body)
    }

    /// Construct new `LoadoutBuilder` from `asset_specifier`
    pub fn from_loadout_spec(
        loadout_spec: LoadoutSpec,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Result<Self, SpecError> {
        let loadout = Self::empty();
        loadout.with_loadout_spec(loadout_spec, rng, time)
    }

    #[must_use]
    /// Construct new `LoadoutBuilder` from `asset_specifier`
    ///
    /// Will panic if asset is broken
    pub fn from_loadout_spec_expect(
        loadout_spec: LoadoutSpec,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Self {
        Self::from_loadout_spec(loadout_spec, rng, time).expect("failed to load loadout spec")
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    /// Set default active mainhand weapon based on `body`
    pub fn with_default_maintool(self, body: &Body) -> Self {
        self.active_mainhand(Some(default_main_tool(body)))
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    /// Set default equipement based on `body`
    pub fn with_default_equipment(self, body: &Body) -> Self {
        let chest = match body {
            Body::BipedLarge(body) => match body.species {
                biped_large::Species::Mindflayer => {
                    Some("common.items.npc_armor.biped_large.mindflayer")
                },
                biped_large::Species::Minotaur => {
                    Some("common.items.npc_armor.biped_large.minotaur")
                },
                biped_large::Species::Tidalwarrior => {
                    Some("common.items.npc_armor.biped_large.tidal_warrior")
                },
                biped_large::Species::Yeti => Some("common.items.npc_armor.biped_large.yeti"),
                biped_large::Species::Harvester => {
                    Some("common.items.npc_armor.biped_large.harvester")
                },
                biped_large::Species::Ogre
                | biped_large::Species::Blueoni
                | biped_large::Species::Redoni
                | biped_large::Species::Cavetroll
                | biped_large::Species::Mountaintroll
                | biped_large::Species::Swamptroll
                | biped_large::Species::Wendigo => {
                    Some("common.items.npc_armor.biped_large.generic")
                },
                biped_large::Species::Cyclops => Some("common.items.npc_armor.biped_large.cyclops"),
                biped_large::Species::Dullahan => {
                    Some("common.items.npc_armor.biped_large.dullahan")
                },
                biped_large::Species::Tursus => Some("common.items.npc_armor.biped_large.tursus"),
                biped_large::Species::Cultistwarlord => {
                    Some("common.items.npc_armor.biped_large.warlord")
                },
                biped_large::Species::Cultistwarlock => {
                    Some("common.items.npc_armor.biped_large.warlock")
                },
                biped_large::Species::Gigasfrost => {
                    Some("common.items.npc_armor.biped_large.gigas_frost")
                },
                biped_large::Species::HaniwaGeneral => {
                    Some("common.items.npc_armor.biped_large.haniwageneral")
                },
                biped_large::Species::TerracottaBesieger
                | biped_large::Species::TerracottaDemolisher
                | biped_large::Species::TerracottaPunisher
                | biped_large::Species::TerracottaPursuer
                | biped_large::Species::Cursekeeper => {
                    Some("common.items.npc_armor.biped_large.terracotta")
                },
                biped_large::Species::Forgemaster => {
                    Some("common.items.npc_armor.biped_large.forgemaster")
                },
                _ => None,
            },
            Body::BirdLarge(body) => match body.species {
                bird_large::Species::FlameWyvern
                | bird_large::Species::FrostWyvern
                | bird_large::Species::CloudWyvern
                | bird_large::Species::SeaWyvern
                | bird_large::Species::WealdWyvern => {
                    Some("common.items.npc_armor.bird_large.wyvern")
                },
                bird_large::Species::Phoenix => Some("common.items.npc_armor.bird_large.phoenix"),
                _ => None,
            },
            Body::BirdMedium(body) => match body.species {
                bird_medium::Species::BloodmoonBat => {
                    Some("common.items.npc_armor.bird_medium.bloodmoon_bat")
                },
                _ => None,
            },
            Body::Golem(body) => match body.species {
                golem::Species::ClayGolem => Some("common.items.npc_armor.golem.claygolem"),
                golem::Species::Gravewarden => Some("common.items.npc_armor.golem.gravewarden"),
                golem::Species::WoodGolem => Some("common.items.npc_armor.golem.woodgolem"),
                golem::Species::AncientEffigy => Some("common.items.npc_armor.golem.ancienteffigy"),
                golem::Species::Mogwai => Some("common.items.npc_armor.golem.mogwai"),
                golem::Species::IronGolem => Some("common.items.npc_armor.golem.irongolem"),
                _ => None,
            },
            Body::QuadrupedLow(body) => match body.species {
                quadruped_low::Species::Sandshark
                | quadruped_low::Species::Alligator
                | quadruped_low::Species::Crocodile
                | quadruped_low::Species::SeaCrocodile
                | quadruped_low::Species::Icedrake
                | quadruped_low::Species::Lavadrake
                | quadruped_low::Species::Mossdrake => Some("common.items.npc_armor.generic"),
                quadruped_low::Species::Reefsnapper
                | quadruped_low::Species::Rocksnapper
                | quadruped_low::Species::Rootsnapper
                | quadruped_low::Species::Tortoise
                | quadruped_low::Species::Basilisk
                | quadruped_low::Species::Hydra => Some("common.items.npc_armor.generic_high"),
                quadruped_low::Species::Dagon => Some("common.items.npc_armor.quadruped_low.dagon"),
                _ => None,
            },
            Body::QuadrupedMedium(body) => match body.species {
                quadruped_medium::Species::Bonerattler => Some("common.items.npc_armor.generic"),
                quadruped_medium::Species::Tarasque => Some("common.items.npc_armor.generic_high"),
                quadruped_medium::Species::ClaySteed => {
                    Some("common.items.npc_armor.quadruped_medium.claysteed")
                },
                _ => None,
            },
            Body::Theropod(body) => match body.species {
                theropod::Species::Archaeos | theropod::Species::Ntouka => {
                    Some("common.items.npc_armor.generic")
                },
                theropod::Species::Dodarock => Some("common.items.npc_armor.generic_high"),
                _ => None,
            },
            // TODO: Check over
            Body::Arthropod(body) => match body.species {
                arthropod::Species::Blackwidow
                | arthropod::Species::Cavespider
                | arthropod::Species::Emberfly
                | arthropod::Species::Moltencrawler
                | arthropod::Species::Mosscrawler
                | arthropod::Species::Sandcrawler
                | arthropod::Species::Tarantula => None,
                _ => Some("common.items.npc_armor.generic"),
            },
            Body::QuadrupedSmall(body) => match body.species {
                quadruped_small::Species::Turtle
                | quadruped_small::Species::Holladon
                | quadruped_small::Species::TreantSapling
                | quadruped_small::Species::MossySnail => Some("common.items.npc_armor.generic"),
                _ => None,
            },
            Body::Crustacean(body) => match body.species {
                crustacean::Species::Karkatha => Some("common.items.npc_armor.crustacean.karkatha"),
                _ => None,
            },
            _ => None,
        };

        if let Some(chest) = chest {
            self.chest(Some(Item::new_from_asset_expect(chest)))
        } else {
            self
        }
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn with_preset(mut self, preset: Preset) -> Self {
        let rng = &mut rand::thread_rng();
        match preset {
            Preset::HuskSummon => {
                self = self.with_asset_expect("common.loadout.dungeon.cultist.husk", rng, None);
            },
            Preset::BorealSummon => {
                self =
                    self.with_asset_expect("common.loadout.world.boreal.boreal_warrior", rng, None);
            },
            Preset::IronDwarfSummon => {
                self = self.with_asset_expect(
                    "common.loadout.dungeon.dwarven_quarry.iron_dwarf",
                    rng,
                    None,
                );
            },
            Preset::ShamanicSpiritSummon => {
                self = self.with_asset_expect(
                    "common.loadout.dungeon.terracotta.shamanic_spirit",
                    rng,
                    None,
                );
            },
            Preset::JiangshiSummon => {
                self =
                    self.with_asset_expect("common.loadout.dungeon.terracotta.jiangshi", rng, None);
            },
            Preset::BloodservantSummon => {
                self = self.with_asset_expect(
                    "common.loadout.dungeon.vampire.bloodservant",
                    rng,
                    None,
                );
            },
        }

        self
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn with_creator(
        mut self,
        creator: fn(
            LoadoutBuilder,
            Option<&SiteInformation>,
            time: Option<&(TimeOfDay, Calendar)>,
        ) -> LoadoutBuilder,
        economy: Option<&SiteInformation>,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> LoadoutBuilder {
        self = creator(self, economy, time);

        self
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    fn with_loadout_spec<R: Rng>(
        mut self,
        spec: LoadoutSpec,
        rng: &mut R,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Result<Self, SpecError> {
        // Include any inheritance
        let spec = spec.eval(rng)?;

        // Utility function to unwrap our itemspec
        let mut to_item = |maybe_item: Option<ItemSpec>| {
            if let Some(item) = maybe_item {
                item.try_to_item(rng, time)
            } else {
                Ok(None)
            }
        };

        let to_pair = |maybe_hands: Option<Hands>, rng: &mut R| {
            if let Some(hands) = maybe_hands {
                hands.try_to_pair(rng, time)
            } else {
                Ok((None, None))
            }
        };

        // Place every item
        if let Some(item) = to_item(spec.head)? {
            self = self.head(Some(item));
        }
        if let Some(item) = to_item(spec.neck)? {
            self = self.neck(Some(item));
        }
        if let Some(item) = to_item(spec.shoulders)? {
            self = self.shoulder(Some(item));
        }
        if let Some(item) = to_item(spec.chest)? {
            self = self.chest(Some(item));
        }
        if let Some(item) = to_item(spec.gloves)? {
            self = self.hands(Some(item));
        }
        if let Some(item) = to_item(spec.ring1)? {
            self = self.ring1(Some(item));
        }
        if let Some(item) = to_item(spec.ring2)? {
            self = self.ring2(Some(item));
        }
        if let Some(item) = to_item(spec.back)? {
            self = self.back(Some(item));
        }
        if let Some(item) = to_item(spec.belt)? {
            self = self.belt(Some(item));
        }
        if let Some(item) = to_item(spec.legs)? {
            self = self.pants(Some(item));
        }
        if let Some(item) = to_item(spec.feet)? {
            self = self.feet(Some(item));
        }
        if let Some(item) = to_item(spec.tabard)? {
            self = self.tabard(Some(item));
        }
        if let Some(item) = to_item(spec.bag1)? {
            self = self.bag(ArmorSlot::Bag1, Some(item));
        }
        if let Some(item) = to_item(spec.bag2)? {
            self = self.bag(ArmorSlot::Bag2, Some(item));
        }
        if let Some(item) = to_item(spec.bag3)? {
            self = self.bag(ArmorSlot::Bag3, Some(item));
        }
        if let Some(item) = to_item(spec.bag4)? {
            self = self.bag(ArmorSlot::Bag4, Some(item));
        }
        if let Some(item) = to_item(spec.lantern)? {
            self = self.lantern(Some(item));
        }
        if let Some(item) = to_item(spec.glider)? {
            self = self.glider(Some(item));
        }
        let (active_mainhand, active_offhand) = to_pair(spec.active_hands, rng)?;
        if let Some(item) = active_mainhand {
            self = self.active_mainhand(Some(item));
        }
        if let Some(item) = active_offhand {
            self = self.active_offhand(Some(item));
        }
        let (inactive_mainhand, inactive_offhand) = to_pair(spec.inactive_hands, rng)?;
        if let Some(item) = inactive_mainhand {
            self = self.inactive_mainhand(Some(item));
        }
        if let Some(item) = inactive_offhand {
            self = self.inactive_offhand(Some(item));
        }

        Ok(self)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn with_asset(
        self,
        asset_specifier: &str,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Result<Self, SpecError> {
        let spec =
            LoadoutSpec::load_cloned(asset_specifier).map_err(SpecError::LoadoutAssetError)?;
        self.with_loadout_spec(spec, rng, time)
    }

    /// # Usage
    /// Creates new `LoadoutBuilder` with all field replaced from
    /// `asset_specifier` which corresponds to loadout config
    ///
    /// # Panics
    /// 1) Will panic if there is no asset with such `asset_specifier`
    /// 2) Will panic if path to item specified in loadout file doesn't exist
    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn with_asset_expect(
        self,
        asset_specifier: &str,
        rng: &mut impl Rng,
        time: Option<&(TimeOfDay, Calendar)>,
    ) -> Self {
        self.with_asset(asset_specifier, rng, time)
            .expect("failed loading loadout config")
    }

    /// Set default armor items for the loadout. This may vary with game
    /// updates, but should be safe defaults for a new character.
    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn defaults(self) -> Self {
        let rng = &mut rand::thread_rng();
        self.with_asset_expect("common.loadout.default", rng, None)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    fn with_equipment(mut self, equip_slot: EquipSlot, item: Option<Item>) -> Self {
        // Panic if item doesn't correspond to slot
        assert!(
            item.as_ref()
                .map_or(true, |item| equip_slot.can_hold(&item.kind()))
        );

        // TODO: What if `with_equipment` is used twice for the same slot. Or defaults
        // include an item in this slot.
        // Used when creating a loadout, so time not needed as it is used to check when
        // stuff gets unequipped. A new loadout has never unequipped an item.
        let time = Time(0.0);

        self.0.swap(equip_slot, item, time);
        self
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    fn with_armor(self, armor_slot: ArmorSlot, item: Option<Item>) -> Self {
        self.with_equipment(EquipSlot::Armor(armor_slot), item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn active_mainhand(self, item: Option<Item>) -> Self {
        self.with_equipment(EquipSlot::ActiveMainhand, item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn active_offhand(self, item: Option<Item>) -> Self {
        self.with_equipment(EquipSlot::ActiveOffhand, item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn inactive_mainhand(self, item: Option<Item>) -> Self {
        self.with_equipment(EquipSlot::InactiveMainhand, item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn inactive_offhand(self, item: Option<Item>) -> Self {
        self.with_equipment(EquipSlot::InactiveOffhand, item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn shoulder(self, item: Option<Item>) -> Self {
        self.with_armor(ArmorSlot::Shoulders, item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn chest(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Chest, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn belt(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Belt, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn hands(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Hands, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn pants(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Legs, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn feet(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Feet, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn back(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Back, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn ring1(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Ring1, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn ring2(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Ring2, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn neck(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Neck, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn lantern(self, item: Option<Item>) -> Self {
        self.with_equipment(EquipSlot::Lantern, item)
    }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn glider(self, item: Option<Item>) -> Self { self.with_equipment(EquipSlot::Glider, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn head(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Head, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn tabard(self, item: Option<Item>) -> Self { self.with_armor(ArmorSlot::Tabard, item) }

    #[must_use = "Method consumes builder and returns updated builder."]
    pub fn bag(self, which: ArmorSlot, item: Option<Item>) -> Self { self.with_armor(which, item) }

    #[must_use]
    pub fn build(self) -> Loadout { self.0 }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::comp::{self, Body};
    use rand::thread_rng;
    use strum::IntoEnumIterator;

    // Testing different species
    //
    // Things that will be caught - invalid assets paths for
    // creating default main hand tool or equipment without config
    #[test]
    fn test_loadout_species() {
        macro_rules! test_species {
            // base case
            ($species:tt : $body:tt) => {
                let mut rng = thread_rng();
                for s in comp::$species::ALL_SPECIES.iter() {
                    let body = comp::$species::Body::random_with(&mut rng, s);
                    let female_body = comp::$species::Body {
                        body_type: comp::$species::BodyType::Female,
                        ..body
                    };
                    let male_body = comp::$species::Body {
                        body_type: comp::$species::BodyType::Male,
                        ..body
                    };
                    std::mem::drop(LoadoutBuilder::from_default(
                        &Body::$body(female_body),
                    ));
                    std::mem::drop(LoadoutBuilder::from_default(
                        &Body::$body(male_body),
                    ));
                }
            };
            // recursive call
            ($base:tt : $body:tt, $($species:tt : $nextbody:tt),+ $(,)?) => {
                test_species!($base: $body);
                test_species!($($species: $nextbody),+);
            }
        }

        // See `[AllBodies](crate::comp::body::AllBodies)`
        test_species!(
            humanoid: Humanoid,
            quadruped_small: QuadrupedSmall,
            quadruped_medium: QuadrupedMedium,
            quadruped_low: QuadrupedLow,
            quadruped_small: QuadrupedSmall,
            bird_medium: BirdMedium,
            bird_large: BirdLarge,
            fish_small: FishSmall,
            fish_medium: FishMedium,
            biped_small: BipedSmall,
            biped_large: BipedLarge,
            theropod: Theropod,
            dragon: Dragon,
            golem: Golem,
            arthropod: Arthropod,
        );
    }

    // Testing all loadout presets
    //
    // Things that will be catched - invalid assets paths
    #[test]
    fn test_loadout_presets() {
        for preset in Preset::iter() {
            drop(LoadoutBuilder::empty().with_preset(preset));
        }
    }

    // It just loads every loadout asset and tries to validate them
    //
    // TODO: optimize by caching checks
    // Because of nature of inheritance of loadout specs,
    // we will check some loadout assets at least two times.
    // One for asset itself and second if it serves as a base for other asset.
    #[test]
    fn validate_all_loadout_assets() {
        let loadouts = assets::load_rec_dir::<LoadoutSpec>("common.loadout")
            .expect("failed to load loadout directory");
        for loadout_id in loadouts.read().ids() {
            let loadout =
                LoadoutSpec::load_cloned(loadout_id).expect("failed to load loadout asset");
            loadout
                .validate(vec![loadout_id.to_string()])
                .unwrap_or_else(|e| panic!("{loadout_id} is broken: {e:?}"));
        }
    }

    // Basically test that our validation tests don't have false-positives
    #[test]
    fn test_valid_assets() {
        let loadouts = assets::load_rec_dir::<LoadoutSpec>("test.loadout.ok")
            .expect("failed to load loadout directory");

        for loadout_id in loadouts.read().ids() {
            let loadout =
                LoadoutSpec::load_cloned(loadout_id).expect("failed to load loadout asset");
            loadout
                .validate(vec![loadout_id.to_string()])
                .unwrap_or_else(|e| panic!("{loadout_id} is broken: {e:?}"));
        }
    }
}