manabrew-engine 0.6.0

Magic: The Gathering rules engine — a Rust port of Forge
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
use super::{resolve_numeric_svar, EffectContext};
use crate::agent::PlayerAgent;
use crate::game::GameState;
use crate::ids::PlayerId;
use crate::parsing::keys;
use crate::parsing::Params;
use crate::spellability::{build_spell_ability, SpellAbility};

/// Scope of a `ChoiceRestriction$` on `SP$ Charm`. Past selections within
/// this scope are filtered out of the available mode list.
/// Mirrors Java's `CharmEffect` string literals.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum_macros::EnumString)]
#[strum(ascii_case_insensitive)]
pub enum ChoiceRestriction {
    ThisGame,
    ThisTurn,
    YourLastCombat,
}

/// `SP$ Charm` — modal spell: player chooses N effects from a list.
///
/// Mirrors Java's `CharmEffect.java`.
///
/// # Card script format
/// ```text
/// A:SP$ Charm | Choices$ Mode1,Mode2,Mode3 | [CharmNum$ 2] | [MinCharmNum$ 1]
/// SVar:Mode1:DB$ Draw | NumCards$ 1 | SpellDescription$ Draw a card.
/// SVar:Mode2:DB$ Destroy | ValidTgts$ Creature | SpellDescription$ Destroy target creature.
/// ```
///
/// Struct form of this effect so it can participate in the
/// `SpellAbilityEffect` trait hierarchy — mirrors Java's
/// `CharmEffect` class extending `SpellAbilityEffect`.
#[manabrew_engine_macros::spell_effect(CharmEffect)]
fn resolve(ctx: &mut EffectContext, sa: &crate::spellability::SpellAbility) {
    // Java chains chosen charm modes onto the root SpellAbility during casting
    // (via make_choices_precast), then the stack resolver walks the full
    // sub-ability chain. If sub-abilities are already present, just return —
    // the stack's resolve_ability loop will walk and resolve each sub-ability.
    if sa.sub_ability.is_some() {
        return;
    }

    let source_id = match sa.source {
        Some(id) => id,
        None => return,
    };

    let choices_str = sa.ir.choices.clone().unwrap_or_default();
    if choices_str.is_empty() {
        return;
    }

    let charm_num = resolve_numeric_svar(ctx.game, sa, keys::CHARM_NUM, 1).max(0) as usize;
    let min_charm_num =
        resolve_numeric_svar(ctx.game, sa, keys::MIN_CHARM_NUM, charm_num as i32).max(0) as usize;

    let player = sa.activating_player;

    // Collect SVar names for each mode
    let mode_svars: Vec<&str> = choices_str.split(',').map(|s| s.trim()).collect();

    // Get mode texts from the source card's SVars
    let svars = ctx.game.card(source_id).svars.clone();
    let mode_texts: Vec<String> = mode_svars
        .iter()
        .filter_map(|svar| svars.get(*svar).cloned())
        .collect();

    if mode_texts.is_empty() {
        return;
    }

    // Extract SpellDescription$ for each mode (human-readable label)
    let mode_descriptions: Vec<String> = mode_texts
        .iter()
        .map(|text| {
            let params = Params::from_raw(text);
            params
                .get_cloned(keys::SPELL_DESCRIPTION)
                .unwrap_or_else(|| text.clone())
        })
        .collect();

    // `ChoiceRestriction$` — drop modes already chosen on this source within
    // the restriction scope. Java tracks per-source history on
    // `Card.chosenModesThisGame` etc.; Rust stores a {mode_svar → turn_number}
    // map on the Card keyed by the scope enum below.
    let restriction = sa
        .ir
        .choice_restriction_text
        .as_deref()
        .and_then(|s| s.parse::<ChoiceRestriction>().ok());
    let current_turn = ctx.game.turn.turn_number as i32;
    let last_combat_turn = ctx
        .game
        .last_combat_turn_of(sa.activating_player)
        .unwrap_or(i32::MIN);
    let is_restricted_index = |mode_svar: &str| -> bool {
        let Some(scope) = restriction else {
            return false;
        };
        let history = &ctx.game.card(source_id).chosen_charm_modes;
        let Some(&turn) = history.get(mode_svar) else {
            return false;
        };
        match scope {
            ChoiceRestriction::ThisGame => true,
            ChoiceRestriction::ThisTurn => turn == current_turn,
            ChoiceRestriction::YourLastCombat => turn >= last_combat_turn,
        }
    };

    // Filter modes to only those with valid targets (matching Java's CharmEffect
    // which passes only `possible` modes to chooseModeForAbility).
    let valid_mode_indices: Vec<usize> = mode_texts
        .iter()
        .enumerate()
        .filter(|(i, text)| {
            !is_restricted_index(mode_svars[*i])
                && mode_has_valid_targets(ctx, text, player, source_id)
        })
        .map(|(i, _)| i)
        .collect();

    if valid_mode_indices.is_empty() {
        return; // No modes have valid targets — spell fizzles
    }

    let valid_descriptions: Vec<String> = valid_mode_indices
        .iter()
        .map(|&i| mode_descriptions[i].clone())
        .collect();

    // Check if Entwine was paid (SA flag) — if so, auto-select all modes
    let entwine_paid = sa.ir.entwine || sa.kicked; // Entwine is sometimes represented as kicked

    // Check source card for Entwine/Escalate keywords
    let has_entwine = ctx.game.card(source_id).get_entwine_cost().is_some();
    let has_escalate = ctx.game.card(source_id).get_escalate_cost().is_some();

    // If Escalate, allow choosing more modes (up to all)
    let charm_num = if has_escalate {
        mode_texts.len()
    } else {
        charm_num
    };

    // Ask the activating player to choose mode(s)
    let use_preselected_modes = should_use_preselected_modes(ctx.game, source_id, &mode_texts);
    // Check if modes were pre-selected (Spree — chosen during casting before payment)
    let pre_selected = if use_preselected_modes {
        ctx.game.card_mut(source_id).chosen_modes.take()
    } else {
        ctx.game.card_mut(source_id).chosen_modes = None;
        None
    };
    let mut chosen_indices: Vec<usize> = if let Some(pre) = pre_selected {
        // Spree: modes already chosen before payment
        pre
    } else if entwine_paid || (has_entwine && sa.kicked) {
        // Entwine: all valid modes (mapped back to original indices)
        valid_mode_indices.clone()
    } else {
        let agent_choices = ctx.agents[player.index()].choose_mode(
            player,
            &valid_descriptions,
            min_charm_num,
            charm_num.min(valid_mode_indices.len()),
            Some(source_id),
        );
        // Map agent choices (indices into valid_descriptions) back to original mode indices
        agent_choices
            .into_iter()
            .filter_map(|i| valid_mode_indices.get(i).copied())
            .collect()
    };

    // Java `CharmEffect.chainAbilities` sorts chosen modes by their declared
    // `CharmOrder` (1-based `Choices$` list index) before resolving, so Destroy
    // always runs before GainLife even if the player picked GainLife first.
    // Mirror that here — agent pick order must not leak into target prompts.
    chosen_indices.sort();

    // Record chosen modes into source card's history so a future cast can
    // honor `ChoiceRestriction$`. Also honors `CanRepeatModes` (Rust default)
    // vs dedup mode.
    for &idx in &chosen_indices {
        if let Some(svar_name) = mode_svars.get(idx).copied() {
            ctx.game
                .card_mut(source_id)
                .chosen_charm_modes
                .insert(svar_name.to_string(), current_turn);
        }
    }

    // Resolve each chosen mode in declaration order
    for idx in chosen_indices {
        if idx >= mode_texts.len() {
            continue;
        }
        let mode_text = &mode_texts[idx];

        // Build the mode's SpellAbility (recursively includes SubAbility$ chain)
        let mut mode_sa = build_spell_ability(ctx.game, source_id, mode_text, player);
        mode_sa.source = Some(source_id);
        // Propagate trigger context from parent SA to mode SA so that
        // effects like Modular can read trigger_remembered_amount.
        mode_sa.trigger_remembered_amount = sa.trigger_remembered_amount;

        // Walk the sub-ability chain: set targets then resolve each node
        let mut cur_opt: Option<SpellAbility> = Some(mode_sa);
        while let Some(mut cur_sa) = cur_opt {
            setup_mode_targets(ctx, &mut cur_sa, player);
            super::resolve_effect(ctx, &cur_sa);
            // Descend into sub-ability (unbox)
            cur_opt = cur_sa.sub_ability.map(|b| *b);
            if ctx.game.game_over {
                break;
            }
        }

        if ctx.game.game_over {
            break;
        }
    }
}

