amble_engine 0.67.0

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

use std::collections::{HashMap, HashSet};

use crate::{
    AmbleWorld, ItemId, View, WorldObject,
    entity_search::{self, SearchError, SearchScope, entity_not_found},
    helpers::plural_s,
    item::{ContainerState, IngestMode, Item, ItemAbility, ItemInteractionType, consume, interaction_requirement_met},
    spinners::CoreSpinnerType,
    style::GameStyle,
    trigger::{TriggerCondition, check_triggers, triggers_contain_condition},
    view::ViewItem,
};

use anyhow::{Context, Result, bail};
use colored::Colorize;
use log::info;

/// Touch or press an `Item`.
///
/// # Errors
/// Returns an error if the player's current room cannot be resolved or if the scoped items
/// referenced during trigger evaluation cannot be found.
pub fn touch_handler(world: &mut AmbleWorld, view: &mut View, item_str: &str) -> Result<bool> {
    let room_id = world.player_room_id();
    let item_id = match entity_search::find_item_match(world, item_str, SearchScope::TouchableItems(room_id.clone())) {
        Ok(uuid) => uuid,
        Err(SearchError::NoMatchingName(input)) => {
            if let Some(room) = world.rooms.get(&room_id)
                && let Some(entry) = room.find_scenery(&input)
            {
                view.push(ViewItem::ActionSuccess(format!(
                    "You touch the {}. It's firmly part of the scenery.",
                    entry.name.item_style()
                )));
                info!(
                    "{} touched scenery \"{}\" in room {}",
                    world.player.name(),
                    entry.name,
                    room.symbol()
                );
                return Ok(true);
            }
            entity_not_found(world, view, input.as_str());
            return Ok(false);
        },
        Err(e) => bail!(e),
    };

    let triggers_fired = check_triggers(world, view, &[TriggerCondition::Touch(item_id.clone())])?;
    let sent_trigger_fired = triggers_contain_condition(&triggers_fired, |trig| match trig {
        TriggerCondition::Touch(triggered_item_id) => triggered_item_id == &item_id,
        _ => false,
    });
    let item = world
        .items
        .get(&item_id)
        .with_context(|| format!("get({item_id}) from world.items"))?;
    if !sent_trigger_fired {
        info!(
            "{} touched {} ({})... and nothing happened.",
            world.player.name(),
            item.name(),
            item.symbol(),
        );
        view.push(ViewItem::ActionSuccess(
            world.spin_core(CoreSpinnerType::NoEffect, "That has no discernable effect."),
        ));
    }
    Ok(true)
}

