Skip to main content

manabrew_engine/spellability/
mod.rs

1pub mod ability;
2pub mod ability_activated;
3pub mod ability_mana_part;
4pub mod ability_static;
5pub mod ability_sub;
6pub mod alternative_cost;
7pub mod land_ability;
8pub mod optional_cost;
9pub mod optional_cost_value;
10pub mod params;
11pub mod runtime_types;
12pub mod spell;
13pub mod spell_ability_condition;
14pub mod spell_ability_predicates;
15pub mod spell_ability_restriction;
16pub mod spell_ability_stack_instance;
17pub mod spell_ability_variables;
18pub mod spell_permanent;
19pub mod target_choices;
20pub mod target_restrictions;
21pub mod trait_spell_ability;
22pub mod valid_sa;
23
24use std::collections::HashMap;
25use std::sync::atomic::{AtomicU32, Ordering};
26
27use serde::{Deserialize, Serialize};
28
29use crate::ability::ability_factory::AbilityRecordType;
30use crate::ability::ability_ir::SpellAbilityIr;
31use crate::ability::api_type::ApiType;
32use crate::ability::AbilityKey;
33use crate::agent::PlayerAgent;
34use crate::card::card_damage_map::CardDamageMap;
35use crate::card::card_zone_table::CardZoneTable;
36use crate::card_trait_base::CardTraitIrOwner;
37use crate::cost::{parse_cost, Cost};
38use crate::event::AbilityValue;
39use crate::game::GameState;
40use crate::ids::{CardId, PlayerId};
41use crate::mana::ManaPool;
42use crate::parsing::{keys, Params, ParsedParams};
43
44pub use ability_mana_part::AbilityManaPart;
45pub use alternative_cost::{AlternativeCost, MORPH_GENERIC_COST, MORPH_PT};
46pub use optional_cost::OptionalCost;
47pub use optional_cost_value::OptionalCostValue;
48pub use runtime_types::{
49    AbilityDuration, ReplaceDyingCondition, SpellAbilityMode, TriggerCondition,
50};
51pub use spell_ability_condition::SpellAbilityCondition;
52pub use spell_ability_predicates::{has_sub_ability_api, is_api, is_valid};
53pub use spell_ability_restriction::SpellAbilityRestriction;
54pub use spell_ability_variables::SpellAbilityVariables;
55pub use target_choices::TargetChoices;
56pub use target_restrictions::{TargetKind, TargetRestrictions};
57pub use valid_sa::matches_valid_sa;
58
59static NEXT_SPELL_ABILITY_ID: AtomicU32 = AtomicU32::new(1);
60
61fn next_spell_ability_id() -> u32 {
62    NEXT_SPELL_ABILITY_ID.fetch_add(1, Ordering::Relaxed)
63}
64
65pub trait TriggerKeyInput {
66    fn into_ability_key(self) -> Option<AbilityKey>;
67}
68
69impl TriggerKeyInput for AbilityKey {
70    fn into_ability_key(self) -> Option<AbilityKey> {
71        Some(self)
72    }
73}
74
75impl TriggerKeyInput for &str {
76    fn into_ability_key(self) -> Option<AbilityKey> {
77        crate::ability::ability_key::from_string(self)
78    }
79}
80
81impl TriggerKeyInput for String {
82    fn into_ability_key(self) -> Option<AbilityKey> {
83        crate::ability::ability_key::from_string(&self)
84    }
85}
86
87impl TriggerKeyInput for &String {
88    fn into_ability_key(self) -> Option<AbilityKey> {
89        crate::ability::ability_key::from_string(self)
90    }
91}
92
93// ── SpellAbility (mirrors Java's SpellAbility.java) ──────────────────
94
95/// A spell or ability with its own targeting, costs, and sub-ability chain.
96/// Mirrors Java's `SpellAbility` class — each node in the chain has its own
97/// `target_restrictions`, `target_chosen`, `sub_ability`, `api`, etc.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct SpellAbility {
100    #[serde(default)]
101    pub id: u32,
102    /// Effect API type (e.g. DealDamage, Destroy, Draw).
103    /// Mirrors Java's `ApiType api` field.
104    pub api: Option<ApiType>,
105    /// The card that hosts this ability. Mirrors Java's `hostCard`.
106    pub source: Option<CardId>,
107    /// Java parity: original host card for granted/copied abilities.
108    /// Used by costs like `Unattach<OriginalHost>`.
109    #[serde(default)]
110    pub original_host: Option<CardId>,
111    /// The player who activated/cast this. Mirrors Java's `activatingPlayer`.
112    pub activating_player: PlayerId,
113    /// The player who chooses this ability's targets. Mirrors Java's
114    /// `targetingPlayer` field.
115    pub targeting_player: Option<PlayerId>,
116    /// The raw ability text (pipe-delimited params).
117    pub ability_text: String,
118    /// Java parity: AB/SP/ST/DB record kind used to distinguish sub-abilities.
119    #[serde(default)]
120    pub record_type: AbilityRecordType,
121    /// Compiled Forge script IR; resolution reads typed fields from here.
122    /// Skipped on serde: a deserialized `SpellAbility` must rebuild it from
123    /// `ability_text` before use or every typed param reads as absent.
124    #[serde(skip)]
125    pub ir: SpellAbilityIr,
126    /// Targeting restrictions parsed from `ValidTgts$`.
127    /// `None` means this ability doesn't use targeting.
128    /// Mirrors Java's `targetRestrictions` field.
129    pub target_restrictions: Option<TargetRestrictions>,
130    /// The chosen targets for this ability.
131    /// Mirrors Java's `targetChosen` field.
132    pub target_chosen: TargetChoices,
133    /// Parsed costs from `Cost$` parameter.
134    /// Mirrors Java's `payCosts` field.
135    pub pay_costs: Option<Cost>,
136    /// Linked sub-ability chain. Mirrors Java's `subAbility` field
137    /// (AbilitySub extends SpellAbility).
138    pub sub_ability: Option<Box<SpellAbility>>,
139    /// Java parity: payload carried by `WrappedAbility`.
140    #[serde(default)]
141    pub wrapped_ability: Option<Box<SpellAbility>>,
142    /// Whether this is a spell (not an ability).
143    pub is_spell: bool,
144    /// Whether this is a triggered ability.
145    pub is_trigger: bool,
146    /// Whether this is an activated ability.
147    pub is_activated: bool,
148    /// Java parity: whether this ability is intrinsic to its host.
149    #[serde(default)]
150    pub intrinsic: bool,
151    /// Card that owns the trigger (for intervening-if recheck).
152    pub trigger_source: Option<CardId>,
153    /// Zone timestamp of the trigger source when this triggered ability was created.
154    /// Used to preserve object identity across zone changes (CR 400.7).
155    #[serde(default)]
156    pub trigger_source_zone_timestamp: Option<u64>,
157    /// Zone timestamp of `source` when this SpellAbility instance was created.
158    /// Used for non-target references like `Defined$ Self` to preserve object identity.
159    #[serde(default)]
160    pub source_zone_timestamp: Option<u64>,
161    /// Source trigger id (Java `sourceTrigger`), used for state-trigger dedupe.
162    pub source_trigger_id: Option<u32>,
163    /// Index into card.triggers for intervening-if recheck.
164    pub trigger_index: Option<usize>,
165    /// Alternative cost used to cast this spell (Flashback, Spectacle, Evoke, Dash, etc.).
166    pub alt_cost: Option<AlternativeCost>,
167    /// Index within the card's list of same-kind alternative costs. Zero for
168    /// all cases except multi-cost Evoke (intrinsic + granted by Ashling-style
169    /// static AddKeyword): 0 = first payable Evoke, 1 = second, …
170    #[serde(default)]
171    pub alt_cost_index: u8,
172    /// Number of Evoke keywords on the card at cast time (intrinsic + granted
173    /// from hand — e.g. Ashling, the Limitless's `AddKeyword$ Evoke:4`).
174    /// Java parity: `CardFactoryUtil` attaches one Evoke "sacrifice when it
175    /// enters" trigger per Evoke keyword, so a card with two Evoke keywords
176    /// carries two sac triggers. Captured at cast because granted keywords from
177    /// zone-gated statics (`AffectedZone$ Hand`) are gone once the card moves
178    /// to the stack.
179    #[serde(default)]
180    pub evoke_keyword_count: u8,
181    /// Whether the kicker cost was paid.
182    pub kicked: bool,
183    /// Whether buyback was paid (spell returns to hand on resolve).
184    pub buyback_paid: bool,
185    /// Whether this spell is overloaded (targets all valid instead of one).
186    pub overloaded: bool,
187    /// Whether this spell is a copy (created by Storm, Replicate, etc.).
188    pub is_copy: bool,
189    /// Java parity: life paid while activating or casting this ability.
190    #[serde(default)]
191    pub paid_life_amount: i32,
192    /// Number of times the kicker/multikicker cost was paid.
193    pub kick_count: u32,
194    /// Number of times the replicate cost was paid.
195    pub replicate_count: u32,
196    /// Whether a generic optional additional cost was paid.
197    pub optional_generic_cost_paid: bool,
198    /// Sum of integer values remembered on the trigger that spawned this
199    /// ability (Java: TriggerRememberAmount / sa.getTriggerRemembered()).
200    pub trigger_remembered_amount: i32,
201    /// The value chosen for X in the mana cost (e.g. Fireball X=5 means 5 damage).
202    /// Mirrors Java's `SpellAbility.getXManaCostPaid()`.
203    pub x_mana_cost_paid: u32,
204    /// Cards discarded as part of the cost payment.
205    /// Mirrors Java's `CostPayment.getPaidList("Discarded")`.
206    pub discarded_cost_cards: Vec<crate::ids::CardId>,
207    /// Optional costs that have been paid for this spell.
208    /// Mirrors Java's `SpellAbility.optionalCosts`.
209    #[serde(default)]
210    pub optional_costs: Vec<OptionalCost>,
211    /// Hash of costs paid, keyed by cost type with list of values.
212    /// Mirrors Java's `SpellAbility.paidHash`.
213    #[serde(default)]
214    pub paid_hash: HashMap<String, Vec<String>>,
215    /// Java parity: mana atoms used to pay this spell or ability.
216    #[serde(default)]
217    pub paying_mana: Vec<u16>,
218    /// Java parity: paid abilities list.
219    #[serde(default)]
220    pub paid_abilities: Vec<SpellAbility>,
221    /// Mana-producing part of this ability (for mana abilities).
222    /// Mirrors Java's `SpellAbility.manaPart`.
223    pub mana_part: Option<AbilityManaPart>,
224    /// Express mana choice forced by callback/autopay for flexible mana abilities.
225    #[serde(default)]
226    pub express_mana_choice: Option<u16>,
227    /// Cards tapped for convoke cost reduction.
228    /// Mirrors Java's `SpellAbility.tappedForConvoke`.
229    #[serde(default)]
230    pub convoke_tapped: Vec<CardId>,
231    /// Cards spliced onto this spell.
232    /// Mirrors Java's `SpellAbility.splicedCards`.
233    #[serde(default)]
234    pub spliced_cards: Vec<CardId>,
235    /// Announced variable values (e.g. X, number of targets).
236    /// Mirrors Java's `SpellAbility.announceVars`.
237    #[serde(default)]
238    pub announce_vars: HashMap<String, i32>,
239    /// Card sacrificed as part of emerge cost.
240    /// Mirrors Java's `SpellAbility.sacrificedAsEmerge`.
241    pub sacrificed_as_emerge: Option<CardId>,
242    /// Card sacrificed as part of offering cost.
243    /// Mirrors Java's `SpellAbility.sacrificedAsOffering`.
244    pub sacrificed_as_offering: Option<CardId>,
245    /// Human-readable description of this ability.
246    /// Mirrors Java's `SpellAbility.description`.
247    #[serde(default)]
248    pub description: String,
249    /// Description used when this ability is on the stack.
250    /// Mirrors Java's `SpellAbility.stackDescription`.
251    #[serde(default)]
252    pub stack_description: String,
253    /// Whether this is a mana ability (doesn't use the stack).
254    /// Mirrors Java's `SpellAbility.isManaAbility`.
255    #[serde(default)]
256    pub is_mana_ability: bool,
257    /// Whether this is a land ability (play land action).
258    /// Mirrors Java's `LandAbility` subclass flag.
259    #[serde(default)]
260    pub is_land_ability: bool,
261    /// Runtime-only face-down cast state used by morph/disguise-style spells.
262    #[serde(default)]
263    pub cast_face_down: bool,
264    /// Trigger objects map for tracking trigger context.
265    #[serde(default)]
266    pub trigger_objects: HashMap<AbilityKey, AbilityValue>,
267    /// Java parity: non-scalar trigger objects that carry spell/ability context.
268    #[serde(default)]
269    pub trigger_spell_abilities: HashMap<AbilityKey, SpellAbility>,
270    /// Java parity: additional ability lists used by mode/charm-style abilities.
271    #[serde(default)]
272    pub additional_ability_lists: HashMap<String, Vec<SpellAbility>>,
273    /// Java parity: replacing-objects payload.
274    #[serde(default)]
275    pub replacing_objects: HashMap<AbilityKey, AbilityValue>,
276    /// Java parity: trigger remembered objects copied from the originating trigger.
277    #[serde(default)]
278    pub trigger_remembered: Vec<AbilityValue>,
279    /// Activation restriction for this ability.
280    #[serde(default)]
281    pub restriction: SpellAbilityRestriction,
282    /// Condition that must be met for the effect to apply.
283    #[serde(default)]
284    pub condition: SpellAbilityCondition,
285    /// Rollback effects tracked for undo support.
286    #[serde(default)]
287    pub rollback_effects: Vec<String>,
288    /// Keyword amounts for optional keyword costs.
289    #[serde(default)]
290    pub optional_keyword_amounts: HashMap<String, i32>,
291    /// Pips to reduce from cost.
292    #[serde(default)]
293    pub pips_to_reduce: Vec<String>,
294    /// Java parity: whether copied effects may choose new targets.
295    #[serde(default)]
296    pub may_choose_new_targets: bool,
297    /// Last known state for LKI tracking.
298    #[serde(default)]
299    pub last_state: HashMap<String, String>,
300    /// Java parity: batched zone-change table accumulated for `ChangeZoneResolve`.
301    #[serde(skip)]
302    pub change_zone_table: Option<CardZoneTable>,
303    /// Java parity: accumulated damage map for `DamageResolve`.
304    #[serde(skip)]
305    pub damage_map: Option<CardDamageMap>,
306    /// Java parity: accumulated prevented-damage map for `DamageResolve`.
307    #[serde(skip)]
308    pub prevent_map: Option<CardDamageMap>,
309}
310
311/// Mirrors Java's `SpellAbility.toString()`.
312/// Walks the sub-ability chain, concatenating descriptions.
313impl std::fmt::Display for SpellAbility {
314    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
315        let mut node = Some(self);
316        let mut first = true;
317        while let Some(current) = node {
318            if !first {
319                write!(f, " ")?;
320            }
321            first = false;
322            write!(f, "{}", current.description)?;
323            node = current.sub_ability.as_deref();
324        }
325        Ok(())
326    }
327}
328
329impl CardTraitIrOwner for SpellAbility {
330    type Ir = SpellAbilityIr;
331
332    fn ir(&self) -> &Self::Ir {
333        &self.ir
334    }
335
336    fn card_trait_requirements(&self) -> &crate::card::valid_filter::CardTraitRequirementsIr {
337        &self.ir.card_trait_requirements
338    }
339}
340
341impl SpellAbility {
342    /// Whether this ability uses targeting.
343    /// Mirrors Java's `usesTargeting()`: `return targetRestrictions != null`.
344    pub fn uses_targeting(&self) -> bool {
345        self.target_restrictions.is_some()
346    }
347
348    /// Check if a parameter is set to "True" (case-insensitive).
349    /// Common pattern for boolean params like `Ninjutsu$ True`, `Mega$ True`, etc.
350    pub fn param_is_true(&self, key: &str) -> bool {
351        match key {
352            keys::OPTIONAL => self.ir.optional,
353            keys::MANDATORY => self.ir.mandatory,
354            keys::TAPPED => self.ir.tapped,
355            keys::HIDDEN => self.ir.hidden,
356            keys::IMPRINT => self.ir.imprint,
357            keys::CHOOSE_FROM_DEFINED_CARDS => self.ir.choose_from_defined_cards,
358            keys::FACE_DOWN => self.ir.face_down,
359            keys::EXILE_FACE_DOWN => self.ir.exile_face_down,
360            keys::TRANSFORMED => self.ir.transformed,
361            keys::AT_RANDOM => self.ir.at_random,
362            keys::REMEMBER_ALTERED => self.ir.remember_altered,
363            keys::REMEMBER_AMASS => self.ir.remember_amass,
364            keys::REMEMBER => self.ir.remember_flag,
365            keys::REMOVE_FROM_COMBAT => self.ir.remove_from_combat,
366            keys::RANDOM_TARGET => self.ir.random_target,
367            keys::REMEMBER_CHOSEN => self.ir.remember_chosen,
368            keys::REMEMBER_CLASHER => self.ir.remember_clasher,
369            keys::REMEMBER_CLOAKED => self.ir.remember_cloaked,
370            keys::REMEMBER_DISCOVERED => self.ir.remember_discovered,
371            keys::REMEMBER_DRAFTED => self.ir.remember_drafted,
372            keys::REMEMBER_EXCHANGED => self.ir.remember_exchanged,
373            keys::REMEMBER_INVESTIGATING_PLAYERS => self.ir.remember_investigating_players,
374            keys::REMEMBER_MADE => self.ir.remember_made,
375            keys::IMPRINT_MADE => self.ir.imprint_made,
376            keys::RANDOM_CHOSEN => self.ir.random_chosen,
377            keys::SNEAK => self.ir.sneak,
378            keys::MEGA => self.ir.mega,
379            keys::STORE_VOTE_NUM => self.ir.store_vote_num,
380            keys::REMEMBER_VOTED_OBJECTS => self.ir.remember_voted_objects,
381            "ToVisitYourAttractions" => self.ir.to_visit_your_attractions,
382            "RememberHighestPlayer" => self.ir.remember_highest_player,
383            "UseHighestRoll" => self.ir.use_highest_roll,
384            "UseDifferenceBetweenRolls" => self.ir.use_difference_between_rolls,
385            "StoreResults" => self.ir.store_results,
386            "EvenOddResults" => self.ir.even_odd_results,
387            "DifferentResults" => self.ir.different_results,
388            "MaxRollsResults" => self.ir.max_rolls_results,
389            "NoteDoubles" => self.ir.note_doubles,
390            "SubsForEach" => self.ir.subs_for_each,
391            "RerollResults" => self.ir.reroll_results,
392            keys::NINJUTSU => self.ir.ninjutsu,
393            keys::UNEARTH => self.ir.unearth,
394            keys::ATTACKING => self.ir.attacking,
395            keys::OVERWRITE_COLORS => self.ir.overwrite_colors,
396            keys::FORETOLD => self.ir.foretold,
397            keys::FORETOLD_COST => self.ir.foretold_cost,
398            keys::IMPRINT_LAST => self.ir.imprint_last,
399            keys::RANDOM_ORDER => self.ir.random_order,
400            keys::SHUFFLE_CHANGED_PILE => self.ir.shuffle_changed_pile,
401            keys::WARP => self.ir.warp,
402            keys::CAN_REPEAT_MODES => self.ir.can_repeat_modes,
403            keys::ENTWINE => self.ir.entwine,
404            keys::REMOVE_CREATURE_TYPES => self.ir.animate_remove_creature_types,
405            keys::REMOVE_ALL_ABILITIES => self.ir.animate_remove_all_abilities,
406            keys::REMEMBER_REMOVED_CARDS => self.ir.remember_removed_cards,
407            keys::TOKEN_TAPPED => self.ir.token_tapped,
408            keys::REMEMBER_TOKENS => self.ir.remember_tokens,
409            keys::REMEMBER_ORIGINAL_TOKENS => self.ir.remember_original_tokens,
410            keys::IMPRINT_TOKENS => self.ir.imprint_tokens,
411            keys::REMEMBER_SOURCE => self.ir.remember_source,
412            keys::CLEANUP_FOR_EACH => self.ir.cleanup_for_each,
413            "Morph" => self.ir.morph,
414            "MorphUp" => self.ir.morph_up,
415            "Megamorph" => self.ir.megamorph,
416            "RememberAbandoned" => self.ir.remember_abandoned,
417            _ => false,
418        }
419    }
420
421    pub fn param_value(&self, key: &str) -> Option<&str> {
422        match key {
423            keys::MODE => self.ir.mode_text.as_deref(),
424            keys::VALID_CARDS => self.ir.valid_cards_text.as_deref(),
425            keys::VALID_CARD => self.ir.valid_card_text.as_deref(),
426            keys::VALID_PLAYERS => self.ir.valid_players_text.as_deref(),
427            keys::VALID_PLAYER => self.ir.valid_player_text.as_deref(),
428            keys::VALID_TGTS => self.ir.valid_tgts_text.as_deref(),
429            keys::VALID_TARGET => self.ir.valid_target_text.as_deref(),
430            keys::DEFINED => self.ir.defined_text.as_deref(),
431            keys::DEFINED_PLAYER => self.ir.defined_player_text.as_deref(),
432            keys::CONTROLLER => self.ir.controller_text.as_deref(),
433            keys::ORIGIN => self.ir.origin_text.as_deref(),
434            keys::DESTINATION => self.ir.destination_text.as_deref(),
435            keys::CHOICES => self.ir.choices.as_deref(),
436            keys::FOR_EACH => self.ir.for_each_text.as_deref(),
437            keys::TRIGGERS => self.ir.triggers.as_deref(),
438            keys::COUNTER_TYPE => self.ir.counter_type_text.as_deref(),
439            keys::TOKEN_SCRIPT => self.ir.token_script.as_deref(),
440            keys::TOKEN_OWNER => self.ir.token_owner.as_deref(),
441            keys::TOKEN_NAME => self.ir.token_name_text.as_deref(),
442            keys::TOKEN_TYPES => self.ir.token_types_text.as_deref(),
443            keys::TOKEN_COLORS => self.ir.token_colors_text.as_deref(),
444            keys::TOKEN_KEYWORDS => self.ir.token_keywords_text.as_deref(),
445            keys::TOKEN_ATTACKING => self.ir.token_attacking_text.as_deref(),
446            keys::TOKEN_BLOCKING => self.ir.token_blocking_text.as_deref(),
447            keys::TOKEN_REMEMBERED => self.ir.token_remembered.as_deref(),
448            keys::ADD_TRIGGERS_FROM => self.ir.add_triggers_from_text.as_deref(),
449            keys::AT_EOT => self.ir.at_eot.as_deref(),
450            keys::AT_EOT_TRIG => self.ir.at_eot_trig_text.as_deref(),
451            keys::ATTACHED_TO => self.ir.attached_to.as_deref(),
452            keys::ATTACH_AFTER => self.ir.attach_after_text.as_deref(),
453            keys::WITH_COUNTERS_TYPE => self.ir.with_counters_type_text.as_deref(),
454            keys::WITH_COUNTERS_AMOUNT => self.ir.with_counters_amount_text.as_deref(),
455            keys::PUMP_KEYWORDS => self.ir.pump_keywords.as_deref(),
456            keys::PUMP_DURATION => self.ir.pump_duration_text.as_deref(),
457            "Keyword" => self.ir.keyword_text.as_deref(),
458            keys::CHOOSER => self.ir.chooser.as_deref(),
459            keys::NAME => self.ir.name_text.as_deref(),
460            keys::NAMES => self.ir.names_text.as_deref(),
461            keys::CHOOSE_FROM_LIST => self.ir.choose_from_list_text.as_deref(),
462            keys::GAIN_CONTROL => self.ir.gain_control_text.as_deref(),
463            keys::SPELLBOOK => self.ir.spellbook_text.as_deref(),
464            keys::VOTE_MESSAGE => self.ir.vote_message_text.as_deref(),
465            keys::DEFINED_MAGNET => self.ir.defined_magnet_text.as_deref(),
466            "PhaseInOrOut" => self.ir.phase_in_or_out_text.as_deref(),
467            "ExtraPhase" => self.ir.extra_phase_text.as_deref(),
468            "CardState" => self.ir.card_state_name.as_deref(),
469            _ => None,
470        }
471    }
472
473    /// Get the chosen targets. Mirrors Java's `getTargets()`.
474    pub fn get_targets(&self) -> &TargetChoices {
475        &self.target_chosen
476    }
477
478    /// Get the chosen targets mutably. Mirrors Java's `getTargets()` for mutation.
479    pub fn get_targets_mut(&mut self) -> &mut TargetChoices {
480        &mut self.target_chosen
481    }
482
483    /// Get the sub-ability. Mirrors Java's `getSubAbility()`.
484    pub fn get_sub_ability(&self) -> Option<&SpellAbility> {
485        self.sub_ability.as_deref()
486    }
487
488    /// Get the sub-ability mutably.
489    pub fn get_sub_ability_mut(&mut self) -> Option<&mut SpellAbility> {
490        self.sub_ability.as_deref_mut()
491    }
492
493    /// Mirrors Java's `SpellAbility.isWrapper()`.
494    pub fn is_wrapper(&self) -> bool {
495        self.wrapped_ability.is_some()
496    }
497
498    /// Mirrors Java's `WrappedAbility.getWrappedAbility()`.
499    pub fn get_wrapped_ability(&self) -> &SpellAbility {
500        self.wrapped_ability
501            .as_deref()
502            .expect("SpellAbility.get_wrapped_ability called on non-wrapper")
503    }
504
505    pub fn get_wrapped_ability_mut(&mut self) -> &mut SpellAbility {
506        self.wrapped_ability
507            .as_deref_mut()
508            .expect("SpellAbility.get_wrapped_ability_mut called on non-wrapper")
509    }
510
511    pub fn set_wrapped_ability(&mut self, wrapped: SpellAbility) {
512        self.wrapped_ability = Some(Box::new(wrapped));
513    }
514
515    /// Clear the chosen targets. Mirrors Java's `clearTargets()`.
516    pub fn clear_targets(&mut self) {
517        self.target_chosen = TargetChoices::default();
518    }
519
520    /// Walk the entire ability chain and choose targets for each node that
521    /// uses targeting. Mirrors Java's `SpellAbility.setupTargets()` do/while loop.
522    ///
523    /// Returns `true` if all targeting succeeded, `false` if any node couldn't
524    /// find valid targets.
525    pub fn setup_targets(
526        &mut self,
527        game: &GameState,
528        agents: &mut [Box<dyn PlayerAgent>],
529        mana_pools: &[ManaPool],
530    ) -> bool {
531        // Walk self, then sub_ability chain — mirrors Java's do/while
532        if self.uses_targeting() {
533            self.clear_targets();
534            self.targeting_player = choose_targeting_player(self, game, agents);
535            let player = self.targeting_player.unwrap_or(self.activating_player);
536            if !agents[player.index()].choose_targets_for(self, game, mana_pools) {
537                return false;
538            }
539        }
540
541        // Walk sub-ability chain
542        let mut current = self.sub_ability.as_deref_mut();
543        while let Some(sa) = current {
544            if sa.uses_targeting() {
545                sa.clear_targets();
546                sa.targeting_player = choose_targeting_player(sa, game, agents);
547                let player = sa.targeting_player.unwrap_or(sa.activating_player);
548                if !agents[player.index()].choose_targets_for(sa, game, mana_pools) {
549                    return false;
550                }
551            }
552            current = sa.sub_ability.as_deref_mut();
553        }
554
555        crate::staticability::static_ability_must_target::meets_must_target_restriction(game, self)
556    }
557
558    /// Create a simple SpellAbility for tests and triggers.
559    pub fn new_simple(source: Option<CardId>, player: PlayerId, ability_text: &str) -> Self {
560        let _perf_scope = crate::perf::ParamsLookupScopeGuard::enter(
561            crate::perf::ParamsLookupScope::AbilityBuild,
562        );
563        let parsed = ParsedParams::parse(ability_text);
564        let params = Params::from_parsed(&parsed);
565        let api = parsed
566            .get(keys::SP)
567            .or_else(|| parsed.get(keys::DB))
568            .or_else(|| parsed.get(keys::AB))
569            .and_then(ApiType::smart_value_of);
570        let record_type = crate::ability::ability_factory::AbilityRecordType::from_parsed(&parsed)
571            .unwrap_or_default();
572        let target_restrictions = if parsed.has(keys::VALID_TGTS) {
573            TargetRestrictions::new_from_parsed(&parsed, &params)
574        } else {
575            None
576        };
577        let cost = parsed.get(keys::COST).map(parse_cost);
578        let mut ir = crate::ability::ability_ir::SpellAbilityIr::from_parsed(api, &parsed);
579        ir.compile_numeric_params_from_runtime(&params);
580
581        SpellAbility {
582            id: next_spell_ability_id(),
583            api,
584            source,
585            original_host: None,
586            activating_player: player,
587            targeting_player: None,
588            ability_text: ability_text.to_string(),
589            record_type,
590            ir,
591            target_restrictions,
592            target_chosen: TargetChoices::default(),
593            pay_costs: cost,
594            sub_ability: None,
595            wrapped_ability: None,
596            is_spell: false,
597            is_trigger: false,
598            is_activated: false,
599            intrinsic: false,
600            trigger_source: None,
601            trigger_source_zone_timestamp: None,
602            source_zone_timestamp: None,
603            source_trigger_id: None,
604            trigger_index: None,
605            alt_cost: None,
606            alt_cost_index: 0,
607            evoke_keyword_count: 0,
608            kicked: false,
609            buyback_paid: false,
610            overloaded: false,
611            is_copy: false,
612            paid_life_amount: 0,
613            kick_count: 0,
614            replicate_count: 0,
615            optional_generic_cost_paid: false,
616            trigger_remembered_amount: 0,
617            x_mana_cost_paid: 0,
618            discarded_cost_cards: Vec::new(),
619            optional_costs: Vec::new(),
620            paid_hash: HashMap::new(),
621            paying_mana: Vec::new(),
622            paid_abilities: Vec::new(),
623            mana_part: None,
624            express_mana_choice: None,
625            convoke_tapped: Vec::new(),
626            spliced_cards: Vec::new(),
627            announce_vars: HashMap::new(),
628            sacrificed_as_emerge: None,
629            sacrificed_as_offering: None,
630            description: String::new(),
631            stack_description: String::new(),
632            is_mana_ability: false,
633            is_land_ability: false,
634            cast_face_down: false,
635            trigger_objects: HashMap::new(),
636            trigger_spell_abilities: HashMap::new(),
637            additional_ability_lists: HashMap::new(),
638            replacing_objects: HashMap::new(),
639            trigger_remembered: Vec::new(),
640            restriction: SpellAbilityRestriction::default(),
641            condition: SpellAbilityCondition::default(),
642            rollback_effects: Vec::new(),
643            optional_keyword_amounts: HashMap::new(),
644            pips_to_reduce: Vec::new(),
645            may_choose_new_targets: false,
646            last_state: HashMap::new(),
647            change_zone_table: None,
648            damage_map: None,
649            prevent_map: None,
650        }
651    }
652
653    /// Create a minimal empty SpellAbility stub.
654    /// Mirrors Java's common `SpellAbility.EmptySa` usage.
655    pub fn new_empty(source: Option<CardId>, player: PlayerId) -> Self {
656        Self::new_simple(source, player, "")
657    }
658
659    /// Create a minimal land-play SpellAbility stub.
660    pub fn new_land(source: Option<CardId>, player: PlayerId) -> Self {
661        let mut sa = Self::new_empty(source, player);
662        sa.is_land_ability = true;
663        sa
664    }
665
666    // ── Sub-ability chain walking ─────────────────────────────────────────
667
668    /// Walk the sub-ability chain looking for a specific API type.
669    /// Mirrors Java's `SpellAbility.findSubAbilityByType(ApiType)`.
670    pub fn find_sub_ability_by_type(&self, api: ApiType) -> Option<&SpellAbility> {
671        let mut current = self.sub_ability.as_deref();
672        while let Some(sub) = current {
673            if sub.api == Some(api) {
674                return Some(sub);
675            }
676            current = sub.sub_ability.as_deref();
677        }
678        None
679    }
680
681    // ── Mana part delegation ──────────────────────────────────────────────
682
683    /// Whether this ability can produce mana.
684    /// Mirrors Java's `SpellAbility.canThisProduce()`.
685    pub fn can_this_produce(&self) -> bool {
686        match &self.mana_part {
687            Some(mp) => mp.can_this_produce(),
688            None => false,
689        }
690    }
691
692    /// Whether this ability can produce a specific color.
693    /// Mirrors Java's `SpellAbility.canProduce(String)`.
694    pub fn can_produce(&self, color: &str) -> bool {
695        match &self.mana_part {
696            Some(mp) => mp.can_produce(color),
697            None => false,
698        }
699    }
700
701    /// Amount of mana generated by this ability.
702    /// Mirrors Java's `SpellAbility.amountOfManaGenerated()`.
703    pub fn amount_of_mana_generated(&self) -> i32 {
704        match &self.mana_part {
705            Some(mp) => mp.amount_of_mana_generated(),
706            None => 0,
707        }
708    }
709
710    /// Total amount of mana generated, counting Any/All as 1.
711    /// Mirrors Java's `SpellAbility.totalAmountOfManaGenerated()`.
712    pub fn total_amount_of_mana_generated(&self) -> i32 {
713        match &self.mana_part {
714            Some(mp) => mp.total_amount_of_mana_generated(),
715            None => 0,
716        }
717    }
718
719    // ── Cost and payment ──────────────────────────────────────────────────
720
721    /// Whether paying with shard mana is allowed.
722    /// Mirrors Java's `SpellAbility.allowsPayingWithShard()`.
723    pub fn allows_paying_with_shard(&self) -> bool {
724        self.ir.allows_paying_with_shard
725    }
726
727    /// Whether this ability cannot be copied.
728    /// Mirrors Java's `SpellAbility.cantBeCopied()`.
729    pub fn cant_be_copied(&self) -> bool {
730        self.ir.cant_be_copied_ability
731    }
732
733    /// Whether this ability can be played (checks restrictions).
734    /// Mirrors Java's `SpellAbility.canPlay()`.
735    pub fn can_play(&self, game: &GameState) -> bool {
736        if let Some(card_id) = self.source {
737            if !self
738                .restriction
739                .can_play_with_sa(game, card_id, self.activating_player, Some(self))
740            {
741                return false;
742            }
743
744            let card = game.card(card_id);
745            if let Some(limit_expr) = self.restriction.variables.limit_to_check() {
746                let limit = crate::svar::resolve_numeric_value(game, self, limit_expr, 0);
747                if card.get_ability_activated_this_turn(Some(self)) as i32 >= limit {
748                    return false;
749                }
750            }
751            if let Some(limit_expr) = self.restriction.variables.game_limit_to_check() {
752                let limit = crate::svar::resolve_numeric_value(game, self, limit_expr, 0);
753                if card.get_ability_activated_this_game(Some(self)) as i32 >= limit {
754                    return false;
755                }
756            }
757
758            true
759        } else {
760            true
761        }
762    }
763
764    /// Whether this ability can be played with optional costs.
765    /// Mirrors Java's `SpellAbility.canPlayWithOptionalCost()`.
766    pub fn can_play_with_optional_cost(&self) -> bool {
767        !self.optional_costs.is_empty()
768    }
769
770    /// Whether to prompt even if this is the only possible ability.
771    /// Mirrors Java's `SpellAbility.promptIfOnlyPossibleAbility()`.
772    pub fn prompt_if_only_possible_ability(&self) -> bool {
773        self.ir.prompt_if_only_possible_ability
774    }
775
776    /// Add an optional cost to this ability.
777    /// Mirrors Java's `SpellAbility.addOptionalCost(OptionalCost)`.
778    pub fn add_optional_cost(&mut self, cost: OptionalCost) {
779        if !self.optional_costs.contains(&cost) {
780            self.optional_costs.push(cost);
781        }
782    }
783
784    /// Whether the mana cost contains X.
785    /// Mirrors Java's `SpellAbility.costHasX()`.
786    pub fn cost_has_x(&self) -> bool {
787        self.ir.cost_has_x
788    }
789
790    /// Whether the mana cost contains X (mana-specific check).
791    /// Mirrors Java's `SpellAbility.costHasManaX()`.
792    pub fn cost_has_mana_x(&self) -> bool {
793        self.ir.cost_has_x
794    }
795
796    /// Whether conditions are met for this ability.
797    /// Mirrors Java's `SpellAbility.metConditions()`.
798    pub fn met_conditions(&self, game: &GameState) -> bool {
799        self.condition.are_met(game, self)
800    }
801
802    /// Clear mana paid tracking.
803    /// Mirrors Java's `SpellAbility.clearManaPaid()`.
804    pub fn clear_mana_paid(&mut self) {
805        self.x_mana_cost_paid = 0;
806    }
807
808    /// Apply effects from paying mana (e.g. Sunburst).
809    /// Mirrors Java's `SpellAbility.applyPayingManaEffects()`.
810    pub fn apply_paying_mana_effects(&mut self) {
811        // Mana payment effects are applied during resolution based on
812        // the colors of mana spent, tracked in the card's colors_spent_to_cast.
813    }
814
815    /// Run this ability (no-op in Rust; Java resolves via resolveStack).
816    /// Mirrors Java's `SpellAbility.run()`.
817    pub fn run(&self) {
818        // Resolution is handled by the stack resolution system in Rust.
819        // This method exists for API parity with Java.
820    }
821
822    // ── Paid cost tracking ────────────────────────────────────────────────
823
824    /// Add a value to the paid cost hash.
825    /// Mirrors Java's `SpellAbility.addCostToHashList(String, String)`.
826    pub fn add_cost_to_hash_list(&mut self, key: &str, value: &str) {
827        self.paid_hash
828            .entry(key.to_string())
829            .or_default()
830            .push(value.to_string());
831    }
832
833    /// Reset the paid cost hash.
834    /// Mirrors Java's `SpellAbility.resetPaidHash()`.
835    pub fn reset_paid_hash(&mut self) {
836        self.paid_hash.clear();
837    }
838
839    // ── Trigger objects ───────────────────────────────────────────────────
840
841    /// Check if a triggering object is set.
842    /// Mirrors Java's `SpellAbility.hasTriggeringObject(String)`.
843    pub fn has_triggering_object<K: TriggerKeyInput>(&self, key: K) -> bool {
844        key.into_ability_key()
845            .map(|parsed| self.trigger_objects.contains_key(&parsed))
846            .unwrap_or(false)
847    }
848
849    /// Get a triggering object value by key.
850    pub fn get_triggering_value(&self, key: AbilityKey) -> Option<&AbilityValue> {
851        self.trigger_objects.get(&key)
852    }
853
854    /// Get a triggering card by key.
855    pub fn get_triggering_card(&self, key: AbilityKey) -> Option<CardId> {
856        match self.get_triggering_value(key) {
857            Some(AbilityValue::Card(card)) => Some(*card),
858            Some(AbilityValue::Cards(cards)) => cards.first().copied(),
859            Some(AbilityValue::GameEntities(entities)) => {
860                entities.iter().find_map(|entity| match entity {
861                    crate::agent::GameEntity::Card(card) => Some(*card),
862                    crate::agent::GameEntity::Player(_) => None,
863                })
864            }
865            _ => None,
866        }
867    }
868
869    /// Get a triggering player by key.
870    pub fn get_triggering_player(&self, key: AbilityKey) -> Option<PlayerId> {
871        match self.get_triggering_value(key) {
872            Some(AbilityValue::Player(player)) => Some(*player),
873            Some(AbilityValue::Players(players)) => players.first().copied(),
874            Some(AbilityValue::GameEntities(entities)) => {
875                entities.iter().find_map(|entity| match entity {
876                    crate::agent::GameEntity::Player(player) => Some(*player),
877                    crate::agent::GameEntity::Card(_) => None,
878                })
879            }
880            _ => None,
881        }
882    }
883
884    /// Get triggering cards by key.
885    pub fn get_triggering_cards(&self, key: AbilityKey) -> Vec<CardId> {
886        match self.get_triggering_value(key) {
887            Some(AbilityValue::Card(card)) => vec![*card],
888            Some(AbilityValue::Cards(cards)) => cards.clone(),
889            Some(AbilityValue::GameEntities(entities)) => entities
890                .iter()
891                .filter_map(|entity| match entity {
892                    crate::agent::GameEntity::Card(card) => Some(*card),
893                    crate::agent::GameEntity::Player(_) => None,
894                })
895                .collect(),
896            _ => Vec::new(),
897        }
898    }
899
900    /// Get triggering players by key.
901    pub fn get_triggering_players(&self, key: AbilityKey) -> Vec<PlayerId> {
902        match self.get_triggering_value(key) {
903            Some(AbilityValue::Player(player)) => vec![*player],
904            Some(AbilityValue::Players(players)) => players.clone(),
905            Some(AbilityValue::GameEntities(entities)) => entities
906                .iter()
907                .filter_map(|entity| match entity {
908                    crate::agent::GameEntity::Player(player) => Some(*player),
909                    crate::agent::GameEntity::Card(_) => None,
910                })
911                .collect(),
912            _ => Vec::new(),
913        }
914    }
915
916    /// Get a triggering object by key.
917    /// Mirrors Java's `SpellAbility.getTriggeringObject(String)`.
918    pub fn get_triggering_object<K: TriggerKeyInput>(&self, key: K) -> Option<&str> {
919        key.into_ability_key()
920            .and_then(|parsed| self.get_triggering_value(parsed))
921            .and_then(|value| match value {
922                AbilityValue::String(raw) => Some(raw.as_str()),
923                _ => None,
924            })
925    }
926
927    /// Clear all triggering objects.
928    /// Mirrors Java's `SpellAbility.resetTriggeringObjects()`.
929    pub fn reset_triggering_objects(&mut self) {
930        self.trigger_objects.clear();
931    }
932
933    /// Cleanup after resolution — reset targets, trigger objects, paid hash.
934    /// Mirrors Java's `SpellAbility.resetOnceResolved()`.
935    pub fn reset_once_resolved(&mut self) {
936        self.clear_targets();
937        self.reset_triggering_objects();
938        self.reset_paid_hash();
939        self.x_mana_cost_paid = 0;
940        self.kick_count = 0;
941        self.replicate_count = 0;
942        self.optional_generic_cost_paid = false;
943        self.discarded_cost_cards.clear();
944        self.optional_costs.clear();
945        self.convoke_tapped.clear();
946        self.spliced_cards.clear();
947        self.announce_vars.clear();
948        self.sacrificed_as_emerge = None;
949        self.sacrificed_as_offering = None;
950    }
951
952    // ── Description and text ──────────────────────────────────────────────
953
954    /// Generate a unique key for this ability.
955    /// Mirrors Java's `SpellAbility.yieldKey()`.
956    pub fn yield_key(&self) -> String {
957        let api_str = self.api.map(|a| format!("{a:?}")).unwrap_or_default();
958        let source_str = self.source.map(|s| format!("{}", s.0)).unwrap_or_default();
959        format!("{api_str}_{source_str}")
960    }
961
962    /// Build a description from params.
963    /// Mirrors Java's `SpellAbility.rebuiltDescription()`.
964    pub fn rebuilt_description(&self) -> String {
965        if !self.description.is_empty() {
966            return self.description.clone();
967        }
968        if let Some(desc) = self.ir.sp_desc_text.as_deref() {
969            return desc.to_string();
970        }
971        self.ability_text.clone()
972    }
973
974    /// Full text without suppression.
975    /// Mirrors Java's `SpellAbility.toUnsuppressedString()`.
976    pub fn to_unsuppressed_string(&self) -> String {
977        self.rebuilt_description()
978    }
979
980    // ── Sub-abilities ─────────────────────────────────────────────────────
981
982    /// Check if an additional ability with the given key exists.
983    /// Mirrors Java's `SpellAbility.hasAdditionalAbility(String)`.
984    pub fn has_additional_ability<K: TriggerKeyInput>(&self, key: K) -> bool {
985        key.into_ability_key()
986            .map(|parsed| self.trigger_spell_abilities.contains_key(&parsed))
987            .unwrap_or(false)
988    }
989
990    /// Get an additional ability by key.
991    /// Mirrors Java's `SpellAbility.getAdditionalAbility(String)`.
992    pub fn get_additional_ability<K: TriggerKeyInput>(&self, key: K) -> Option<&SpellAbility> {
993        key.into_ability_key()
994            .and_then(|parsed| self.trigger_spell_abilities.get(&parsed))
995    }
996
997    /// Set an additional ability by key.
998    /// Mirrors Java's `SpellAbility.setAdditionalAbility(String, SpellAbility)`.
999    pub fn set_additional_ability<K: TriggerKeyInput>(&mut self, key: K, ability: SpellAbility) {
1000        if let Some(parsed) = key.into_ability_key() {
1001            self.trigger_spell_abilities.insert(parsed, ability);
1002        }
1003    }
1004
1005    /// Append a sub-ability to the end of the chain.
1006    /// Mirrors Java's `SpellAbility.appendSubAbility(SpellAbility)`.
1007    pub fn append_sub_ability(&mut self, sub: SpellAbility) {
1008        if self.sub_ability.is_none() {
1009            self.sub_ability = Some(Box::new(sub));
1010        } else {
1011            // Walk to end of chain
1012            let mut current = self.sub_ability.as_deref_mut();
1013            while let Some(sa) = current {
1014                if sa.sub_ability.is_none() {
1015                    sa.sub_ability = Some(Box::new(sub));
1016                    return;
1017                }
1018                current = sa.sub_ability.as_deref_mut();
1019            }
1020        }
1021    }
1022
1023    // ── Copying ───────────────────────────────────────────────────────────
1024
1025    /// Clone this spell ability.
1026    /// Mirrors Java's `SpellAbility.copy()`.
1027    pub fn copy(&self) -> Self {
1028        crate::perf::increment(crate::perf::Metric::SpellAbilityClones, 1);
1029        self.clone()
1030    }
1031
1032    pub fn copy_for_player(&self, activ: PlayerId) -> Self {
1033        crate::perf::increment(crate::perf::Metric::SpellAbilityClones, 1);
1034        let mut clone = self.clone();
1035        clone.activating_player = activ;
1036        clone
1037    }
1038
1039    pub fn copy_with_host_lki(&self, host: crate::card::Card, lki: bool) -> Self {
1040        self.copy_with_host_activating_lki_keep_text_changes(
1041            host,
1042            self.activating_player,
1043            lki,
1044            false,
1045        )
1046    }
1047
1048    pub fn copy_with_host_lki_keep_text_changes(
1049        &self,
1050        host: crate::card::Card,
1051        lki: bool,
1052        keep_text_changes: bool,
1053    ) -> Self {
1054        self.copy_with_host_activating_lki_keep_text_changes(
1055            host,
1056            self.activating_player,
1057            lki,
1058            keep_text_changes,
1059        )
1060    }
1061
1062    pub fn copy_with_host_activating_lki(
1063        &self,
1064        host: crate::card::Card,
1065        activ: PlayerId,
1066        lki: bool,
1067    ) -> Self {
1068        self.copy_with_host_activating_lki_keep_text_changes(host, activ, lki, false)
1069    }
1070
1071    pub fn copy_with_host_activating_lki_keep_text_changes(
1072        &self,
1073        host: crate::card::Card,
1074        activ: PlayerId,
1075        lki: bool,
1076        keep_text_changes: bool,
1077    ) -> Self {
1078        crate::perf::increment(crate::perf::Metric::SpellAbilityClones, 1);
1079        let mut clone = self.clone();
1080        clone.id = if lki {
1081            self.id
1082        } else {
1083            next_spell_ability_id()
1084        };
1085
1086        clone.source = Some(host.id);
1087        clone.may_choose_new_targets = false;
1088        clone.trigger_objects = self.trigger_objects.clone();
1089        if !lki {
1090            clone.replacing_objects = HashMap::new();
1091        }
1092
1093        clone.pay_costs = self.pay_costs.clone();
1094        if self.mana_part.is_some() {
1095            clone.mana_part = self.mana_part.clone();
1096        }
1097
1098        clone.optional_keyword_amounts = self.optional_keyword_amounts.clone();
1099        clone.damage_map = self.damage_map.clone();
1100        clone.prevent_map = self.prevent_map.clone();
1101        clone.change_zone_table = self.change_zone_table.clone();
1102        clone.paying_mana = self.paying_mana.clone();
1103        clone.paid_abilities = Vec::new();
1104        clone.paid_hash = self.paid_hash.clone();
1105
1106        if self.uses_targeting() {
1107            clone.target_chosen = self.target_chosen.clone();
1108        }
1109
1110        clone.trigger_spell_abilities = HashMap::new();
1111        clone.additional_ability_lists = HashMap::new();
1112
1113        if let Some(sub_ability) = &self.sub_ability {
1114            clone.sub_ability = Some(Box::new(
1115                sub_ability.copy_with_host_activating_lki_keep_text_changes(
1116                    host.clone(),
1117                    activ,
1118                    lki,
1119                    keep_text_changes,
1120                ),
1121            ));
1122        }
1123
1124        for (name, ability) in &self.trigger_spell_abilities {
1125            clone.trigger_spell_abilities.insert(
1126                *name,
1127                ability.copy_with_host_activating_lki_keep_text_changes(
1128                    host.clone(),
1129                    activ,
1130                    lki,
1131                    keep_text_changes,
1132                ),
1133            );
1134        }
1135
1136        for (name, abilities) in &self.additional_ability_lists {
1137            clone.additional_ability_lists.insert(
1138                name.clone(),
1139                abilities
1140                    .iter()
1141                    .map(|ability| {
1142                        ability.copy_with_host_activating_lki_keep_text_changes(
1143                            host.clone(),
1144                            activ,
1145                            lki,
1146                            keep_text_changes,
1147                        )
1148                    })
1149                    .collect(),
1150            );
1151        }
1152
1153        clone.restriction = self.restriction.clone();
1154        clone.condition = self.condition.clone();
1155        clone.activating_player = activ;
1156
1157        let _ = keep_text_changes;
1158        clone
1159    }
1160
1161    /// Clone with no mana cost.
1162    /// Mirrors Java's `SpellAbility.copyWithNoManaCost()`.
1163    pub fn copy_with_no_mana_cost(&self) -> Self {
1164        crate::perf::increment(crate::perf::Metric::SpellAbilityClones, 1);
1165        let mut copied = self.clone();
1166        copied.pay_costs = None;
1167        copied
1168    }
1169
1170    /// Clone with a specific cost.
1171    /// Mirrors Java's `SpellAbility.copyWithDefinedCost(String)`.
1172    pub fn copy_with_defined_cost(&self, cost: &str) -> Self {
1173        crate::perf::increment(crate::perf::Metric::SpellAbilityClones, 1);
1174        let mut copied = self.clone();
1175        copied.pay_costs = Some(parse_cost(cost));
1176        copied
1177    }
1178
1179    /// Clone with mana cost replacement.
1180    /// Mirrors Java's `SpellAbility.copyWithManaCostReplaced(String, String)`.
1181    pub fn copy_with_mana_cost_replaced(&self, old: &str, new: &str) -> Self {
1182        crate::perf::increment(crate::perf::Metric::SpellAbilityClones, 1);
1183        let mut copied = self.clone();
1184        if let Some(ref cost) = self.pay_costs {
1185            let cost_str = format!("{cost:?}");
1186            let replaced = cost_str.replace(old, new);
1187            copied.pay_costs = Some(parse_cost(&replaced));
1188        }
1189        copied
1190    }
1191
1192    // ── Targeting ─────────────────────────────────────────────────────────
1193
1194    /// Check if this ability can target a specific card.
1195    /// Mirrors Java's `SpellAbility.canTarget(Card)`.
1196    pub fn can_target(&self, card: CardId, game: &GameState) -> bool {
1197        if let Some(ref tr) = self.target_restrictions {
1198            tr.has_candidates(game, self.activating_player, self.source)
1199                && self
1200                    .ir
1201                    .targets_with_defined_controller_text
1202                    .as_deref()
1203                    .map(|defined| {
1204                        crate::ability::ability_utils::resolve_defined_players_with_sa(
1205                            defined,
1206                            self,
1207                            self.activating_player,
1208                            game,
1209                        )
1210                    })
1211                    .map(|players| {
1212                        players.is_empty() || players.contains(&game.card(card).controller)
1213                    })
1214                    .unwrap_or(true)
1215                && target_restrictions::can_be_targeted_by_sa(
1216                    game,
1217                    card,
1218                    self.activating_player,
1219                    self,
1220                )
1221        } else {
1222            false
1223        }
1224    }
1225
1226    /// Reset targets (alias for clear_targets).
1227    /// Mirrors Java's `SpellAbility.resetTargets()`.
1228    pub fn reset_targets(&mut self) {
1229        self.clear_targets();
1230    }
1231
1232    /// Add divided allocation for a target.
1233    /// Mirrors Java's `SpellAbility.addDividedAllocation(Card, int)`.
1234    pub fn add_divided_allocation(&mut self, card: CardId, amount: i32) {
1235        self.target_chosen.add_divided_allocation(card, amount);
1236    }
1237
1238    /// Reset only the first target in the chain.
1239    /// Mirrors Java's `SpellAbility.resetFirstTarget()`.
1240    pub fn reset_first_target(&mut self) {
1241        self.target_chosen = TargetChoices::default();
1242    }
1243
1244    /// Check if more targets can be added.
1245    /// Mirrors Java's `SpellAbility.canAddMoreTarget()`.
1246    pub fn can_add_more_target(&self, game: &GameState) -> bool {
1247        if let Some(ref tr) = self.target_restrictions {
1248            let max = tr.get_max_targets(game, self);
1249            let current = self.target_chosen.all_target_cards().len() as i32
1250                + self.target_chosen.all_target_players().len() as i32;
1251            current < max
1252        } else {
1253            false
1254        }
1255    }
1256
1257    /// Collect all targeted cards from the entire chain.
1258    /// Mirrors Java's `SpellAbility.findTargetedCards()`.
1259    pub fn find_targeted_cards(&self) -> Vec<CardId> {
1260        let mut cards = Vec::new();
1261        cards.extend(self.target_chosen.all_target_cards());
1262        let mut current = self.sub_ability.as_deref();
1263        while let Some(sub) = current {
1264            cards.extend(sub.target_chosen.all_target_cards());
1265            current = sub.sub_ability.as_deref();
1266        }
1267        cards
1268    }
1269
1270    /// Collect all targeted players from the entire chain.
1271    /// Mirrors Java's `SpellAbility.findTargetedPlayers()`.
1272    pub fn find_targeted_players(&self) -> Vec<PlayerId> {
1273        let mut players = Vec::new();
1274        players.extend(self.target_chosen.all_target_players());
1275        let mut current = self.sub_ability.as_deref();
1276        while let Some(sub) = current {
1277            for player in sub.target_chosen.all_target_players() {
1278                if !players.contains(&player) {
1279                    players.push(player);
1280                }
1281            }
1282            current = sub.sub_ability.as_deref();
1283        }
1284        players
1285    }
1286
1287    /// Whether this ability targets spells/abilities on the stack.
1288    /// Mirrors Java's `SpellAbility.canTargetSpellAbility()`.
1289    pub fn can_target_spell_ability(&self) -> bool {
1290        matches!(
1291            self.target_restrictions.as_ref().map(|tr| &tr.target_kind),
1292            Some(TargetKind::Spell)
1293        )
1294    }
1295
1296    /// Setup new targets for a retargeting scenario.
1297    /// Mirrors Java's `SpellAbility.setupNewTargets()`.
1298    pub fn setup_new_targets(
1299        &mut self,
1300        game: &GameState,
1301        agents: &mut [Box<dyn PlayerAgent>],
1302        mana_pools: &[ManaPool],
1303    ) -> bool {
1304        self.clear_targets();
1305        self.setup_targets(game, agents, mana_pools)
1306    }
1307
1308    // ── Convoke / Emerge / Offering ───────────────────────────────────────
1309
1310    /// Clear pip reduction tracking.
1311    /// Mirrors Java's `SpellAbility.clearPipsToReduce()`.
1312    pub fn clear_pips_to_reduce(&mut self) {
1313        self.pips_to_reduce.clear();
1314    }
1315
1316    /// Add a card tapped for convoke.
1317    /// Mirrors Java's `SpellAbility.addTappedForConvoke(Card)`.
1318    pub fn add_tapped_for_convoke(&mut self, card: CardId) {
1319        self.convoke_tapped.push(card);
1320    }
1321
1322    /// Clear convoke tracking.
1323    /// Mirrors Java's `SpellAbility.clearTappedForConvoke()`.
1324    pub fn clear_tapped_for_convoke(&mut self) {
1325        self.convoke_tapped.clear();
1326    }
1327
1328    /// Reset the sacrificed-as-emerge card.
1329    /// Mirrors Java's `SpellAbility.resetSacrificedAsEmerge()`.
1330    pub fn reset_sacrificed_as_emerge(&mut self) {
1331        self.sacrificed_as_emerge = None;
1332    }
1333
1334    /// Reset the sacrificed-as-offering card.
1335    /// Mirrors Java's `SpellAbility.resetSacrificedAsOffering()`.
1336    pub fn reset_sacrificed_as_offering(&mut self) {
1337        self.sacrificed_as_offering = None;
1338    }
1339
1340    // ── Splice ────────────────────────────────────────────────────────────
1341
1342    /// Add spliced cards to this spell.
1343    /// Mirrors Java's `SpellAbility.addSplicedCards(List<Card>)`.
1344    pub fn add_spliced_cards(&mut self, cards: Vec<CardId>) {
1345        self.spliced_cards.extend(cards);
1346    }
1347
1348    // ── Deterministic checks ──────────────────────────────────────────────
1349
1350    /// Whether `Defined$` resolves to a deterministic set of objects.
1351    /// Mirrors Java's `SpellAbility.knownDetermineDefined()`.
1352    pub fn known_determine_defined(&self) -> bool {
1353        match self.defined() {
1354            Some(defined) => matches!(
1355                defined,
1356                "Self"
1357                    | "You"
1358                    | "Targeted"
1359                    | "TargetedPlayer"
1360                    | "Remembered"
1361                    | "ParentTarget"
1362                    | "SourceController"
1363                    | "Imprinted"
1364            ),
1365            None => true,
1366        }
1367    }
1368
1369    // ── Undo ──────────────────────────────────────────────────────────────
1370
1371    /// Undo this ability.
1372    /// Mirrors Java's `SpellAbility.undo()`.
1373    pub fn undo(&mut self) -> bool {
1374        self.clear_tapped_for_convoke();
1375        self.reset_sacrificed_as_emerge();
1376        self.reset_sacrificed_as_offering();
1377        self.reset_paid_hash();
1378        self.clear_mana_paid();
1379        true
1380    }
1381
1382    // ── Announce vars ─────────────────────────────────────────────────────
1383
1384    /// Add an announced variable value.
1385    /// Mirrors Java's `SpellAbility.addAnnounceVar(String, int)`.
1386    pub fn add_announce_var(&mut self, key: &str, value: i32) {
1387        self.announce_vars.insert(key.to_string(), value);
1388    }
1389
1390    // ── Targeting by SA ───────────────────────────────────────────────────
1391
1392    /// Check if this spell ability can be targeted by another SA.
1393    /// Mirrors Java's `SpellAbility.canBeTargetedBy(SpellAbility)`.
1394    pub fn can_be_targeted_by(&self, _sa: &SpellAbility) -> bool {
1395        // Spells on the stack can generally be targeted unless they have
1396        // "can't be countered" or similar protection. The basic check is
1397        // whether this is a spell (on the stack).
1398        if self.is_spell {
1399            return !self.cant_be_copied();
1400        }
1401        true
1402    }
1403
1404    // ── Property checks ───────────────────────────────────────────────────
1405
1406    /// Check if this ability has a specific property.
1407    /// Mirrors Java's `SpellAbility.hasProperty(String)`.
1408    pub fn has_property(&self, property: &str) -> bool {
1409        match property {
1410            "Spell" => self.is_spell,
1411            "Trigger" => self.is_trigger,
1412            "Activated" => self.is_activated,
1413            "ManaAbility" => self.is_mana_ability,
1414            "Optional" => self.ir.optional,
1415            "Mandatory" => self.ir.mandatory,
1416            "Tapped" => self.ir.tapped,
1417            "Hidden" => self.ir.hidden,
1418            "FaceDown" => self.ir.face_down,
1419            "ExileFaceDown" => self.ir.exile_face_down,
1420            "Transformed" => self.ir.transformed,
1421            "AtRandom" => self.ir.at_random,
1422            "Imprint" => self.ir.imprint,
1423            "Morph" => self.ir.morph,
1424            "MorphUp" => self.ir.morph_up,
1425            "Megamorph" => self.ir.megamorph,
1426            "PwAbility" => self.ir.pw_ability,
1427            "Flash" => self.ir.flash,
1428            "SplitSecond" => self.ir.split_second,
1429            _ => false,
1430        }
1431    }
1432
1433    pub fn is_last_chapter(&self, game: &crate::game::GameState) -> bool {
1434        let Some(source) = self.trigger_source.or(self.source) else {
1435            return false;
1436        };
1437        let Some(trigger_id) = self.source_trigger_id else {
1438            return false;
1439        };
1440        let card = game.card(source);
1441        card.triggers
1442            .iter()
1443            .find(|trigger| trigger.id == trigger_id)
1444            .is_some_and(|trigger| trigger.is_last_chapter(card))
1445    }
1446
1447    /// Whether this ability tracks mana spent.
1448    /// Mirrors Java's `SpellAbility.tracksManaSpent()`.
1449    pub fn tracks_mana_spent(&self) -> bool {
1450        self.ir.track_mana_spent
1451    }
1452
1453    // ── Text changes ──────────────────────────────────────────────────────
1454
1455    /// Apply text replacement.
1456    /// Mirrors Java's `SpellAbility.changeText(String, String)`.
1457    pub fn apply_text_change(&mut self, original: &str, replacement: &str) {
1458        if original == replacement {
1459            return;
1460        }
1461        self.description = self.description.replace(original, replacement);
1462        self.stack_description = self.stack_description.replace(original, replacement);
1463        if let Some(ref mut tr) = self.target_restrictions {
1464            tr.apply_target_text_changes(&[(original, replacement)]);
1465        }
1466
1467        if let Some(sub_ability) = self.sub_ability.as_deref_mut() {
1468            sub_ability.apply_text_change(original, replacement);
1469        }
1470
1471        for ability in self.trigger_spell_abilities.values_mut() {
1472            ability.apply_text_change(original, replacement);
1473        }
1474    }
1475
1476    /// Apply intrinsic text replacement.
1477    /// Mirrors Java's `SpellAbility.changeTextIntrinsic(String, String)`.
1478    pub fn apply_text_change_intrinsic(&mut self, original: &str, replacement: &str) {
1479        self.apply_text_change(original, replacement);
1480    }
1481
1482    /// Apply a batch of text replacements to this ability and linked abilities.
1483    pub fn apply_text_changes(&mut self, pairs: &[(String, String)]) {
1484        for (original, replacement) in pairs {
1485            self.apply_text_change(original, replacement);
1486        }
1487    }
1488
1489    /// Apply intrinsic text changes to this ability and linked abilities.
1490    pub fn apply_text_changes_intrinsic(
1491        &mut self,
1492        color_map: &HashMap<String, String>,
1493        type_map: &HashMap<String, String>,
1494    ) {
1495        for (original, replacement) in color_map.iter().chain(type_map.iter()) {
1496            self.apply_text_change_intrinsic(original, replacement);
1497        }
1498    }
1499
1500    /// Java parity hook for `SpellAbility.setHostCard(Card)`.
1501    pub fn set_host_card(&mut self, card: crate::card::Card) {
1502        self.set_host_card_id(card.id);
1503    }
1504
1505    pub fn set_host_card_id(&mut self, card_id: CardId) {
1506        self.source = Some(card_id);
1507        if self.original_host.is_none() {
1508            self.original_host = Some(card_id);
1509        }
1510
1511        if let Some(sub_ability) = self.sub_ability.as_deref_mut() {
1512            sub_ability.set_host_card_id(card_id);
1513        }
1514
1515        for ability in self.trigger_spell_abilities.values_mut() {
1516            ability.set_host_card_id(card_id);
1517        }
1518    }
1519
1520    /// Java parity hook for `SpellAbility.setKeyword(KeywordInterface)`.
1521    pub fn set_keyword(&mut self, keyword: crate::keyword::keyword_interface::KeywordInterface) {
1522        if let Some(sub_ability) = self.sub_ability.as_deref_mut() {
1523            sub_ability.set_keyword(keyword.clone());
1524        }
1525
1526        for ability in self.trigger_spell_abilities.values_mut() {
1527            ability.set_keyword(keyword.clone());
1528        }
1529    }
1530
1531    /// Java parity hook for `SpellAbility.setCardState(CardState)`.
1532    #[allow(clippy::only_used_in_recursion)]
1533    pub fn set_card_state(&mut self, state: &crate::card::card_state::CardState) {
1534        if let Some(sub_ability) = self.sub_ability.as_deref_mut() {
1535            sub_ability.set_card_state(state);
1536        }
1537
1538        for ability in self.trigger_spell_abilities.values_mut() {
1539            ability.set_card_state(state);
1540        }
1541    }
1542
1543    /// Java parity hook for `SpellAbility.setIntrinsic(boolean)`.
1544    pub fn set_intrinsic(&mut self, intrinsic: bool) {
1545        self.intrinsic = intrinsic;
1546
1547        if let Some(sub_ability) = self.sub_ability.as_deref_mut() {
1548            if sub_ability.is_intrinsic() != intrinsic {
1549                sub_ability.set_intrinsic(intrinsic);
1550            }
1551        }
1552
1553        for ability in self.trigger_spell_abilities.values_mut() {
1554            if ability.is_intrinsic() != intrinsic {
1555                ability.set_intrinsic(intrinsic);
1556            }
1557        }
1558    }
1559
1560    pub fn is_intrinsic(&self) -> bool {
1561        self.intrinsic
1562    }
1563
1564    /// Mirrors Java's `SpellAbility.getAmountLifePaid()`.
1565    pub fn get_amount_life_paid(&self) -> i32 {
1566        self.paid_life_amount
1567    }
1568
1569    /// Mirrors Java's `SpellAbility.setAmountLifePaid(int)`.
1570    pub fn set_amount_life_paid(&mut self, value: i32) {
1571        self.paid_life_amount = value;
1572    }
1573
1574    // ── AI scoring ────────────────────────────────────────────────────────
1575
1576    /// Calculate an AI score for this mana ability.
1577    /// Mirrors Java's `SpellAbility.calculateScoreForManaAbility()`.
1578    pub fn calculate_score_for_mana_ability(&self) -> i32 {
1579        if !self.is_mana_ability {
1580            return 0;
1581        }
1582        let base = self.total_amount_of_mana_generated();
1583        // Prefer abilities that produce more mana and have fewer restrictions
1584        let restriction_penalty = if self.restriction.variables.sorcery_speed() {
1585            -1
1586        } else {
1587            0
1588        };
1589        base + restriction_penalty
1590    }
1591
1592    // ── Timing checks ─────────────────────────────────────────────────────
1593
1594    /// Check if this ability can be cast at the current timing.
1595    /// Mirrors Java's `SpellAbility.canCastTiming(Game)`.
1596    pub fn can_cast_timing(&self, game: &GameState) -> bool {
1597        let can_cast_sorcery = game.turn.phase.is_main()
1598            && game.stack.is_empty()
1599            && game.turn.active_player == self.activating_player;
1600
1601        // Non-spell, non-activated abilities do not have default timing checks here.
1602        if !self.is_spell && !self.is_activated {
1603            return true;
1604        }
1605
1606        if can_cast_sorcery || self.with_flash(game) {
1607            return true;
1608        }
1609
1610        // Spells are sorcery-speed by default unless an explicit timing permission applies.
1611        if self.is_spell {
1612            return false;
1613        }
1614
1615        // Activated abilities are instant-speed by default except for explicit
1616        // sorcery-speed restrictions and planeswalker abilities.
1617        if self.is_activated {
1618            return !self.ir.pw_ability && !self.restriction.variables.sorcery_speed();
1619        }
1620
1621        true
1622    }
1623
1624    /// Check if this spell has flash.
1625    /// Mirrors Java's `SpellAbility.withFlash(Game)`.
1626    pub fn with_flash(&self, game: &GameState) -> bool {
1627        if self.restriction.variables.instant_speed() {
1628            return true;
1629        }
1630        if self.ir.flash {
1631            return true;
1632        }
1633        if let Some(card_id) = self.source {
1634            let card = game.card(card_id);
1635            if ((self.is_spell || self.is_land_ability) && card.type_line.is_instant())
1636                || card.has_keyword("Flash")
1637            {
1638                return true;
1639            }
1640            return crate::staticability::static_ability_cast_with_flash::any_with_flash_for_card(
1641                &game.cards,
1642                card,
1643                self.activating_player,
1644            );
1645        }
1646        false
1647    }
1648
1649    /// Check restrictions for this ability.
1650    /// Mirrors Java's `SpellAbility.checkRestrictions(Game)`.
1651    pub fn check_restrictions(&self, game: &GameState) -> bool {
1652        self.can_play(game)
1653    }
1654
1655    // ── Rollback ──────────────────────────────────────────────────────────
1656
1657    /// Add a rollback effect.
1658    /// Mirrors Java's `SpellAbility.addRollbackEffect(String)`.
1659    pub fn add_rollback_effect(&mut self, effect: String) {
1660        self.rollback_effects.push(effect);
1661    }
1662
1663    /// Rollback all tracked effects.
1664    /// Mirrors Java's `SpellAbility.rollback()`.
1665    pub fn rollback(&mut self) -> bool {
1666        let had_effects = !self.rollback_effects.is_empty();
1667        self.rollback_effects.clear();
1668        had_effects
1669    }
1670
1671    // ── Optional keyword amounts ──────────────────────────────────────────
1672
1673    /// Check if this ability has an optional keyword with a specific amount.
1674    /// Mirrors Java's `SpellAbility.hasOptionalKeywordAmount(String)`.
1675    pub fn has_optional_keyword_amount(&self, keyword: &str) -> bool {
1676        self.optional_keyword_amounts.contains_key(keyword)
1677    }
1678
1679    /// Clear all optional keyword amounts.
1680    /// Mirrors Java's `SpellAbility.clearOptionalKeywordAmount()`.
1681    pub fn clear_optional_keyword_amount(&mut self) {
1682        self.optional_keyword_amounts.clear();
1683    }
1684
1685    /// Clear last known state tracking.
1686    /// Mirrors Java's `SpellAbility.clearLastState()`.
1687    pub fn clear_last_state(&mut self) {
1688        self.last_state.clear();
1689    }
1690
1691    // ── Trigger object management ─────────────────────────────────────────
1692
1693    /// Set a triggering object in the map.
1694    /// Mirrors Java's `SpellAbility.setTriggeringObject(AbilityKey, Object)`.
1695    pub fn set_triggering_object<K: TriggerKeyInput, V: Into<AbilityValue>>(
1696        &mut self,
1697        key: K,
1698        value: V,
1699    ) {
1700        if let Some(parsed) = key.into_ability_key() {
1701            self.trigger_objects.insert(parsed, value.into());
1702        }
1703    }
1704
1705    /// Typed trigger value setter.
1706    pub fn set_triggering_value<V: Into<AbilityValue>>(&mut self, key: AbilityKey, value: V) {
1707        self.trigger_objects.insert(key, value.into());
1708    }
1709
1710    /// Set a triggering spell ability in the map.
1711    /// Mirrors Java's `SpellAbility.setTriggeringObject(AbilityKey, Object)` for SpellAbility values.
1712    pub fn set_triggering_spell_ability<K: TriggerKeyInput>(
1713        &mut self,
1714        key: K,
1715        value: SpellAbility,
1716    ) {
1717        if let Some(parsed) = key.into_ability_key() {
1718            self.trigger_spell_abilities.insert(parsed, value);
1719        }
1720    }
1721
1722    /// Get a triggering spell ability from the map.
1723    pub fn get_triggering_spell_ability<K: TriggerKeyInput>(
1724        &self,
1725        key: K,
1726    ) -> Option<&SpellAbility> {
1727        key.into_ability_key()
1728            .and_then(|parsed| self.trigger_spell_abilities.get(&parsed))
1729    }
1730
1731    /// Update an existing triggering object.
1732    /// Mirrors Java's `SpellAbility.updateTriggeringObject(String, Object)`.
1733    pub fn update_triggering_object<K: TriggerKeyInput, V: Into<AbilityValue>>(
1734        &mut self,
1735        key: K,
1736        value: V,
1737    ) {
1738        self.set_triggering_object(key, value);
1739    }
1740
1741    // ── Target management ─────────────────────────────────────────────────
1742
1743    /// Update a target in the chosen targets.
1744    /// Mirrors Java's `SpellAbility.updateTarget(Card, Card)`.
1745    pub fn update_target(&mut self, old: CardId, new: CardId) {
1746        self.target_chosen.replace_target_card(old, new);
1747    }
1748
1749    /// Whether this targets a single target only.
1750    /// Mirrors Java's `SpellAbility.targetsSingleTarget()`.
1751    pub fn targets_single_target(&self) -> bool {
1752        if let Some(ref tr) = self.target_restrictions {
1753            tr.max_targets == "1"
1754        } else {
1755            false
1756        }
1757    }
1758
1759    // ── Variable operand getters/setters ──────────────────────────────────
1760    // These mirror Java's SpellAbilityVariables Operand/ToCheck/Operator accessors.
1761    // In Rust, they are stored in the SpellAbilityVariables but accessed via SA.
1762
1763    /// Get variable operand 1.
1764    /// Mirrors Java's `SpellAbility.getSVar("Operand")`.
1765    pub fn gets_var_operand(&self) -> Option<&str> {
1766        self.condition
1767            .variables
1768            .gets_var_operand()
1769            .or_else(|| self.restriction.variables.gets_var_operand())
1770    }
1771
1772    /// Get variable operand 2.
1773    /// Mirrors Java's `SpellAbility.getSVar("Operand2")`.
1774    pub fn gets_var_operand2(&self) -> Option<&str> {
1775        self.condition
1776            .variables
1777            .gets_var_operand2()
1778            .or_else(|| self.restriction.variables.gets_var_operand2())
1779    }
1780
1781    /// Set variable operand 1.
1782    /// Mirrors Java's `SpellAbility.setSVar("Operand", val)`.
1783    pub fn sets_var_operand(&mut self, value: &str) {
1784        self.condition.variables.sets_var_operand(value);
1785        self.restriction.variables.sets_var_operand(value);
1786    }
1787
1788    /// Set variable operand 2.
1789    /// Mirrors Java's `SpellAbility.setSVar("Operand2", val)`.
1790    pub fn sets_var_operand2(&mut self, value: &str) {
1791        self.condition.variables.sets_var_operand2(value);
1792        self.restriction.variables.sets_var_operand2(value);
1793    }
1794
1795    /// Get variable to check 1.
1796    /// Mirrors Java's `SpellAbility.getSVar("VarToCheck")`.
1797    pub fn gets_var_to_check(&self) -> Option<&str> {
1798        self.condition
1799            .variables
1800            .gets_var_to_check()
1801            .or_else(|| self.restriction.variables.gets_var_to_check())
1802    }
1803
1804    /// Get variable to check 2.
1805    /// Mirrors Java's `SpellAbility.getSVar("VarToCheck2")`.
1806    pub fn gets_var_to_check2(&self) -> Option<&str> {
1807        self.condition
1808            .variables
1809            .gets_var_to_check2()
1810            .or_else(|| self.restriction.variables.gets_var_to_check2())
1811    }
1812
1813    /// Set variable to check 1.
1814    /// Mirrors Java's `SpellAbility.setSVar("VarToCheck", val)`.
1815    pub fn sets_var_to_check(&mut self, value: &str) {
1816        self.condition.variables.sets_var_to_check(value);
1817        self.restriction.variables.sets_var_to_check(value);
1818    }
1819
1820    /// Set variable to check 2.
1821    /// Mirrors Java's `SpellAbility.setSVar("VarToCheck2", val)`.
1822    pub fn sets_var_to_check2(&mut self, value: &str) {
1823        self.condition.variables.sets_var_to_check2(value);
1824        self.restriction.variables.sets_var_to_check2(value);
1825    }
1826
1827    /// Get variable operator 1.
1828    /// Mirrors Java's `SpellAbility.getSVar("Operator")`.
1829    pub fn gets_var_operator(&self) -> Option<&str> {
1830        self.condition
1831            .variables
1832            .gets_var_operator()
1833            .or_else(|| self.restriction.variables.gets_var_operator())
1834    }
1835
1836    /// Get variable operator 2.
1837    /// Mirrors Java's `SpellAbility.getSVar("Operator2")`.
1838    pub fn gets_var_operator2(&self) -> Option<&str> {
1839        self.condition
1840            .variables
1841            .gets_var_operator2()
1842            .or_else(|| self.restriction.variables.gets_var_operator2())
1843    }
1844
1845    /// Set variable operator 1.
1846    /// Mirrors Java's `SpellAbility.setSVar("Operator", val)`.
1847    pub fn sets_var_operator(&mut self, value: &str) {
1848        self.condition.variables.sets_var_operator(value);
1849        self.restriction.variables.sets_var_operator(value);
1850    }
1851
1852    /// Set variable operator 2.
1853    /// Mirrors Java's `SpellAbility.setSVar("Operator2", val)`.
1854    pub fn sets_var_operator2(&mut self, value: &str) {
1855        self.condition.variables.sets_var_operator2(value);
1856        self.restriction.variables.sets_var_operator2(value);
1857    }
1858}
1859
1860// build_spell_ability now lives in ability::ability_factory.
1861// Re-export here for backward compatibility.
1862pub use crate::ability::ability_factory::build_spell_ability;
1863pub use crate::ability::ability_factory::build_spell_ability_for_card_cast;
1864pub use crate::ability::ability_factory::build_spell_ability_from_host_card;
1865
1866/// Check whether any spell on the stack has split second.
1867/// Split second prevents players from casting spells or activating abilities
1868/// (except mana abilities) while it's on the stack.
1869/// Single source of truth — used by spell, ability, and ability_activated modules.
1870pub fn has_split_second_on_stack(game: &GameState) -> bool {
1871    for entry in game.stack.iter() {
1872        if entry.spell_ability.ir.split_second {
1873            return true;
1874        }
1875        if let Some(card_id) = entry.spell_ability.source {
1876            let card = game.card(card_id);
1877            if card.has_keyword("Split second") {
1878                return true;
1879            }
1880        }
1881    }
1882    false
1883}
1884
1885pub fn choose_targets_by_kind(
1886    agent: &mut dyn PlayerAgent,
1887    sa: &mut SpellAbility,
1888    game: &GameState,
1889    mana_pools: &[ManaPool],
1890) -> bool {
1891    use crate::card::card_util;
1892
1893    let tr = match &sa.target_restrictions {
1894        Some(tr) => tr,
1895        None => return true,
1896    };
1897
1898    let player = sa.targeting_player.unwrap_or(sa.activating_player);
1899
1900    let min_targets = tr.get_min_targets(game, sa);
1901    let max_targets = tr.get_max_targets(game, sa);
1902    if max_targets <= 0 {
1903        return true;
1904    }
1905
1906    if !matches!(tr.target_kind, TargetKind::CardInZone { .. })
1907        && !tr.has_candidates(game, player, sa.source)
1908    {
1909        return min_targets <= 0;
1910    }
1911
1912    sa.target_chosen.target_card = None;
1913    sa.target_chosen.target_card_zone_timestamp = None;
1914    sa.target_chosen.divided_map.clear();
1915
1916    match &tr.target_kind {
1917        TargetKind::None => {}
1918        TargetKind::Player => {
1919            agent.snapshot_state(game, mana_pools);
1920            let is_opponent_only = tr
1921                .valid_tgts
1922                .iter()
1923                .any(|v| v.eq_ignore_ascii_case("Opponent"));
1924            let valid_players: Vec<PlayerId> = game
1925                .alive_players()
1926                .into_iter()
1927                .filter(|&pid| !is_opponent_only || pid != player)
1928                .collect();
1929            if max_targets > 1 {
1930                let mut chosen = Vec::new();
1931                while (chosen.len() as i32) < max_targets {
1932                    let Some(pid) = agent.choose_target_player(player, &valid_players, Some(&*sa))
1933                    else {
1934                        break;
1935                    };
1936                    if !chosen.contains(&pid) {
1937                        chosen.push(pid);
1938                    }
1939                    if chosen.len() == valid_players.len() {
1940                        break;
1941                    }
1942                }
1943                sa.target_chosen.target_player = chosen.first().copied();
1944                sa.target_chosen.additional_target_players = chosen.into_iter().skip(1).collect();
1945            } else {
1946                sa.target_chosen.target_player =
1947                    agent.choose_target_player(player, &valid_players, Some(&*sa));
1948            }
1949        }
1950        TargetKind::Any => {
1951            let valid_players: Vec<PlayerId> =
1952                if target_restrictions::any_target_allows_players(&tr.valid_tgts) {
1953                    game.alive_players().into_iter().collect()
1954                } else {
1955                    Vec::new()
1956                };
1957            let valid_cards: Vec<CardId> = card_util::get_valid_cards_to_target(game, sa);
1958            agent.snapshot_state(game, mana_pools);
1959            match agent.choose_target_any(player, &valid_players, &valid_cards, Some(&*sa)) {
1960                crate::agent::TargetChoice::Player(pid) => {
1961                    sa.target_chosen.target_player = Some(pid)
1962                }
1963                crate::agent::TargetChoice::Card(cid) => {
1964                    sa.target_chosen.target_card = Some(cid);
1965                    sa.target_chosen.target_card_zone_timestamp =
1966                        Some(game.card(cid).zone_timestamp);
1967                }
1968                crate::agent::TargetChoice::None => {}
1969            }
1970        }
1971        TargetKind::Creature(_) => {
1972            let valid: Vec<CardId> = card_util::get_valid_cards_to_target(game, sa)
1973                .into_iter()
1974                .filter(|&cid| target_allowed_by_defined_controller(game, sa, cid))
1975                .collect();
1976            agent.snapshot_state(game, mana_pools);
1977            if max_targets > 1 {
1978                let chosen = agent.choose_cards_for_effect(
1979                    player,
1980                    &valid,
1981                    min_targets.max(0) as usize,
1982                    max_targets as usize,
1983                );
1984                if let Some(&first) = chosen.first() {
1985                    sa.target_chosen.target_card = Some(first);
1986                    sa.target_chosen.target_card_zone_timestamp =
1987                        Some(game.card(first).zone_timestamp);
1988                    for &extra in chosen.iter().skip(1) {
1989                        sa.target_chosen.divided_map.insert(extra, 0);
1990                    }
1991                }
1992            } else {
1993                sa.target_chosen.target_card = agent.choose_target_card(player, &valid, Some(&*sa));
1994                if let Some(cid) = sa.target_chosen.target_card {
1995                    sa.target_chosen.target_card_zone_timestamp =
1996                        Some(game.card(cid).zone_timestamp);
1997                }
1998            }
1999        }
2000        TargetKind::Permanent(_) => {
2001            let valid: Vec<CardId> = card_util::get_valid_cards_to_target(game, sa)
2002                .into_iter()
2003                .filter(|&cid| target_allowed_by_defined_controller(game, sa, cid))
2004                .collect();
2005            agent.snapshot_state(game, mana_pools);
2006            if max_targets > 1 {
2007                let chosen = agent.choose_cards_for_effect(
2008                    player,
2009                    &valid,
2010                    min_targets.max(0) as usize,
2011                    max_targets as usize,
2012                );
2013                if let Some(&first) = chosen.first() {
2014                    sa.target_chosen.target_card = Some(first);
2015                    sa.target_chosen.target_card_zone_timestamp =
2016                        Some(game.card(first).zone_timestamp);
2017                    for &extra in chosen.iter().skip(1) {
2018                        sa.target_chosen.divided_map.insert(extra, 0);
2019                    }
2020                }
2021            } else {
2022                sa.target_chosen.target_card = agent.choose_target_card(player, &valid, Some(&*sa));
2023                if let Some(cid) = sa.target_chosen.target_card {
2024                    sa.target_chosen.target_card_zone_timestamp =
2025                        Some(game.card(cid).zone_timestamp);
2026                }
2027            }
2028        }
2029        TargetKind::CardInZone { zone, .. } => {
2030            let valid: Vec<CardId> = card_util::get_valid_cards_to_target(game, sa)
2031                .into_iter()
2032                .filter(|&cid| target_allowed_by_defined_controller(game, sa, cid))
2033                .collect();
2034            if valid.is_empty() {
2035                return min_targets <= 0;
2036            }
2037            agent.snapshot_state(game, mana_pools);
2038            if max_targets > 1 {
2039                let chosen = agent.choose_cards_for_effect(
2040                    player,
2041                    &valid,
2042                    min_targets.max(0) as usize,
2043                    max_targets as usize,
2044                );
2045                if let Some(&first) = chosen.first() {
2046                    sa.target_chosen.target_card = Some(first);
2047                    sa.target_chosen.target_card_zone_timestamp =
2048                        Some(game.card(first).zone_timestamp);
2049                    for &extra in chosen.iter().skip(1) {
2050                        sa.target_chosen.divided_map.insert(extra, 0);
2051                    }
2052                }
2053            } else {
2054                sa.target_chosen.target_card =
2055                    agent.choose_target_card_from_zone(player, *zone, &valid, Some(&*sa));
2056                if let Some(cid) = sa.target_chosen.target_card {
2057                    sa.target_chosen.target_card_zone_timestamp =
2058                        Some(game.card(cid).zone_timestamp);
2059                }
2060            }
2061        }
2062        TargetKind::Spell => {
2063            let valid = target_restrictions::get_all_candidates_spells(game);
2064            let valid = if let Some(ref restrictions) = sa.target_restrictions {
2065                target_restrictions::filter_spells_for_target_restrictions(
2066                    game,
2067                    &valid,
2068                    restrictions,
2069                )
2070            } else {
2071                valid
2072            };
2073            agent.snapshot_state(game, mana_pools);
2074            sa.target_chosen.target_stack_entry =
2075                agent.choose_target_spell(player, &valid, sa.source);
2076        }
2077    }
2078
2079    let chosen_targets = sa.target_chosen.all_target_cards().len() as i32
2080        + sa.target_chosen.all_target_players().len() as i32
2081        + i32::from(sa.target_chosen.target_stack_entry.is_some());
2082    chosen_targets >= min_targets
2083}
2084
2085fn target_allowed_by_defined_controller(
2086    game: &GameState,
2087    sa: &SpellAbility,
2088    card_id: CardId,
2089) -> bool {
2090    let Some(defined) = sa.ir.targets_with_defined_controller_text.as_deref() else {
2091        return true;
2092    };
2093    let players = crate::ability::ability_utils::resolve_defined_players_with_sa(
2094        defined,
2095        sa,
2096        sa.activating_player,
2097        game,
2098    );
2099    players.is_empty() || players.contains(&game.card(card_id).controller)
2100}
2101
2102fn choose_targeting_player(
2103    sa: &SpellAbility,
2104    game: &GameState,
2105    agents: &mut [Box<dyn PlayerAgent>],
2106) -> Option<PlayerId> {
2107    if let Some(defined) = sa.ir.targeting_player_text.as_deref() {
2108        let candidates = crate::ability::ability_utils::resolve_defined_players_with_sa(
2109            defined,
2110            sa,
2111            sa.activating_player,
2112            game,
2113        );
2114        if candidates.is_empty() {
2115            return None;
2116        }
2117        return agents[sa.activating_player.index()].choose_target_player(
2118            sa.activating_player,
2119            &candidates,
2120            None,
2121        );
2122    }
2123    Some(sa.activating_player)
2124}
2125
2126// Re-export MagicStack and StackEntry from zone module (their canonical home,
2127// matching Java's `forge.game.zone.MagicStack`).
2128pub use crate::zone::magic_stack::{MagicStack, StackEntry};