pub fn make_choices_precast(
    game: &mut GameState,
    agents: &mut [Box<dyn PlayerAgent>],
    sa: &mut SpellAbility,
) -> bool {
    make_choices_precast_with_count(game, agents, sa).is_some()
}

pub fn make_choices_precast_with_count(
    game: &mut GameState,
    agents: &mut [Box<dyn PlayerAgent>],
    sa: &mut SpellAbility,
) -> Option<usize> {
    let source_id = match sa.source {
        Some(id) => id,
        None => return Some(0),
    };

    let choices_str = sa.ir.choices.clone().unwrap_or_default();
    if choices_str.is_empty() {
        return Some(0);
    }

    let player = sa.activating_player;
    let mode_svars: Vec<&str> = choices_str.split(',').map(|s| s.trim()).collect();
    let svars = game.card(source_id).svars.clone();
    let mode_texts: Vec<String> = mode_svars
        .iter()
        .filter_map(|svar| svars.get(*svar).cloned())
        .collect();
    if mode_texts.is_empty() {
        return None;
    }

    let mode_descriptions: Vec<String> = mode_texts
        .iter()
        .map(|text| {
            let params = Params::from_raw(text);
            params
                .get_cloned(keys::SPELL_DESCRIPTION)
                .unwrap_or_else(|| text.clone())
        })
        .collect();

    // Drop modes already chosen on this source within the `ChoiceRestriction$`
    // scope (mirror of the same filter in `resolve` — must run here too because
    // triggered abilities make their mode choices precast and the resolver only
    // consumes the pre-selected list).
    let restriction = sa
        .ir
        .choice_restriction_text
        .as_deref()
        .and_then(|s| s.parse::<ChoiceRestriction>().ok());
    let current_turn = game.turn.turn_number as i32;
    let last_combat_turn = game.last_combat_turn_of(player).unwrap_or(i32::MIN);
    let is_restricted_index = |mode_svar: &str| -> bool {
        let Some(scope) = restriction else {
            return false;
        };
        let history = &game.card(source_id).chosen_charm_modes;
        let Some(&turn) = history.get(mode_svar) else {
            return false;
        };
        match scope {
            ChoiceRestriction::ThisGame => true,
            ChoiceRestriction::ThisTurn => turn == current_turn,
            ChoiceRestriction::YourLastCombat => turn >= last_combat_turn,
        }
    };

    let valid_mode_indices: Vec<usize> = mode_texts
        .iter()
        .enumerate()
        .filter(|(i, text)| {
            !is_restricted_index(mode_svars[*i])
                && mode_has_valid_targets_in_game(game, text, player, source_id)
        })
        .map(|(i, _)| i)
        .collect();
    if valid_mode_indices.is_empty() {
        return None;
    }

    let valid_descriptions: Vec<String> = valid_mode_indices
        .iter()
        .map(|&i| mode_descriptions[i].clone())
        .collect();

    let has_entwine = game.card(source_id).get_entwine_cost().is_some();
    let has_escalate = game.card(source_id).get_escalate_cost().is_some();
    let can_repeat = sa.ir.can_repeat_modes;

    let mut charm_num = resolve_numeric_svar(game, sa, keys::CHARM_NUM, 1).max(0) as usize;
    let min_charm_num =
        resolve_numeric_svar(game, sa, keys::MIN_CHARM_NUM, charm_num as i32).max(0) as usize;
    if has_escalate {
        charm_num = mode_texts.len();
    }
    if !can_repeat && min_charm_num > valid_mode_indices.len() {
        return None;
    }

    let use_preselected_modes = should_use_preselected_modes(game, source_id, &mode_texts);
    let pre_selected = if use_preselected_modes {
        game.card_mut(source_id).chosen_modes.take()
    } else {
        game.card_mut(source_id).chosen_modes = None;
        None
    };
    let mut chosen_indices: Vec<usize> = if let Some(pre) = pre_selected {
        pre
    } else if sa.ir.entwine || (has_entwine && sa.kicked) {
        valid_mode_indices.clone()
    } else {
        let chosen = agents[player.index()].choose_mode(
            player,
            &valid_descriptions,
            min_charm_num,
            charm_num.min(valid_mode_indices.len()),
            Some(source_id),
        );
        chosen
            .into_iter()
            .filter_map(|i| valid_mode_indices.get(i).copied())
            .collect()
    };

    if chosen_indices.len() < min_charm_num {
        return None;
    }

    // Mirror Java's `CharmEffect.chainAbilities`: resolve modes in the order
    // they were declared (CharmOrder), not in the order the player picked
    // them. Otherwise mode target prompts fire in agent-pick order and
    // cascade RNG divergences vs Java.
    chosen_indices.sort();
    let selected_mode_count = chosen_indices.len();

    // Record chosen modes into the source's history so the *next* trigger
    // fire on this source (e.g. another Teval's Judgment trigger from the
    // same turn's graveyard movements) honors `ChoiceRestriction$ ThisTurn`.
    // The resolve-time path also records, but precast-driven flows like
    // triggered Charms never reach the resolver's recorder for the freshly
    // built SA, so we have to do it here too.
    for &idx in &chosen_indices {
        if let Some(svar_name) = mode_svars.get(idx).copied() {
            game.card_mut(source_id)
                .chosen_charm_modes
                .insert(svar_name.to_string(), current_turn);
        }
    }

    sa.sub_ability = None;
    let parent_trigger_remembered = sa.trigger_remembered_amount;
    for idx in chosen_indices {
        if idx >= mode_texts.len() {
            continue;
        }
        let mut mode_sa = build_spell_ability(game, source_id, &mode_texts[idx], player);
        mode_sa.source = Some(source_id);
        // Propagate trigger context from parent SA so effects like Modular
        // can access trigger_remembered_amount at resolution time.
        mode_sa.trigger_remembered_amount = parent_trigger_remembered;
        append_subability(sa, mode_sa);
    }

    Some(selected_mode_count)
}