/// Ingests an item (or single portion of a multi-use item).
///
/// # Errors
/// Returns an error if the player's current room cannot be located, if scoped items cannot be
/// resolved, or if trigger evaluation encounters missing world state.
pub fn ingest_handler(world: &mut AmbleWorld, view: &mut View, item_str: &str, mode: IngestMode) -> Result<bool> {
    let room_id = world.player_room_id();
    let item_id = match entity_search::find_item_match(world, item_str, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(SearchError::NoMatchingName(_)) => {
            entity_not_found(world, view, item_str);
            return Ok(false);
        },
        Err(e) => bail!(e),
    };

    // found one -- does item have the ability to be ingested this way?
    let item = world
        .items
        .get(&item_id)
        .with_context(|| format!("get({item_id}) from world.items"))?;
    let (item_name, item_symbol) = (item.name().to_owned(), item.symbol().to_owned());
    let meets_mode = match mode {
        IngestMode::Eat => item.abilities.contains(&ItemAbility::Eat),
        IngestMode::Drink => item.abilities.contains(&ItemAbility::Drink),
        IngestMode::Inhale => item.abilities.contains(&ItemAbility::Inhale),
    };
    if !meets_mode {
        // no, log and notify player
        info!(
            "{} tried to {mode} an item ({}) which lacks that ability.",
            world.player.name(),
            item.symbol()
        );
        view.push(ViewItem::ActionFailure(format!(
            "Despite your best effort, you are unable to {mode} the {}.",
            item.name().item_style()
        )));
        return Ok(false);
    }

    /* we now have the id (item_id) of an item that is available nearby,
    matches player input, and can be ingested in the specified way */

    // Check triggers for any specific reaction / feedback to this ingestion
    let sent_id = item_id.clone();
    let sent_mode = mode;
    let fired_triggers = check_triggers(
        world,
        view,
        &[TriggerCondition::Ingest {
            item_id: item_id.clone(),
            mode,
        }],
    )?;
    let sent_trigger_fired = triggers_contain_condition(&fired_triggers, |cond| match cond {
        TriggerCondition::Ingest { item_id, mode } => item_id == &sent_id && *mode == sent_mode,
        _ => false,
    });

    // If no trigger fired, give default feedback
    if !sent_trigger_fired {
        view.push(ViewItem::ActionSuccess(format!(
            "You {mode} the {}. It doesn't seem to do much.",
            item_name.item_style()
        )));
    }

    // Consume 1 use of the item
    let ability = match mode {
        IngestMode::Eat => ItemAbility::Eat,
        IngestMode::Drink => ItemAbility::Drink,
        IngestMode::Inhale => ItemAbility::Inhale,
    };
    if let Some(uses_left) = consume(world, &item_id, &ability)? {
        if uses_left == 0 {
            view.push(ViewItem::ActionSuccess(format!(
                "The {} has no more uses left.",
                item_name.item_style()
            )));
        } else {
            #[allow(clippy::cast_possible_wrap)]
            view.push(ViewItem::ActionSuccess(format!(
                "The {} has {} use{} left",
                item_name.item_style(),
                uses_left,
                plural_s(uses_left as isize)
            )));
        }
    }

    info!("{} ingested '{}' ({})", world.player.name(), item_name, item_symbol);
    Ok(true)
}
/// Uses one item on another item with a specific type of interaction.
///
/// This is the core handler for complex item interactions where one item (the tool)
/// is used to perform an action on another item (the target). The interaction system
/// validates that the tool has the required capabilities and that the target can
/// accept that type of interaction.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `interaction` - The type of interaction to perform (e.g., Cut, Burn, Clean)
/// * `tool_str` - Pattern string to match the tool item in player inventory
/// * `target_str` - Pattern string to match the target item in nearby area
///
/// # Returns
///
/// Returns `Ok(())` on successful interaction attempt, regardless of whether
/// the interaction actually succeeded or failed due to game logic.
///
/// # Interaction Validation
///
/// The function performs several validation steps:
/// 1. **Tool availability** - Tool must be in player inventory
/// 2. **Target availability** - Target must be nearby (room or inventory)
/// 3. **Capability matching** - Tool must have ability required by target
/// 4. **Interaction firing** - Triggers must exist to handle the interaction
///
/// # Trigger System
///
/// Multiple triggers may fire for a single interaction:
/// - `UseItemOnItem` - Specific tool + target + interaction combination
/// - `ActOnItem` - General action on target (regardless of tool)
/// - `UseItem` - General tool usage (regardless of target)
///
/// # Consumable Items
///
/// If the tool is consumable, it will lose uses when successfully employed.
/// The function tracks remaining uses and notifies the player when items
/// are exhausted.
///
/// # Feedback System
///
/// - Success: Determined by whether appropriate triggers fire
/// - Failure: Provides specific feedback about missing requirements
/// - No effect: Generic message from the `NoEffect` spinner when no triggers handle the interaction
///
/// # Errors
/// Returns an error if the player's current room cannot be determined, if tool or target items
/// cannot be resolved from world data, or if trigger evaluation fails.
///
/// # Panics
/// Zero. The cases are checked for `None` and handled gracefully before the `expect()` calls occur
#[allow(clippy::too_many_lines)]
pub fn use_item_on_handler(
    world: &mut AmbleWorld,
    view: &mut View,
    interaction: ItemInteractionType,
    tool_str: &str,
    target_str: &str,
) -> Result<bool> {
    let Some((target, tool)) = resolve_use_item_participants(world, view, tool_str, target_str)? else {
        return Ok(false);
    };
    let (target_id, target_name, target_sym) =
        (target.id.clone(), target.name().to_owned(), target.symbol().to_owned());
    let (tool_id, tool_name, tool_sym) = (tool.id.clone(), tool.name().to_string(), tool.symbol().to_owned());
    let tool_is_consumable = tool.consumable.is_some();

    // check if these items can interact in this way
    if !interaction_requirement_met(interaction, target, tool) {
        view.push(ViewItem::ActionFailure(format!(
            "You can't do that with a {}!",
            tool.name().item_style(),
        )));
        info!("Player tried to {interaction:?} {target_name} ({target_sym}) with {tool_name} ({tool_sym})");
        return Ok(true);
    }
    // The utilized ItemAbility is needed to send a UseItem TriggerCondition. ItemAbility::Use is
    // a reasonable default but should never come up; the existence of this Interaction
    // implies a specific matching ability which has already been verified by the
    // interaction_requirement_met(...) call above.
    let used_ability = target
        .interaction_requires
        .get(&interaction)
        .unwrap_or(&ItemAbility::Use)
        .clone();

    let interaction_fired = dispatch_use_item_triggers(world, view, interaction, &target_id, &tool_id, &used_ability)?;

    // Nope, no triggered reaction to these conditions
    if !interaction_fired {
        view.push(ViewItem::ActionFailure(
            world
                .spin_core(CoreSpinnerType::NoEffect, "That appears to have had no effect.")
                .clone(),
        ));
        info!("No matching trigger for {interaction:?} {target_name} ({target_sym}) with {tool_name} ({tool_sym})");
    }
    // consume 1 use if consumable. Obviously.
    if tool_is_consumable {
        let uses_left = consume(world, &tool_id, &used_ability)?;
        if let Some(uses_left) = uses_left {
            if uses_left == 0 {
                view.push(ViewItem::ActionSuccess(format!(
                    "The {} has no more uses left.",
                    tool_name.item_style()
                )));
            } else {
                #[allow(clippy::cast_possible_wrap)]
                view.push(ViewItem::ActionSuccess(format!(
                    "The {} has {} use{} left",
                    tool_name.item_style(),
                    uses_left,
                    plural_s(uses_left as isize)
                )));
            }
        }
    }
    Ok(true)
}