/// Pre-cast legality check for Charm mode selection.
///
/// Mirrors Java `CharmEffect.makeChoices` behavior enough to decide whether the
/// cast should proceed at all: if not enough legal modes exist, casting fails.
pub(crate) fn can_make_choices_precast(
    game: &GameState,
    player: PlayerId,
    source_id: crate::ids::CardId,
    charm_sa_text: &str,
) -> bool {
    let sa_params = Params::from_raw(charm_sa_text);
    let Some(choices_str) = sa_params.get(keys::CHOICES) else {
        return true;
    };

    let mode_svars: Vec<&str> = choices_str.split(',').map(|s| s.trim()).collect();
    if mode_svars.is_empty() {
        return false;
    }

    let svars = game.card(source_id).svars.clone();
    let mode_texts: Vec<String> = mode_svars
        .iter()
        .filter_map(|svar| svars.get(*svar).cloned())
        .collect();
    if mode_texts.is_empty() {
        return false;
    }

    let mut charm_num: usize = sa_params
        .get(keys::CHARM_NUM)
        .and_then(|s| {
            s.parse().ok().or_else(|| {
                // If not a plain integer, try resolving as an SVar from the source card.
                game.card(source_id)
                    .svars
                    .get(s.trim())
                    .and_then(|v| v.parse().ok())
            })
        })
        .unwrap_or(1);
    let min_charm_num: usize = sa_params
        .get(keys::MIN_CHARM_NUM)
        .and_then(|s| {
            s.parse().ok().or_else(|| {
                game.card(source_id)
                    .svars
                    .get(s.trim())
                    .and_then(|v| v.parse().ok())
            })
        })
        .unwrap_or(charm_num);
    let can_repeat = sa_params.has(keys::CAN_REPEAT_MODES);

    let valid_count = mode_texts
        .iter()
        .filter(|text| mode_has_valid_targets_in_game(game, text, player, source_id))
        .count();

    if valid_count == 0 {
        return false;
    }

    if !can_repeat && min_charm_num > valid_count {
        return false;
    }

    if !can_repeat {
        charm_num = charm_num.min(valid_count);
    }

    charm_num >= min_charm_num
}