fn resolve_use_item_participants<'a>(
    world: &'a AmbleWorld,
    view: &mut View,
    tool_str: &str,
    target_str: &str,
) -> Result<Option<(&'a Item, &'a Item)>> {
    // find an item in inventory matching tool_str
    let tool_id = match entity_search::find_item_match(world, tool_str, SearchScope::Inventory) {
        Ok(uuid) => uuid,
        Err(SearchError::NoMatchingName(tool_pattern)) => {
            view.push(ViewItem::ActionFailure(format!(
                "There is no \"{}\" in your inventory.",
                tool_pattern.error_style()
            )));
            return Ok(None);
        },
        Err(e) => bail!(e),
    };
    // find a reachable item in the room or inventory matching target_str
    let room_id = world.player_room_id();
    let target_id = match entity_search::find_item_match(world, target_str, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(SearchError::NoMatchingName(target_pattern)) => {
            view.push(ViewItem::ActionFailure(format!(
                "You don't see any item matching \"{}\" within reach.",
                target_pattern.error_style()
            )));
            return Ok(None);
        },
        Err(e) => bail!(e),
    };
    // return references to the items matched
    let tool = world.items.get(&tool_id).expect("tool_id already known valid");
    let target = world.items.get(&target_id).expect("target_id already known valid");
    Ok(Some((target, tool)))
}

// sends trigger event conditions appropriate to item usage, returns true if any
// of the conditions caused a trigger to fire
fn dispatch_use_item_triggers(
    world: &mut AmbleWorld,
    view: &mut View,
    interaction: ItemInteractionType,
    target_id: &ItemId,
    tool_id: &ItemId,
    used_ability: &ItemAbility,
) -> Result<bool> {
    let fired = check_triggers(
        world,
        view,
        &[
            TriggerCondition::UseItemOnItem {
                interaction,
                target_id: target_id.clone(),
                tool_id: tool_id.clone(),
            },
            TriggerCondition::ActOnItem {
                action: interaction,
                target_id: target_id.clone(),
            },
            TriggerCondition::UseItem {
                item_id: tool_id.clone(),
                ability: used_ability.clone(),
            },
        ],
    )?;

    Ok(triggers_contain_condition(&fired, |cond| match cond {
        TriggerCondition::ActOnItem {
            action,
            target_id: fired_target,
        } => *action == interaction && fired_target == target_id,
        TriggerCondition::UseItem { ability, .. } => ability == used_ability,
        TriggerCondition::UseItemOnItem {
            interaction: fired_interaction,
            target_id: fired_target,
            tool_id: fired_tool,
        } => *fired_interaction == interaction && fired_target == target_id && fired_tool == tool_id,
        _ => false,
    }))
}
/// Activates an item if it has the ability to be turned on.
///
/// This handler attempts to turn on or activate items in the current room
/// that have switch-like functionality. Items must have the `TurnOn` ability
/// to be activated, and the activation may trigger various game effects.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `item_pattern` - Pattern string to match against items in current room
///
/// # Returns
///
/// Returns `Ok(())` after attempting activation, regardless of success.
///
/// # Behavior
///
/// - Searches current room for items matching the pattern
/// - Verifies the item has the `TurnOn` ability
/// - Fires `TriggerCondition::UseItem` with `ItemAbility::TurnOn`
/// - Provides appropriate feedback based on whether triggers fire
///
/// # Error Handling
///
/// - Item not found: Standard "not found" message
/// - Item cannot be turned on: Specific capability message
/// - NPC matched: Humorous rejection message
/// - No effect: Generic "nothing happens" message when no triggers fire
///
/// # Errors
/// Returns an error if the player's current room cannot be determined or if trigger execution
/// fails due to missing world data.
pub fn turn_on_handler(world: &mut AmbleWorld, view: &mut View, item_pattern: &str) -> Result<bool> {
    // search player's location for an item with name matching 'pattern'
    let room_id = world.player_room_id();
    let item_id = match entity_search::find_item_match(world, item_pattern, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(e) => match e {
            SearchError::NoMatchingName(_) => {
                entity_not_found(world, view, item_pattern);
                return Ok(false);
            },
            _ => bail!(e),
        },
    };
    let item = world
        .items
        .get_mut(&item_id)
        .with_context(|| format!("world.items.get_mut({item_id})"))?;

    if item.abilities.contains(&ItemAbility::TurnOn) {
        info!("Player switched on {} ({})", item.name(), item.symbol());
        let sent_id = item.id.clone();
        let fired_triggers = check_triggers(
            world,
            view,
            &[TriggerCondition::UseItem {
                item_id: sent_id.clone(),
                ability: ItemAbility::TurnOn,
            }],
        )?;
        let sent_trigger_fired = triggers_contain_condition(&fired_triggers, |cond| match cond {
            TriggerCondition::UseItem { item_id, ability } => item_id == &sent_id && ability == &ItemAbility::TurnOn,
            _ => false,
        });
        if !sent_trigger_fired {
            view.push(ViewItem::ActionFailure(format!(
                "{}",
                "You hear a clicking sound and then... nothing happens.".italic()
            )));
        }
    } else {
        info!(
            "Player tried to turn on unswitchable item {} ({})",
            item.name(),
            item.symbol()
        );
        view.push(ViewItem::ActionFailure(format!(
            "The {} can't be turned on.",
            item.name().item_style()
        )));
    }
    Ok(true)
}

/// Disables an item if it has the ability to be turned off.
///
/// This handler attempts to turn off or disable items in the current room
/// that have switch-like functionality. Items must have the `TurnOff` ability
/// to be stopped, and that can be tied to various game world responses via triggers.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `item_pattern` - Pattern string to match against items in current room
///
/// # Returns
///
/// Returns `Ok(())` after attempting to disable, regardless of success in doing so.
///
/// # Behavior
///
/// - Searches current room for items matching the pattern
/// - Verifies the item has the `TurnOff` ability
/// - Fires `TriggerCondition::UseItem` with `ItemAbility::TurnOff`
/// - Provides appropriate feedback based on whether triggers fire
///
/// # Error Handling
///
/// - Item not found: Standard "not found" message
/// - Item cannot be turned off: Specific capability message
/// - NPC matched: Humorous rejection message
/// - No effect: Generic "nothing happens" message when no triggers fire
///
/// # Errors
/// Returns an error if the player's current room cannot be determined or if trigger execution
/// fails because required world data is missing.
pub fn turn_off_handler(world: &mut AmbleWorld, view: &mut View, item_pattern: &str) -> Result<bool> {
    // search player's location for an item with name matching 'pattern'
    let room_id = world.player_room_id();
    let item_id = match entity_search::find_item_match(world, item_pattern, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(e) => match e {
            SearchError::NoMatchingName(_) => {
                entity_not_found(world, view, item_pattern);
                return Ok(false);
            },
            _ => bail!(e),
        },
    };
    let item = world
        .items
        .get_mut(&item_id)
        .with_context(|| format!("world.items.get_mut({item_id})"))?;
    if item.abilities.contains(&ItemAbility::TurnOff) {
        info!("Player switched off {} ({})", item.name(), item.symbol());
        let sent_id = item.id.clone();
        let fired_triggers = check_triggers(
            world,
            view,
            &[TriggerCondition::UseItem {
                item_id: sent_id.clone(),
                ability: ItemAbility::TurnOff,
            }],
        )?;
        let sent_trigger_fired = triggers_contain_condition(&fired_triggers, |cond| match cond {
            TriggerCondition::UseItem { item_id, ability } => item_id == &sent_id && ability == &ItemAbility::TurnOff,
            _ => false,
        });
        if !sent_trigger_fired {
            view.push(ViewItem::ActionFailure(format!(
                "{}",
                "You hear a clicking sound and then... nothing happens.".italic()
            )));
        }
    } else {
        info!(
            "Player tried to turn off unswitchable item {} ({})",
            item.name(),
            item.symbol()
        );
        view.push(ViewItem::ActionFailure(format!(
            "The {} can't be turned off.",
            item.name().item_style()
        )));
    }

    Ok(true)
}
/// Opens a closed container item, making its contents accessible.
///
/// This handler attempts to open container items that are currently in a
/// closed state. Only unlocked containers can be opened; locked containers
/// must be unlocked first. Opening a container may trigger game events.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `pattern` - Pattern string to match against nearby container items
///
/// # Returns
///
/// Returns `Ok(())` after attempting to open the container.
///
/// # Container State Logic
///
/// - **Non-container**: Cannot be opened (no container state)
/// - **Locked**: Must be unlocked first before opening
/// - **Already open**: Acknowledges current state
/// - **Closed**: Successfully opens and triggers events
///
/// # Trigger Effects
///
/// Opening a container fires `TriggerCondition::Open`, which can:
/// - Reveal items inside the container
/// - Advance puzzle or story logic
/// - Trigger ambient effects or messages
/// - Cause other game state changes
///
/// # Scope
///
/// Searches both the current room and player inventory for containers,
/// allowing players to open containers they're carrying as well as
/// those in their environment.
///
/// # Errors
/// Returns an error if the player's current room cannot be resolved, if the targeted container
/// cannot be retrieved, or if trigger execution fails due to missing data.
pub fn open_handler(world: &mut AmbleWorld, view: &mut View, pattern: &str) -> Result<bool> {
    // search player's location for an item with name matching 'pattern'
    let room_id = world.player_room_id();
    let container_id = match entity_search::find_item_match(world, pattern, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(e) => match e {
            SearchError::NoMatchingName(_) => {
                entity_not_found(world, view, pattern);
                return Ok(false);
            },
            _ => bail!(e),
        },
    };

    // either show failure reasons, or set container state to open
    let mut container_opened = false;
    if let Some(target_item) = world.get_item_mut(&container_id) {
        match target_item.container_state {
            None => {
                view.push(ViewItem::ActionFailure(format!(
                    "The {} can't be opened.",
                    target_item.name().item_style()
                )));
            },
            Some(ContainerState::Locked | ContainerState::TransparentLocked) => {
                view.push(ViewItem::ActionFailure(format!(
                    "The {} is locked. You'll have to unlock it first.",
                    target_item.name().item_style()
                )));
            },
            Some(ContainerState::Open | ContainerState::TransparentOpen) => {
                view.push(ViewItem::ActionSuccess(format!(
                    "The {} is already open.",
                    target_item.name().item_style()
                )));
            },
            Some(ContainerState::Closed) => {
                // check to see if any particular interaction type is required to open
                if let Some(required_ability) = target_item.interaction_requires.get(&ItemInteractionType::Open) {
                    view.push(ViewItem::ActionFailure(format!(
                        "The {} can't be opened without using something that can {}.",
                        target_item.name().item_style(),
                        required_ability.to_string().highlight()
                    )));
                } else {
                    target_item.container_state = Some(ContainerState::Open);
                    container_opened = true;
                }
            },
            Some(ContainerState::TransparentClosed) => {
                // check to see if any particular interaction type is required to open
                if let Some(required_ability) = target_item.interaction_requires.get(&ItemInteractionType::Open) {
                    view.push(ViewItem::ActionFailure(format!(
                        "The {} can't be opened without using something that can {}.",
                        target_item.name().item_style(),
                        required_ability.to_string().highlight()
                    )));
                } else {
                    target_item.container_state = Some(ContainerState::TransparentOpen);
                    container_opened = true;
                }
            },
        }
    }

    // if a container was successfully opened: tell player, show contents, and log it
    if let Some(opened) = world.items.get(&container_id)
        && container_opened
    {
        opened.show(world, view);
        info!(
            "{} opened the {} ({})",
            world.player.name(),
            opened.name(),
            opened.symbol()
        );
        view.push_with_priority(
            ViewItem::ActionSuccess(format!("You opened the {}.\n", opened.name().item_style())),
            -100,
        );
        check_triggers(world, view, &[TriggerCondition::Open(container_id.clone())])?;
    }

    Ok(true)
}