/// Collect valid mode indices for a charm/modal spell.
/// Mirrors Java's `CharmEffect.makePossibleOptions(SpellAbility)`.
///
/// Returns the indices (into the mode list) of modes that have valid targets.
pub fn make_possible_options(
    game: &GameState,
    source_id: crate::ids::CardId,
    player: PlayerId,
    choices_str: &str,
) -> Vec<usize> {
    let mode_svars: Vec<&str> = choices_str.split(',').map(|s| s.trim()).collect();
    let svars = game.card(source_id).svars.clone();
    let mode_texts: Vec<String> = mode_svars
        .iter()
        .filter_map(|svar| svars.get(*svar).cloned())
        .collect();

    mode_texts
        .iter()
        .enumerate()
        .filter(|(_, text)| mode_has_valid_targets_in_game(game, text, player, source_id))
        .map(|(i, _)| i)
        .collect()
}

/// Build a formatted description string for charm mode choices.
/// Mirrors Java's `CharmEffect.makeFormatedDescription(SpellAbility)`.
///
/// Returns a description listing all available modes with their descriptions.
pub fn make_formated_description(
    game: &GameState,
    source_id: crate::ids::CardId,
    choices_str: &str,
) -> String {
    let mode_svars: Vec<&str> = choices_str.split(',').map(|s| s.trim()).collect();
    let svars = game.card(source_id).svars.clone();
    let mode_texts: Vec<String> = mode_svars
        .iter()
        .filter_map(|svar| svars.get(*svar).cloned())
        .collect();

    let mut description = String::new();
    description.push_str("Choose one —\n");
    for (i, text) in mode_texts.iter().enumerate() {
        let params = Params::from_raw(text);
        let mode_desc = params
            .get_cloned(keys::SPELL_DESCRIPTION)
            .unwrap_or_else(|| text.clone());
        description.push_str(&format!("{}\n", mode_desc));
        let _ = i; // index for potential numbering
    }
    description
}