/// Closes an open container item, hiding its contents from view.
///
/// This handler closes container items that are currently open, which can
/// be useful for organization, security, or puzzle mechanics. Closing containers
/// does not trigger game events but changes their accessibility state.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `pattern` - Pattern string to match against nearby container items
///
/// # Returns
///
/// Returns `Ok(())` after attempting to close the container.
///
/// # Container State Logic
///
/// - **Non-container**: Cannot be closed (no container state)
/// - **Already closed/locked**: Acknowledges current state
/// - **Open**: Successfully closes the container
///
/// # Behavior
///
/// Unlike opening, closing containers does not trigger game events.
/// This is primarily a state management operation that affects item
/// visibility and access but not game progression.
///
/// # Scope
///
/// Searches both current room and player inventory for containers,
/// allowing closure of both environmental and carried containers.
///
/// # Errors
/// Returns an error if the player's current room cannot be resolved or if the targeted container
/// cannot be retrieved from the world.
pub fn close_handler(world: &mut AmbleWorld, view: &mut View, pattern: &str) -> Result<bool> {
    // search player's location for an item with name matching 'pattern'
    let room_id = world.player_room_id();
    let container_id = match entity_search::find_item_match(world, pattern, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(e) => match e {
            SearchError::NoMatchingName(_) => {
                entity_not_found(world, view, pattern);
                return Ok(false);
            },
            _ => bail!(e),
        },
    };

    if let Some(target_item) = world.get_item_mut(&container_id) {
        let item_name = target_item.name().to_owned();
        let item_sym = target_item.symbol().to_owned();

        match target_item.container_state {
            None => {
                view.push(ViewItem::ActionFailure(format!(
                    "The {} can't be closed.",
                    target_item.name().item_style()
                )));
            },
            Some(
                ContainerState::Closed
                | ContainerState::Locked
                | ContainerState::TransparentClosed
                | ContainerState::TransparentLocked,
            ) => {
                view.push(ViewItem::ActionSuccess(format!(
                    "The {} is already closed.",
                    item_name.item_style()
                )));
            },
            Some(ContainerState::Open) => {
                target_item.container_state = Some(ContainerState::Closed);
                view.push(ViewItem::ActionSuccess(format!(
                    "You closed the {}.\n",
                    item_name.item_style()
                )));
                info!("{} closed the {} ({})", world.player.name(), item_name, item_sym);
            },
            Some(ContainerState::TransparentOpen) => {
                target_item.container_state = Some(ContainerState::TransparentClosed);
                view.push(ViewItem::ActionSuccess(format!(
                    "You closed the {}.\n",
                    target_item.name().item_style()
                )));
                info!("{} closed the {} ({})", world.player.name(), item_name, item_sym);
            },
        }
    }
    Ok(true)
}

/// Locks a container item, securing it against unauthorized access.
///
/// This handler locks container items, preventing them from being opened
/// until they are unlocked with an appropriate key. Locking is primarily
/// used for puzzle mechanics and security.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `pattern` - Pattern string to match against containers in current room
///
/// # Returns
///
/// Returns `Ok(())` after attempting to lock the container.
///
/// # Container State Logic
///
/// - **Non-container**: Cannot be locked (no lock mechanism)
/// - **Already locked**: Acknowledges current state
/// - **Open/Closed**: Successfully locks the container
///
/// # Key Requirements
///
/// Unlike unlocking, locking typically doesn't require specific keys
/// in most game implementations, though this could be extended to
/// require lock-specific tools or abilities.
///
/// # Scope
///
/// Only searches the current room for containers to lock, as locking
/// items in inventory is less commonly needed in gameplay scenarios.
///
/// # Errors
/// Returns an error if the player's current room cannot be determined or if the targeted container
/// cannot be located within the world state.
pub fn lock_handler(world: &mut AmbleWorld, view: &mut View, pattern: &str) -> Result<bool> {
    // search player's location for an item with name matching 'pattern'
    let room_id = world.player_room_id();
    let container_id = match entity_search::find_item_match(world, pattern, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(e) => match e {
            SearchError::NoMatchingName(_) => {
                entity_not_found(world, view, pattern);
                return Ok(false);
            },
            _ => bail!(e),
        },
    };

    if let Some(target_item) = world.get_item_mut(&container_id) {
        let item_name = target_item.name().to_owned();
        let item_sym = target_item.symbol().to_owned();
        match target_item.container_state {
            None => {
                view.push(ViewItem::ActionFailure(format!(
                    "The {} isn't something that can be locked.",
                    item_name.item_style()
                )));
            },
            Some(ContainerState::Locked | ContainerState::TransparentLocked) => {
                view.push(ViewItem::ActionSuccess(format!(
                    "The {} is already locked.",
                    item_name.item_style()
                )));
            },
            Some(ContainerState::Open | ContainerState::Closed) => {
                target_item.container_state = Some(ContainerState::Locked);
                view.push(ViewItem::ActionSuccess(format!(
                    "You locked the {}.\n",
                    item_name.item_style()
                )));
                info!("{} locked the {} ({})", world.player.name(), item_name, item_sym);
            },
            Some(ContainerState::TransparentOpen | ContainerState::TransparentClosed) => {
                target_item.container_state = Some(ContainerState::TransparentLocked);
                view.push(ViewItem::ActionSuccess(format!(
                    "You locked the {}.\n",
                    item_name.item_style()
                )));
                info!("{} locked the {} ({})", world.player.name(), item_name, item_sym);
            },
        }
    }
    Ok(true)
}

/// Unlocks a locked container using an appropriate key from inventory.
///
/// This handler attempts to unlock locked containers by checking the player's
/// inventory for items with the appropriate unlocking abilities. Success
/// requires having the right key, and unlocking may trigger game events.
///
/// # Parameters
///
/// * `world` - Mutable reference to the game world
/// * `view` - Mutable reference to the player's view for feedback messages
/// * `pattern` - Pattern string to match against containers in current room
///
/// # Returns
///
/// Returns `Ok(())` after attempting to unlock the container.
///
/// # Key System
///
/// The function searches inventory for items with `ItemAbility::Unlock`:
/// - **Specific keys**: Target a particular container by id
/// - **Universal keys**: Can unlock any container (master keys)
///
/// # Container State Logic
///
/// - **Non-container**: Cannot be unlocked (no lock)
/// - **Already unlocked**: Acknowledges current state
/// - **Locked with valid key**: Successfully unlocks to closed state
/// - **Locked without key**: Denies access with helpful message
///
/// # Trigger Effects
///
/// Unlocking fires `TriggerCondition::Unlock`, which can:
/// - Advance puzzle sequences requiring specific unlocking order
/// - Reveal important story items or clues
/// - Trigger narrative events or character reactions
/// - Enable access to new areas or content
///
/// # Security Model
///
/// The key must be in the player's inventory - keys in the room or
/// in other containers cannot be used, maintaining gameplay challenge.
///
/// # Errors
/// Returns an error if the player's current room cannot be determined, if the targeted container
/// cannot be resolved from the world state, or if trigger evaluation fails.
pub fn unlock_handler(world: &mut AmbleWorld, view: &mut View, pattern: &str) -> Result<bool> {
    // search player's location for an item with name matching 'pattern'
    let room_id = world.player_room_id();
    let container_id = match entity_search::find_item_match(world, pattern, SearchScope::TouchableItems(room_id)) {
        Ok(uuid) => uuid,
        Err(e) => match e {
            SearchError::NoMatchingName(_) => {
                entity_not_found(world, view, pattern);
                return Ok(false);
            },
            _ => bail!(e),
        },
    };

    let key_data = find_valid_key(&world.items, &world.player.inventory, &container_id);

    let mut consumed_turn = false;
    if let Some(target_item) = world.get_item_mut(&container_id) {
        consumed_turn = true;
        let item_name = target_item.name().to_owned();
        let item_sym = target_item.symbol().to_owned();
        match target_item.container_state {
            None => {
                view.push(ViewItem::ActionFailure(format!(
                    "The {} doesn't have a lock.",
                    item_name.item_style()
                )));
            },
            Some(
                ContainerState::Open
                | ContainerState::TransparentOpen
                | ContainerState::Closed
                | ContainerState::TransparentClosed,
            ) => {
                view.push(ViewItem::ActionSuccess(format!(
                    "The {} is already unlocked.",
                    item_name.item_style()
                )));
            },
            Some(ContainerState::Locked | ContainerState::TransparentLocked) => {
                if let Some(key) = key_data {
                    // If it was transparent locked, make it transparent closed, otherwise regular closed
                    target_item.container_state =
                        if target_item.container_state == Some(ContainerState::TransparentLocked) {
                            Some(ContainerState::TransparentClosed)
                        } else {
                            Some(ContainerState::Closed)
                        };
                    view.push(ViewItem::ActionSuccess(format!(
                        "You unlocked the {} with the {}.\n",
                        item_name.item_style(),
                        key.name.item_style(),
                    )));
                    info!(
                        "{} unlocked '{}' ({}) using key '{}' ({})",
                        world.player.name(),
                        item_name,
                        item_sym,
                        key.name,
                        key.symbol,
                    );
                    check_triggers(world, view, &[TriggerCondition::Unlock(container_id.clone())])?;
                } else {
                    view.push(ViewItem::ActionFailure(format!(
                        "You don't have anything that can unlock the {}.",
                        item_name.item_style()
                    )));
                }
            },
        }
    }
    Ok(consumed_turn)
}