/// Make charm mode choices during pre-cast.
/// Mirrors Java's `CharmEffect.makeChoices(SpellAbility)`.
///
/// This is a wrapper around `make_choices_precast` for structural parity.
pub fn make_choices(
    game: &mut GameState,
    agents: &mut [Box<dyn PlayerAgent>],
    sa: &mut SpellAbility,
) -> bool {
    make_choices_precast(game, agents, sa)
}

/// Chain a list of sub-abilities (modes) onto a root spell ability.
/// Mirrors Java's `CharmEffect.chainAbilities(SpellAbility, List<AbilitySub>)`.
///
/// Appends each mode ability as a sub-ability at the end of the SA chain.
pub fn chain_abilities(
    game: &GameState,
    sa: &mut SpellAbility,
    mode_texts: &[String],
    player: PlayerId,
    source_id: crate::ids::CardId,
) {
    for mode_text in mode_texts {
        let mut mode_sa = build_spell_ability(game, source_id, mode_text, player);
        mode_sa.source = Some(source_id);
        mode_sa.trigger_remembered_amount = sa.trigger_remembered_amount;
        append_subability(sa, mode_sa);
    }
}

/// Check whether a charm mode has valid targets (or needs no targets).
///
/// Mirrors Java's pre-filtering of `possible` modes in CharmEffect before
/// calling `chooseModeForAbility`. Modes without targeting requirements are
/// always valid. Modes requiring specific targets are valid only if at least
/// one legal candidate exists.
fn mode_has_valid_targets(
    ctx: &EffectContext,
    mode_text: &str,
    player: PlayerId,
    source_id: crate::ids::CardId,
) -> bool {
    mode_has_valid_targets_in_game(ctx.game, mode_text, player, source_id)
}

fn append_subability(root: &mut SpellAbility, mode_sa: SpellAbility) {
    let mut slot = &mut root.sub_ability;
    loop {
        match slot {
            Some(node) => slot = &mut node.sub_ability,
            None => {
                *slot = Some(Box::new(mode_sa));
                return;
            }
        }
    }
}

fn should_use_preselected_modes(
    game: &GameState,
    source_id: crate::ids::CardId,
    mode_texts: &[String],
) -> bool {
    let source = game.card(source_id);
    if source.has_keyword("Spree") || source.has_keyword("Tiered") {
        return true;
    }

    mode_texts.iter().any(|text| {
        let params = Params::from_raw(text);
        params.has(keys::MODE_COST)
    })
}

pub(crate) fn mode_has_valid_targets_in_game(
    game: &GameState,
    mode_text: &str,
    player: PlayerId,
    source_id: crate::ids::CardId,
) -> bool {
    let sa = build_spell_ability(game, source_id, mode_text, player);
    let tr = match &sa.target_restrictions {
        Some(tr) => tr,
        None => return true, // No targeting = always valid
    };

    // Match Java CharmEffect.makePossibleOptions(): only drop a targeted mode
    // when it requires at least one target and the full targeting engine finds
    // zero legal candidates.
    if tr.get_min_targets(game, &sa) <= 0 {
        return true;
    }

    tr.has_candidates(game, player, sa.source)
}

fn setup_mode_targets(ctx: &mut EffectContext, mode_sa: &mut SpellAbility, player: PlayerId) {
    if !mode_sa.uses_targeting() {
        return;
    }
    mode_sa.targeting_player = Some(player);
    ctx.agents[player.index()].choose_targets_for(mode_sa, ctx.game, ctx.mana_pools);
}

#[cfg(test)]
mod tests {
    use crate::ability::spell_ability_effect::SpellAbilityEffect;
    use forge_foundation::{CardTypeLine, ColorSet, ManaCost, ZoneType};
    use std::collections::{BTreeMap, HashMap};

    use crate::ability::effects::EffectContext;
    use crate::agent::PassAgent;
    use crate::card::Card;
    use crate::game::GameState;
    use crate::ids::{CardId, PlayerId};
    use crate::mana::ManaPool;
    use crate::spellability::SpellAbility;
    use crate::trigger::handler::TriggerHandler;

    #[test]
    fn charm_choose_mode_zero_choices_noops() {
        let mut game = GameState::new(&["Alice", "Bob"], 20);
        let p0 = PlayerId(0);

        // A charm with no Choices$ should be a no-op
        let sa = SpellAbility::new_simple(None, p0, "A:SP$ Charm");
        let mut th = TriggerHandler::new();
        let mut agents: Vec<Box<dyn crate::agent::PlayerAgent>> =
            vec![Box::new(PassAgent), Box::new(PassAgent)];
        let mut mp = vec![ManaPool::default(), ManaPool::default()];
        let templates = HashMap::new();
        let templates_variants = HashMap::new();
        let token_fallback = HashMap::new();
        let edition_dates: HashMap<String, String> = HashMap::new();
        let mut rng_adapter = crate::game_rng::ThreadRngAdapter;
        let mut ctx = EffectContext {
            game: &mut game,
            combat: None,
            agents: &mut agents,
            trigger_handler: &mut th,
            token_templates: &templates,
            token_art_variants: &templates_variants,
            token_fallback: &token_fallback,
            edition_dates: &edition_dates,
            mana_pools: &mut mp,
            parent_target_card: None,
            rng: &mut rng_adapter,
        };
        // Should not panic
        super::CharmEffect::resolve(&mut ctx, &sa);
    }