// Key metadata.
#[derive(Debug, Clone, PartialEq)]
struct KeyData {
    id: ItemId,
    name: String,
    symbol: String,
    skeleton: bool,
}

/// Search a list of items for a valid key to a given lock and return `KeyData` if found.
///
/// If a specific key *and* a "skeleton" key are present, the data for the specific key is
/// returned.
fn find_valid_key(
    world_items: &HashMap<ItemId, Item>,
    maybe_keys: &HashSet<ItemId>,
    container: &ItemId,
) -> Option<KeyData> {
    // find and return a specific key
    let specific = maybe_keys
        .iter()
        .filter_map(|uuid| world_items.get(uuid))
        .find(|item| item.abilities.contains(&ItemAbility::Unlock(Some(container.clone()))));
    if let Some(key) = specific {
        return Some(KeyData {
            id: key.id.clone(),
            name: key.name.clone(),
            symbol: key.symbol.clone(),
            skeleton: false,
        });
    }
    // if no specific key, find and return a skeleton key
    let skeleton = maybe_keys
        .iter()
        .filter_map(|uuid| world_items.get(uuid))
        .find(|item| item.abilities.contains(&ItemAbility::Unlock(None)));
    if let Some(key) = skeleton {
        return Some(KeyData {
            id: key.id.clone(),
            name: key.name.clone(),
            symbol: key.symbol.clone(),
            skeleton: true,
        });
    }
    // there is no key for this container on the list
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        item::{ContainerState, Item, ItemAbility, ItemInteractionType, Movability},
        room::Room,
        scheduler::EventCondition,
        trigger::{ScriptedAction, Trigger, TriggerAction, TriggerCondition},
        world::{AmbleWorld, Location},
    };
    use std::collections::{HashMap, HashSet};

    #[allow(clippy::too_many_lines)]
    fn build_world() -> (AmbleWorld, View, ItemId, ItemId, ItemId, ItemId) {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_room_id();
        let room = Room {
            id: room_id.clone(),
            symbol: "r".into(),
            name: "Room".into(),
            base_description: String::new(),
            overlays: Vec::new(),
            scenery: Vec::new(),
            scenery_default: None,
            location: Location::Nowhere,
            visited: false,
            exits: HashMap::new(),
            contents: HashSet::new(),
            npcs: HashSet::new(),
        };
        world.rooms.insert(room_id.clone(), room);
        world.player.location = Location::Room(room_id.clone());

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = Item {
            id: container_id.clone(),
            symbol: "c".into(),
            name: "chest".into(),
            description: String::new(),
            location: Location::Room(room_id.clone()),
            visibility: crate::item::ItemVisibility::Listed,
            visible_when: None,
            aliases: Vec::new(),
            container_state: Some(ContainerState::Locked),
            movability: Movability::Free,
            contents: HashSet::new(),
            abilities: HashSet::new(),
            interaction_requires: HashMap::new(),
            text: None,
            consumable: None,
        };
        container
            .interaction_requires
            .insert(ItemInteractionType::Open, ItemAbility::Pry);
        world
            .rooms
            .get_mut(&room_id)
            .unwrap()
            .contents
            .insert(container_id.clone());
        world.items.insert(container_id.clone(), container);

        let tool_id: ItemId = crate::idgen::new_id().into();
        let tool = Item {
            id: tool_id.clone(),
            symbol: "t".into(),
            name: "crowbar".into(),
            description: String::new(),
            location: Location::Inventory,
            visibility: crate::item::ItemVisibility::Listed,
            visible_when: None,
            aliases: Vec::new(),
            movability: Movability::Free,
            container_state: None,
            contents: HashSet::new(),
            abilities: [ItemAbility::Pry].into_iter().collect(),
            interaction_requires: HashMap::new(),
            text: None,
            consumable: None,
        };
        world.player.inventory.insert(tool_id.clone());
        world.items.insert(tool_id.clone(), tool);

        let lamp_id: ItemId = crate::idgen::new_id().into();
        let lamp = Item {
            id: lamp_id.clone(),
            symbol: "l".into(),
            name: "lamp".into(),
            description: String::new(),
            location: Location::Room(room_id.clone()),
            container_state: None,
            visibility: crate::item::ItemVisibility::Listed,
            visible_when: None,
            aliases: Vec::new(),
            movability: Movability::Fixed {
                reason: "lamp is glued to floor".to_string(),
            },
            contents: HashSet::new(),
            abilities: [ItemAbility::TurnOn].into_iter().collect(),
            interaction_requires: HashMap::new(),
            text: None,
            consumable: None,
        };
        world.rooms.get_mut(&room_id).unwrap().contents.insert(lamp_id.clone());
        world.items.insert(lamp_id.clone(), lamp);

        let key_id: ItemId = crate::idgen::new_id().into();
        let key = Item {
            id: key_id.clone(),
            symbol: "k".into(),
            name: "key".into(),
            description: String::new(),
            location: Location::Inventory,
            visibility: crate::item::ItemVisibility::Listed,
            visible_when: None,
            aliases: Vec::new(),
            movability: Movability::Free,
            container_state: None,
            contents: HashSet::new(),
            abilities: [ItemAbility::Unlock(Some(container_id.clone()))].into_iter().collect(),
            interaction_requires: HashMap::new(),
            text: None,
            consumable: None,
        };
        world.player.inventory.insert(key_id.clone());
        world.items.insert(key_id.clone(), key);
        let view = View::new();

        (world, view, container_id, tool_id, lamp_id, key_id)
    }

    #[test]
    fn use_item_on_handler_unlocks_container() {
        let (mut world, mut view, container_id, tool_id, _, _) = build_world();
        world.triggers.push(Trigger {
            name: "open".into(),
            conditions: EventCondition::Trigger(TriggerCondition::UseItemOnItem {
                interaction: ItemInteractionType::Open,
                target_id: container_id.clone(),
                tool_id: tool_id.clone(),
            }),
            actions: vec![ScriptedAction::new(TriggerAction::UnlockItem(container_id.clone()))],
            only_once: false,
            fired: false,
        });
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Locked)
        );
        use_item_on_handler(&mut world, &mut view, ItemInteractionType::Open, "crowbar", "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Open)
        );
    }

    #[test]
    fn use_item_on_handler_without_ability_does_nothing() {
        let (mut world, mut view, container_id, tool_id, _, _) = build_world();
        world.items.get_mut(&tool_id).unwrap().abilities.clear();
        world.triggers.push(Trigger {
            name: "open".into(),
            conditions: EventCondition::Trigger(TriggerCondition::UseItemOnItem {
                interaction: ItemInteractionType::Open,
                target_id: container_id.clone(),
                tool_id: tool_id.clone(),
            }),
            actions: vec![ScriptedAction::new(TriggerAction::UnlockItem(container_id.clone()))],
            only_once: false,
            fired: false,
        });
        use_item_on_handler(&mut world, &mut view, ItemInteractionType::Open, "crowbar", "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Locked)
        );
    }

    #[test]
    fn turn_on_handler_triggers_unlock() {
        let (mut world, mut view, container_id, _, lamp_id, _) = build_world();
        world.triggers.push(Trigger {
            name: "light".into(),
            conditions: EventCondition::Trigger(TriggerCondition::UseItem {
                item_id: lamp_id.clone(),
                ability: ItemAbility::TurnOn,
            }),
            actions: vec![ScriptedAction::new(TriggerAction::UnlockItem(container_id.clone()))],
            only_once: false,
            fired: false,
        });
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Locked)
        );
        turn_on_handler(&mut world, &mut view, "lamp").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Open)
        );
    }

    #[test]
    fn open_handler_opens_closed_container() {
        let (mut world, mut view, container_id, _, _, _) = build_world();
        world.items.get_mut(&container_id).unwrap().container_state = Some(ContainerState::Closed);
        world
            .items
            .get_mut(&container_id)
            .unwrap()
            .interaction_requires
            .remove(&ItemInteractionType::Open);
        open_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Open)
        );
    }

    #[test]
    fn open_handler_will_not_open_container_with_special_open_requirements() {
        let (mut world, mut view, container_id, _, _, _) = build_world();
        world.items.get_mut(&container_id).unwrap().container_state = Some(ContainerState::Closed);
        // note -- the "chest" test item is defined as requiring "pry" to "open"
        open_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Closed)
        );
    }

    #[test]
    fn open_handler_locked_container_stays_locked() {
        let (mut world, mut view, container_id, _, _, _) = build_world();
        open_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Locked)
        );
    }

    #[test]
    fn close_handler_closes_open_container() {
        let (mut world, mut view, container_id, _, _, _) = build_world();
        world.items.get_mut(&container_id).unwrap().container_state = Some(ContainerState::Open);
        close_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Closed)
        );
    }

    #[test]
    fn lock_handler_locks_container() {
        let (mut world, mut view, container_id, _, _, _) = build_world();
        world.items.get_mut(&container_id).unwrap().container_state = Some(ContainerState::Closed);
        lock_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Locked)
        );
    }

    #[test]
    fn unlock_handler_with_key_unlocks_container() {
        let (mut world, mut view, container_id, _, _, _) = build_world();
        unlock_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Closed)
        );
    }

    #[test]
    fn unlock_handler_without_key_does_not_unlock() {
        let (mut world, mut view, container_id, _, _, key_id) = build_world();
        world.player.inventory.remove(&key_id);
        unlock_handler(&mut world, &mut view, "chest").unwrap();
        assert_eq!(
            world.items.get(&container_id).unwrap().container_state,
            Some(ContainerState::Locked)
        );
    }
}