    /// Integration test: charm with two draw modes, PassAgent picks first mode.
    /// Uses a live card with SVars so `build_spell_ability` can look them up.
    #[test]
    fn charm_resolves_chosen_non_targeted_mode() {
        let mut game = GameState::new(&["Alice", "Bob"], 20);
        let p0 = PlayerId(0);
        let p1 = PlayerId(1);

        // Build a fake "charm" card with two modes stored as SVars
        let mut svars = BTreeMap::new();
        // Mode A: draw a card (uses Defined$ You)
        svars.insert(
            "ModeA".to_string(),
            "DB$ Draw | NumCards$ 1 | Defined$ You | SpellDescription$ Draw a card.".to_string(),
        );
        // Mode B: draw a card for opponent (Defined$ Opponent)
        svars.insert(
            "ModeB".to_string(),
            "DB$ Draw | NumCards$ 1 | Defined$ Opponent | SpellDescription$ Opponent draws."
                .to_string(),
        );

        let charm_card = Card::new(
            CardId(0),
            "Test Charm".into(),
            p0,
            CardTypeLine::parse("Instant"),
            ManaCost::parse("U B"),
            ColorSet::from_names("u"),
            None,
            None,
            vec!["A:SP$ Charm | Choices$ ModeA,ModeB".to_string()],
            vec![],
        );
        // We can't set svars in Card::new directly, so we use create_card + mutate
        let cid = game.create_card(charm_card);
        game.card_mut(cid).set_svars_map(svars);

        // Put a card in each player's library so draw succeeds
        let dummy_a = game.create_card(Card::new(
            CardId(0),
            "Dummy A".into(),
            p0,
            CardTypeLine::parse("Creature"),
            ManaCost::parse(""),
            ColorSet::COLORLESS,
            Some(1),
            Some(1),
            vec![],
            vec![],
        ));
        game.move_card(dummy_a, ZoneType::Library, p0);

        let sa = SpellAbility::new_simple(Some(cid), p0, "A:SP$ Charm | Choices$ ModeA,ModeB");

        let mut th = TriggerHandler::new();
        let mut agents: Vec<Box<dyn crate::agent::PlayerAgent>> =
            vec![Box::new(PassAgent), Box::new(PassAgent)];
        let mut mp = vec![ManaPool::default(), ManaPool::default()];
        let templates = HashMap::new();
        let templates_variants = HashMap::new();
        let token_fallback = HashMap::new();
        let edition_dates: HashMap<String, String> = HashMap::new();
        let mut rng_adapter = crate::game_rng::ThreadRngAdapter;
        let mut ctx = EffectContext {
            game: &mut game,
            combat: None,
            agents: &mut agents,
            trigger_handler: &mut th,
            token_templates: &templates,
            token_art_variants: &templates_variants,
            token_fallback: &token_fallback,
            edition_dates: &edition_dates,
            mana_pools: &mut mp,
            parent_target_card: None,
            rng: &mut rng_adapter,
        };

        // PassAgent.choose_mode picks first min modes → ModeA (draw for p0)
        let p0_hand_before = ctx.game.cards_in_zone(ZoneType::Hand, p0).len();
        super::CharmEffect::resolve(&mut ctx, &sa);
        let p0_hand_after = ctx.game.cards_in_zone(ZoneType::Hand, p0).len();
        // p0 should have drawn 1 card
        assert_eq!(p0_hand_after, p0_hand_before + 1);
        // p1 should not have drawn
        assert_eq!(ctx.game.cards_in_zone(ZoneType::Hand, p1).len(), 0);
    }

    #[test]
    fn charm_precast_does_not_reuse_stale_chosen_modes() {
        let mut game = GameState::new(&["Alice", "Bob"], 20);
        let p0 = PlayerId(0);
        let p1 = PlayerId(1);

        let mut svars = BTreeMap::new();
        svars.insert(
            "BraveTheStench".to_string(),
            "DB$ Pump | ValidTgts$ Creature.OppCtrl | TgtPrompt$ Select target creature an opponent controls. | NumAtt$ -1 | NumDef$ -1 | IsCurse$ True | SpellDescription$ Brave the Stench".to_string(),
        );
        svars.insert(
            "SearchTheBody".to_string(),
            "DB$ Token | TokenScript$ c_a_treasure_sac | TokenOwner$ You | SpellDescription$ Search the Body".to_string(),
        );

        let ghast = Card::new(
            CardId(0),
            "Shambling Ghast".into(),
            p1,
            CardTypeLine::parse("Creature Zombie"),
            ManaCost::parse("B"),
            ColorSet::from_names("b"),
            Some(1),
            Some(1),
            vec!["A:SP$ Charm | Choices$ BraveTheStench,SearchTheBody".to_string()],
            vec![],
        );
        let ghast_id = game.create_card(ghast);
        game.card_mut(ghast_id).set_svars_map(svars);

        let patient_zero = game.create_card(Card::new(
            CardId(0),
            "Patient Zero".into(),
            p0,
            CardTypeLine::parse("Creature Zombie"),
            ManaCost::parse("1 B"),
            ColorSet::from_names("b"),
            Some(2),
            Some(2),
            vec![],
            vec![],
        ));
        game.move_card(patient_zero, ZoneType::Battlefield, p0);

        let mut sa = SpellAbility::new_simple(
            Some(ghast_id),
            p1,
            "A:SP$ Charm | Choices$ BraveTheStench,SearchTheBody",
        );
        // Simulate a prior life of the same card instance choosing "Search the Body".
        game.card_mut(ghast_id).set_chosen_modes(vec![1]);
        let mut agents: Vec<Box<dyn crate::agent::PlayerAgent>> =
            vec![Box::new(PassAgent), Box::new(PassAgent)];

        assert!(super::make_choices_precast(&mut game, &mut agents, &mut sa));
        assert!(game.card(ghast_id).chosen_modes.is_none());
        assert_eq!(
            sa.sub_ability.as_ref().and_then(|sub| sub.api),
            Some(crate::ability::api_type::ApiType::Pump)
        );
    }
}