Skip to main content

manabrew_engine/cost/
mod.rs

1pub mod cost_add_mana;
2pub mod cost_adjustment;
3pub mod cost_behold;
4pub mod cost_behold_exile;
5pub mod cost_blight;
6pub mod cost_choose_color;
7pub mod cost_choose_creature_type;
8pub mod cost_collect_evidence;
9pub mod cost_damage;
10pub mod cost_discard;
11pub mod cost_draw;
12pub mod cost_enlist;
13pub mod cost_exert;
14pub mod cost_exile;
15pub mod cost_exile_ctrl_or_grave;
16pub mod cost_exile_from_stack;
17pub mod cost_exiled_move_to_grave;
18pub mod cost_flip_coin;
19pub mod cost_forage;
20pub mod cost_gain_control;
21pub mod cost_gain_life;
22pub mod cost_mill;
23mod cost_parser;
24pub mod cost_part;
25pub mod cost_part_mana;
26pub mod cost_part_with_list;
27pub mod cost_part_with_trigger;
28pub mod cost_pay_energy;
29pub mod cost_pay_life;
30pub mod cost_pay_shards;
31pub mod cost_payment;
32pub mod cost_promise_gift;
33pub mod cost_put_card_to_lib;
34pub mod cost_put_counter;
35pub mod cost_remove_any_counter;
36pub mod cost_remove_counter;
37pub mod cost_return;
38pub mod cost_reveal;
39pub mod cost_reveal_chosen;
40pub mod cost_roll_dice;
41pub mod cost_sacrifice;
42pub mod cost_sub_counter;
43pub mod cost_tap;
44pub mod cost_tap_type;
45pub mod cost_unattach;
46pub mod cost_untap;
47pub mod cost_untap_type;
48pub mod cost_waterbend;
49pub mod individual_cost_payment_instance;
50pub mod payment_decision;
51pub mod selector_domain;
52pub mod trait_cost_decision_maker;
53pub mod trait_cost_visitor;
54
55use forge_foundation::{ManaCost, ZoneType};
56use serde::{Deserialize, Serialize};
57
58use crate::ability::effects::matches_change_type;
59use crate::card::CounterType;
60use crate::game::GameState;
61use crate::ids::{CardId, PlayerId};
62use crate::mana::ManaPool;
63use crate::parsing::CostTokenKind;
64use crate::spellability::SpellAbility;
65use crate::staticability::static_ability_cant_sacrifice::cant_sacrifice;
66
67/// Sentinel passed through [`resolve_dynamic_amount`] for the legacy `X`
68/// pathway. Kept for the few outer-API consumers (`GameLoop::pay_life_cost`,
69/// `AmountSpec::X.resolve`) that still receive an `i32`. New code should use
70/// `AmountSpec::X` directly.
71pub(crate) const DYNAMIC_X_SENTINEL: i32 = i32::MIN;
72
73pub fn resolve_dynamic_amount(
74    game: &GameState,
75    source: CardId,
76    player: PlayerId,
77    amount: i32,
78) -> i32 {
79    if amount != DYNAMIC_X_SENTINEL {
80        return amount;
81    }
82    let source_card = game.card(source);
83
84    if let Some(paid_x) = source_card
85        .svars
86        .get("XPaid")
87        .and_then(|s| s.parse::<i32>().ok())
88    {
89        return paid_x;
90    }
91
92    if let Some(x_expr) = source_card.get_s_var("X") {
93        if x_expr == "Count$xPaid" || x_expr == "Count$XPaid" {
94            return source_card
95                .svars
96                .get("XPaid")
97                .and_then(|s| s.parse::<i32>().ok())
98                .unwrap_or(0);
99        }
100        if let Ok(n) = x_expr.parse::<i32>() {
101            return n;
102        }
103        if x_expr.starts_with("Count$") {
104            return crate::ability::effects::resolve_count_svar(x_expr, game, source, player);
105        }
106    }
107
108    0
109}
110
111/// The amount slot of a [`CostPart`]. Replaces the legacy `i32` (with
112/// `DYNAMIC_X_SENTINEL`) once consumers are migrated. Mirrors Java's
113/// `CostPart.convertAmount` + `AbilityUtils.calculateAmount` split:
114/// literals resolve trivially, `X` reads `XPaid` / `SVar:X`, named SVar
115/// identifiers walk the host card's SVar table at call time.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub enum AmountSpec {
118    Literal(i32),
119    X,
120    /// SVar name on the host card (e.g. `Y` in `ExileFromHand<Y/Card.Blue>`
121    /// — the only legitimate source today is the `RaiseCost` SVar walker
122    /// in `cost_adjustment`). Reserved for explicit, audited parser sites.
123    Svar(String),
124}
125
126impl AmountSpec {
127    /// Parse a script amount token (`"3"`, `"X"`). Strips any trailing
128    /// `/extra` suffix so DSL forms like `Draw<1/You>` parse as `1`. Non-int,
129    /// non-X tokens fall back to `Literal(default)` — `Self::Svar` is reserved
130    /// for explicit parsers that want SVar-chain resolution (only
131    /// `cost_adjustment` today).
132    pub fn parse_or(raw: &str, default: i32) -> Self {
133        let head = raw.split('/').next().unwrap_or(raw).trim();
134        if head.is_empty() {
135            return Self::Literal(default);
136        }
137        if head.eq_ignore_ascii_case("X") {
138            Self::X
139        } else if let Ok(n) = head.parse::<i32>() {
140            Self::Literal(n)
141        } else {
142            Self::Literal(default)
143        }
144    }
145
146    /// Resolve to an `i32` at call time. `X` reads `XPaid`/`SVar:X` via the
147    /// legacy `resolve_dynamic_amount` flow; `Svar(name)` walks the host's
148    /// SVar chain to its first numeric value.
149    pub fn resolve(&self, game: &GameState, source: CardId, player: PlayerId) -> i32 {
150        match self {
151            Self::Literal(n) => *n,
152            Self::X => resolve_dynamic_amount(game, source, player, DYNAMIC_X_SENTINEL),
153            Self::Svar(name) => resolve_named_svar(game, source, player, name),
154        }
155    }
156
157    pub fn as_literal(&self) -> Option<i32> {
158        match self {
159            Self::Literal(n) => Some(*n),
160            _ => None,
161        }
162    }
163
164    pub fn is_x(&self) -> bool {
165        matches!(self, Self::X)
166    }
167}
168
169impl Default for AmountSpec {
170    fn default() -> Self {
171        Self::Literal(0)
172    }
173}
174
175impl From<i32> for AmountSpec {
176    fn from(n: i32) -> Self {
177        Self::Literal(n)
178    }
179}
180
181impl std::fmt::Display for AmountSpec {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        match self {
184            Self::Literal(n) => write!(f, "{n}"),
185            Self::X => f.write_str("X"),
186            Self::Svar(name) => f.write_str(name),
187        }
188    }
189}
190
191/// Walk a named SVar on the host card to its first numeric value.
192/// Used by `AmountSpec::Svar(name).resolve()` (and, transitively, by the
193/// `RaiseCost` parser once it routes through `AmountSpec`).
194fn resolve_named_svar(game: &GameState, source: CardId, player: PlayerId, name: &str) -> i32 {
195    let host = game.card(source);
196    let mut current = name.to_string();
197    for _ in 0..8 {
198        let Some(raw) = host.svars.get(&current) else {
199            return 0;
200        };
201        if let Some(rest) = raw.strip_prefix("SVar$") {
202            let next = rest.split('/').next().unwrap_or("").trim();
203            if next.is_empty() {
204                return 0;
205            }
206            current = next.to_string();
207            continue;
208        }
209        if let Some(num_str) = raw.strip_prefix("Number$") {
210            return num_str.trim().parse().unwrap_or(0);
211        }
212        if let Ok(n) = raw.trim().parse::<i32>() {
213            return n;
214        }
215        if raw.starts_with("Count$") {
216            return crate::ability::effects::resolve_count_svar(raw, game, source, player);
217        }
218        return 0;
219    }
220    0
221}
222
223/// A single component of an ability cost.
224/// Mirrors Java's CostPart hierarchy.
225#[derive(Debug, Clone, Serialize, Deserialize)]
226pub enum RevealFrom {
227    Hand,
228    Exile,
229    HandOrBattlefield,
230    All,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize)]
234pub enum CostPart {
235    /// Tap the source permanent. {T}
236    Tap,
237    /// Pay mana. Mirrors Java `CostPartMana`.
238    Mana {
239        cost: ManaCost,
240        /// Minimum value for X in the mana cost (parsed from restriction "XMin<N>").
241        #[serde(default)]
242        x_min: i32,
243        /// When true, the base mana cost is augmented by the exiled creature's mana cost.
244        #[serde(default)]
245        is_exiled_creature_cost: bool,
246        /// When true, the base mana cost is augmented by the enchanted creature's mana cost.
247        #[serde(default)]
248        is_enchanted_creature_cost: bool,
249        /// When true, the base mana cost is multiplied by an SVar-determined count.
250        #[serde(default)]
251        is_cost_pay_any_number_of_times: bool,
252        /// Maximum number of permanents that can be tapped to reduce the mana cost
253        /// via the Waterbend mechanic. Mirrors Java's `CostPartMana.maxWaterbend`.
254        #[serde(default)]
255        max_waterbend: Option<String>,
256    },
257    /// Pay life. Mirrors CostPayLife.
258    PayLife(AmountSpec),
259    /// Sacrifice permanents. type_filter "CARDNAME" means sacrifice self.
260    Sacrifice {
261        amount: AmountSpec,
262        type_filter: String,
263    },
264    /// Discard cards. type_filter "CARDNAME" means discard self.
265    Discard {
266        amount: AmountSpec,
267        type_filter: String,
268    },
269    /// Remove counters from a permanent (e.g. SubCounter<1/DREAM/NICKNAME>).
270    SubCounter {
271        amount: AmountSpec,
272        counter_type: CounterType,
273        type_filter: String,
274    },
275    /// Add counters to the source permanent (e.g. AddCounter<1/LOYALTY>). Mirrors CostPutCounter.
276    AddCounter {
277        amount: AmountSpec,
278        counter_type: CounterType,
279    },
280    /// Exile cards from a specific zone (own zone) as cost. Mirrors CostExile.
281    Exile {
282        amount: AmountSpec,
283        type_filter: String,
284        from: ZoneType,
285    },
286    /// Exile cards from any player's graveyard as cost (ExileAnyGrave). Mirrors CostExile zoneMode=-1.
287    ExileFromAnyGrave {
288        amount: AmountSpec,
289        type_filter: String,
290    },
291    /// Exile cards from the same graveyard as cost (ExileSameGrave). Mirrors CostExile zoneMode=0.
292    ExileFromSameGrave {
293        amount: AmountSpec,
294        type_filter: String,
295    },
296    /// Return permanents to owner's hand as cost. Mirrors CostReturn.
297    Return {
298        amount: AmountSpec,
299        type_filter: String,
300    },
301    /// Tap other permanents of a type as cost (tapXType<n/filter>). Mirrors CostTapType.
302    /// When `min_total_power` is Some(N), tap any number of creatures whose total power >= N
303    /// (used by Crew). When None, tap exactly `amount` matching permanents.
304    TapType {
305        amount: AmountSpec,
306        type_filter: String,
307        min_total_power: Option<i32>,
308    },
309    /// Untap permanents as cost. Mirrors CostUntap.
310    Untap,
311    /// Untap other permanents of a type as cost (untapYType<n/filter>). Mirrors CostUntapType.
312    UntapType {
313        amount: AmountSpec,
314        type_filter: String,
315        can_untap_source: bool,
316    },
317    /// Pay energy counters. Mirrors CostPayEnergy.
318    PayEnergy(AmountSpec),
319    /// Pay shard counters. Mirrors CostPayShards.
320    PayShards(AmountSpec),
321    /// Deal damage to the source's controller as cost. Mirrors CostDamage.
322    DamageYou(AmountSpec),
323    /// Draw cards as cost. Mirrors CostDraw.
324    Draw(AmountSpec),
325    /// Mill cards as cost. Mirrors CostMill.
326    Mill(AmountSpec),
327    /// Reveal cards as cost. Mirrors CostReveal.
328    Reveal {
329        amount: AmountSpec,
330        type_filter: String,
331        from: RevealFrom,
332    },
333    /// Exert permanent(s) as cost. Mirrors CostExert.
334    Exert {
335        amount: AmountSpec,
336        type_filter: String,
337    },
338    /// Opponent gains life as cost. Mirrors CostGainLife.
339    GainLife(AmountSpec),
340    /// Gain control of permanents matching type_filter as cost. Mirrors CostGainControl.
341    GainControl {
342        amount: AmountSpec,
343        type_filter: String,
344    },
345    /// Remove any counter type from permanents matching type_filter. Mirrors CostRemoveAnyCounter.
346    /// `counter_type` is None means any counter type.
347    RemoveAnyCounter {
348        amount: AmountSpec,
349        type_filter: String,
350        counter_type: Option<CounterType>,
351    },
352    /// Unattach equipment as a cost. Mirrors CostUnattach.
353    /// `type_filter` can be "CARDNAME" (source is the equipment), "OriginalHost",
354    /// or a card filter expression (source is the equipped creature, filter matches equipment).
355    Unattach {
356        type_filter: String,
357        description: Option<String>,
358    },
359    /// Move cards from exile to graveyard as cost. Mirrors CostExiledMoveToGrave.
360    ExiledMoveToGrave {
361        amount: AmountSpec,
362        type_filter: String,
363    },
364    /// Add mana to the pool as a cost (AddMana<amount/type>). Mirrors CostAddMana.
365    /// Always payable. Payment adds the specified mana to the activating player's pool.
366    AddMana {
367        amount: AmountSpec,
368        mana_type: String,
369    },
370    /// Waterbend cost (Waterbend<N>). Mirrors CostWaterbend.
371    /// Pay N generic mana, but you can tap your artifacts and creatures to help (each tapped = {1}).
372    Waterbend { amount: AmountSpec },
373    /// Choose one or more colors as a cost. Mirrors CostChooseColor.
374    ChooseColor(AmountSpec),
375    /// Choose a creature type as a cost. Mirrors CostChooseCreatureType.
376    ChooseCreatureType(AmountSpec),
377    /// Flip one or more coins as a cost. Mirrors CostFlipCoin.
378    FlipCoin(AmountSpec),
379    /// Roll dice as a cost. Mirrors CostRollDice.
380    RollDice {
381        amount: AmountSpec,
382        sides: i32,
383        result_svar: String,
384    },
385    /// Exile spells from stack as a cost. Mirrors CostExileFromStack.
386    ExileFromStack {
387        amount: AmountSpec,
388        type_filter: String,
389    },
390    /// Collect evidence N (exile cards from your graveyard with total MV >= N).
391    CollectEvidence(AmountSpec),
392    /// Forage: exile 3 from your graveyard or sacrifice a Food.
393    Forage,
394    /// Put card(s) to library from a zone as a cost. Mirrors CostPutCardToLib.
395    PutCardToLib {
396        amount: AmountSpec,
397        lib_pos: i32,
398        type_filter: String,
399        from: ZoneType,
400        same_zone: bool,
401    },
402    /// Enlist another creature as a cost. Mirrors CostEnlist.
403    Enlist {
404        amount: AmountSpec,
405        type_filter: String,
406    },
407    /// Promise gift to an opponent as a cost. Mirrors CostPromiseGift.
408    PromiseGift,
409    /// Reveal previously chosen player/type as a cost. Mirrors CostRevealChosen.
410    RevealChosen { reveal_type: String },
411    /// Behold (reveal from hand/battlefield), optionally exile revealed cards.
412    Behold {
413        amount: AmountSpec,
414        type_filter: String,
415        exile: bool,
416    },
417    /// Blight N = put N -1/-1 counters on creature(s) you control.
418    Blight(AmountSpec),
419    /// Exile from battlefield or graveyard as a combined cost (craft).
420    ExileCtrlOrGrave {
421        amount: AmountSpec,
422        type_filter: String,
423    },
424}
425
426impl CostPart {
427    /// Payment ordering — mirrors Java's CostPart.paymentOrder.
428    /// Lower numbers are paid first.
429    fn payment_order(&self) -> i32 {
430        match self {
431            CostPart::Tap => -1,
432            CostPart::Untap => 20,
433            CostPart::Mana {
434                is_exiled_creature_cost,
435                ..
436            } => {
437                if *is_exiled_creature_cost {
438                    200
439                } else {
440                    0
441                }
442            }
443            CostPart::PayEnergy(_) => 7,
444            CostPart::PayShards(_) => 7,
445            CostPart::SubCounter { .. } => 8,
446            CostPart::AddCounter { .. } => 6,
447            CostPart::PayLife(_) => 7,
448            CostPart::DamageYou(_) => 8,
449            CostPart::GainLife(_) => 5,
450            CostPart::Reveal { from, .. } => match from {
451                RevealFrom::Hand => 5,
452                RevealFrom::HandOrBattlefield => 5,
453                _ => -1,
454            },
455            CostPart::Draw(_) => 20,
456            CostPart::Mill(_) => 20,
457            CostPart::Discard { .. } => 10,
458            CostPart::Sacrifice { .. } => 15,
459            CostPart::Exile { from, .. } => {
460                if *from == ZoneType::Library {
461                    20
462                } else {
463                    15
464                }
465            }
466            CostPart::ExileFromAnyGrave { .. } => 15,
467            CostPart::ExileFromSameGrave { .. } => 15,
468            CostPart::Return { .. } => 10,
469            CostPart::TapType { .. } => 18,
470            CostPart::UntapType { .. } => 18,
471            CostPart::GainControl { .. } => 8,
472            CostPart::RemoveAnyCounter { .. } => 8,
473            CostPart::Unattach { .. } => 5,
474            CostPart::ExiledMoveToGrave { .. } => 15,
475            CostPart::AddMana { .. } => 5,
476            CostPart::Waterbend { .. } => 0,
477            CostPart::Exert { .. } => 5,
478            CostPart::ChooseColor(_) => 8,
479            CostPart::ChooseCreatureType(_) => 5,
480            CostPart::FlipCoin(_) => 22,
481            CostPart::RollDice { .. } => 5,
482            CostPart::ExileFromStack { .. } => 15,
483            CostPart::CollectEvidence(_) => 15,
484            CostPart::Forage => 5,
485            CostPart::PutCardToLib { .. } => 10,
486            CostPart::Enlist { .. } => 5,
487            CostPart::PromiseGift => -1,
488            CostPart::RevealChosen { .. } => 20,
489            CostPart::Behold { .. } => 5,
490            CostPart::Blight(_) => 6,
491            CostPart::ExileCtrlOrGrave { .. } => 15,
492        }
493    }
494}
495
496/// The complete cost to activate an ability.
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct Cost {
499    pub parts: Vec<CostPart>,
500    pub has_tap: bool,
501    pub mandatory: bool,
502}
503
504impl Cost {
505    pub fn has_tap_cost(&self) -> bool {
506        self.has_tap
507    }
508
509    pub fn has_no_mana_cost(&self) -> bool {
510        !self
511            .parts
512            .iter()
513            .any(|p| matches!(p, CostPart::Mana { .. }))
514    }
515
516    pub fn has_mana_cost(&self) -> bool {
517        !self.has_no_mana_cost()
518    }
519
520    pub fn has_specific_cost_type(&self, probe: &CostPart) -> bool {
521        let tag = std::mem::discriminant(probe);
522        self.parts.iter().any(|p| std::mem::discriminant(p) == tag)
523    }
524
525    pub fn has_only_specific_cost_type(&self, probe: &CostPart) -> bool {
526        let tag = std::mem::discriminant(probe);
527        self.parts.iter().all(|p| std::mem::discriminant(p) == tag)
528    }
529
530    pub fn sort(&mut self) {
531        self.parts.sort_by_key(|p| p.payment_order());
532    }
533
534    pub fn copy(&self) -> Self {
535        self.clone()
536    }
537
538    pub fn copy_with_no_mana(&self) -> Self {
539        let mut out = self.clone();
540        out.parts.retain(|p| !matches!(p, CostPart::Mana { .. }));
541        out
542    }
543
544    pub fn copy_with_defined_mana(&self, mana_cost: ManaCost) -> Self {
545        let mut out = self.clone();
546        out.parts.retain(|p| !matches!(p, CostPart::Mana { .. }));
547        out.parts.push(CostPart::Mana {
548            cost: mana_cost,
549            x_min: 0,
550            is_exiled_creature_cost: false,
551            is_enchanted_creature_cost: false,
552            is_cost_pay_any_number_of_times: false,
553            max_waterbend: None,
554        });
555        out.sort();
556        out
557    }
558
559    pub fn refund_paid_cost(&self, game: &mut GameState, source: CardId, player: PlayerId) {
560        for part in self.parts.iter().rev() {
561            crate::cost::cost_part::refund(game, source, player, part);
562        }
563    }
564
565    pub fn to_string_alt(&self) -> String {
566        to_simple_string(self)
567    }
568
569    pub fn to_simple_string(&self) -> String {
570        to_simple_string(self)
571    }
572
573    pub fn is_zero_cost(&self) -> bool {
574        self.parts.is_empty()
575            || (self.parts.len() == 1
576                && matches!(&self.parts[0], CostPart::Mana { cost: mana, .. } if mana.is_zero()))
577    }
578}
579
580pub fn convert_amount_type_to_words(amount: i32, amount_expr: &str, noun: &str) -> String {
581    if amount_expr == "X" {
582        format!("X {noun}")
583    } else if amount == 1 {
584        format!("a {noun}")
585    } else {
586        format!("{amount} {noun}s")
587    }
588}
589
590pub fn convert_int_and_type_to_words(amount: i32, noun: &str) -> String {
591    convert_amount_type_to_words(amount, &amount.to_string(), noun)
592}
593
594pub fn merge_to(dst: &mut Cost, src: &Cost) {
595    dst.parts.extend(src.parts.clone());
596    dst.has_tap = dst.has_tap || src.has_tap;
597    dst.mandatory = dst.mandatory || src.mandatory;
598    dst.sort();
599}
600
601pub fn add(cost: &mut Cost, part: CostPart) {
602    cost.has_tap = cost.has_tap || matches!(part, CostPart::Tap);
603    cost.parts.push(part);
604    cost.sort();
605}
606
607pub fn apply_text_change_effects(cost: &mut Cost, game: &GameState, host: CardId) {
608    for part in &mut cost.parts {
609        crate::cost::cost_part::apply_text_change_effects(part, game, host);
610    }
611}
612
613pub fn has_x_in_any_cost_part(cost: &Cost) -> bool {
614    cost.parts.iter().any(|p| match p {
615        CostPart::Mana { cost, .. } => cost.count_x() > 0,
616        _ => cost_part::convert_amount(p).is_some_and(AmountSpec::is_x),
617    })
618}
619
620pub fn get_max_for_non_mana_x(
621    cost: &Cost,
622    game: &GameState,
623    ability: &SpellAbility,
624    payer: PlayerId,
625    effect: bool,
626) -> Option<i32> {
627    let mut val: Option<i32> = None;
628    for p in &cost.parts {
629        if !cost_part::convert_amount(p).is_some_and(AmountSpec::is_x) {
630            continue;
631        }
632        let part_max = cost_part::get_max_amount_x(game, ability, payer, p, effect);
633        val = match (val, part_max) {
634            (Some(a), Some(b)) => Some(a.min(b)),
635            (a, b) => a.or(b),
636        };
637    }
638    if let Some(v) = val {
639        if v <= 0
640            && cost.has_mana_cost()
641            && cost.parts.iter().any(|p| cost_part_mana::get_x_min(p) > 0)
642        {
643            return None;
644        }
645    }
646    val
647}
648
649pub fn to_simple_string(cost: &Cost) -> String {
650    let mut out = Vec::new();
651    for part in &cost.parts {
652        match part {
653            CostPart::Tap => out.push("{T}".to_string()),
654            CostPart::Untap => out.push("{Q}".to_string()),
655            CostPart::Mana { cost, .. } => out.push(format!("{cost}")),
656            CostPart::PayLife(v) => out.push(format!("Pay {v} life")),
657            _ => out.push(format!("{part:?}")),
658        }
659    }
660    out.join(", ")
661}
662
663/// Cost rendered for a player-facing prompt. Life uses the `{LIFE}` token so the
664/// UI can draw a heart; mana keeps its `{...}` symbols.
665pub fn to_prompt_string(cost: &Cost) -> String {
666    let mut out = Vec::new();
667    for part in &cost.parts {
668        match part {
669            CostPart::Tap => out.push("{T}".to_string()),
670            CostPart::Untap => out.push("{Q}".to_string()),
671            CostPart::Mana { cost, .. } => out.push(format!("{cost}")),
672            CostPart::PayLife(v) => out.push(format!("{v} {{LIFE}}")),
673            _ => out.push(format!("{part:?}")),
674        }
675    }
676    out.join(", ")
677}
678
679/// Parse a Cost$ value from the DSL.
680///
681/// Examples:
682/// - `"T"` → tap
683/// - `"1 G"` → mana cost {1}{G}
684/// - `"T 1 G"` → tap + mana
685/// - `"Sac<1/CARDNAME>"` → sacrifice self
686/// - `"PayLife<3>"` → pay 3 life
687/// - `"Exile<1/Creature>"` → exile a creature from battlefield
688/// - `"ExileFromHand<1/Card>"` → exile from hand
689/// - `"Return<1/CARDNAME>"` → return self to hand
690/// - `"tapXType<1/Creature>"` → tap a creature
691/// - `"AddCounter<1/LOYALTY>"` → add a loyalty counter
692/// - `"SubCounter<1/LOYALTY/CARDNAME>"` → remove loyalty counter
693pub fn parse_cost(raw: &str) -> Cost {
694    let tokens = split_cost_tokens(raw);
695    let mut parts = Vec::new();
696    let mut has_tap = false;
697    let mut mandatory = false;
698    let mut mana_tokens: Vec<&str> = Vec::new();
699
700    // Pre-scan for untap cost (Q/Untap), mirroring Java's pre-scan for hasUntapInPrice.
701    let has_untap = tokens.iter().any(|token| {
702        CostTokenKind::parse(token).is_some_and(|parsed| parsed.kind == CostTokenKind::Untap)
703    });
704
705    for token in &tokens {
706        match cost_parser::parse_cost_token(token) {
707            cost_parser::TokenResult::Part(part) => parts.push(part),
708            cost_parser::TokenResult::Tap => {
709                parts.push(CostPart::Tap);
710                has_tap = true;
711            }
712            cost_parser::TokenResult::Mandatory => {
713                mandatory = true;
714            }
715            cost_parser::TokenResult::Mana => {
716                mana_tokens.push(token);
717            }
718        }
719    }
720
721    // Post-process: set can_untap_source on UntapType parts.
722    // Mirrors Java: canUntapSource = !hasUntapInPrice
723    for part in &mut parts {
724        if let CostPart::UntapType {
725            can_untap_source, ..
726        } = part
727        {
728            *can_untap_source = !has_untap;
729        }
730    }
731
732    // If we have mana tokens, combine them into a ManaCost
733    if !mana_tokens.is_empty() {
734        let mana_str = mana_tokens.join(" ");
735        let mana_cost = ManaCost::parse(&mana_str);
736        if mana_cost.cmc() > 0 || !mana_str.is_empty() {
737            parts.push(CostPart::Mana {
738                cost: mana_cost,
739                x_min: 0,
740                is_exiled_creature_cost: false,
741                is_enchanted_creature_cost: false,
742                is_cost_pay_any_number_of_times: false,
743                max_waterbend: None,
744            });
745        }
746    }
747
748    // Sort by payment order
749    parts.sort_by_key(|p| p.payment_order());
750
751    Cost {
752        parts,
753        has_tap,
754        mandatory,
755    }
756}
757
758/// Parse `"amount/filter"` inner content, returning (amount, filter).
759/// If there's no slash, defaults to amount=1 and filter=inner.
760pub(super) fn parse_amount_filter(inner: &str) -> (AmountSpec, String) {
761    if let Some(slash_idx) = inner.find('/') {
762        let amt = AmountSpec::parse_or(&inner[..slash_idx], 1);
763        let rest = &inner[slash_idx + 1..];
764        let filter = if let Some(desc_idx) = rest.find('/') {
765            rest[..desc_idx].to_string()
766        } else {
767            rest.to_string()
768        };
769        (amt, filter)
770    } else {
771        (AmountSpec::Literal(1), inner.to_string())
772    }
773}
774
775pub(super) fn parse_amount_filter_dynamic(inner: &str) -> (AmountSpec, String) {
776    if let Some(slash_idx) = inner.find('/') {
777        let amt = AmountSpec::parse_or(&inner[..slash_idx], 1);
778        let rest = &inner[slash_idx + 1..];
779        let filter = if let Some(desc_idx) = rest.find('/') {
780            rest[..desc_idx].to_string()
781        } else {
782            rest.to_string()
783        };
784        (amt, filter)
785    } else {
786        (AmountSpec::parse_or(inner, 1), inner.to_string())
787    }
788}
789
790/// Split cost string on spaces, keeping `<...>` groups together.
791fn split_cost_tokens(raw: &str) -> Vec<&str> {
792    let mut tokens = Vec::new();
793    let mut start = 0;
794    let mut depth = 0;
795    let bytes = raw.as_bytes();
796
797    let mut i = 0;
798    while i < bytes.len() {
799        match bytes[i] {
800            b'<' => depth += 1,
801            b'>' => {
802                if depth > 0 {
803                    depth -= 1;
804                }
805            }
806            b' ' if depth == 0 => {
807                let token = raw[start..i].trim();
808                if !token.is_empty() {
809                    tokens.push(token);
810                }
811                start = i + 1;
812            }
813            _ => {
814                // This is a character-parsing loop, not a semantic dispatch
815                // No warning needed here — we're just walking through characters
816            }
817        }
818        i += 1;
819    }
820    // Last token
821    let token = raw[start..].trim();
822    if !token.is_empty() {
823        tokens.push(token);
824    }
825    tokens
826}
827
828/// Check if a card matches a type filter string.
829/// Thin wrapper around `matches_change_type` for use by individual cost modules.
830pub fn matches_type_filter(game: &GameState, cid: CardId, type_filter: &str) -> bool {
831    matches_change_type(game.card(cid), type_filter, &[])
832}
833
834/// Find valid sacrifice targets on the battlefield for a player, filtered by type.
835/// Mirrors Java's `CostSacrifice.getMaxAmountX()` + `CardLists.getValidCards()`.
836pub fn get_sacrifice_targets(game: &GameState, player: PlayerId, type_filter: &str) -> Vec<CardId> {
837    game.cards_in_zone(ZoneType::Battlefield, player)
838        .to_vec()
839        .into_iter()
840        .filter(|&cid| matches_change_type(game.card(cid), type_filter, &[]))
841        .collect()
842}
843
844/// Find cards that can have counters removed for `SubCounter<.../Type/...>`.
845pub fn get_sub_counter_targets(
846    game: &GameState,
847    player: PlayerId,
848    source: CardId,
849    type_filter: &str,
850) -> Vec<CardId> {
851    if type_filter.eq_ignore_ascii_case("OriginalHost") {
852        return Vec::new();
853    }
854    let source_card = game.card(source);
855    game.cards_in_zone(ZoneType::Battlefield, player)
856        .to_vec()
857        .into_iter()
858        .filter(|&cid| {
859            if type_filter == "Card" || type_filter.is_empty() {
860                return true;
861            }
862            let selector = crate::parsing::cached_compiled_selector(type_filter);
863            crate::card::valid_filter::matches_valid_card_selector_in_game(
864                &selector,
865                game.card(cid),
866                source_card,
867                game,
868            )
869        })
870        .collect()
871}
872
873/// Find valid sacrifice targets for a cost, filtered both by type and
874/// CantSacrifice-style legality before RNG selection.
875pub fn get_sacrifice_targets_for_cost(
876    game: &GameState,
877    player: PlayerId,
878    type_filter: &str,
879    ability: Option<&SpellAbility>,
880) -> Vec<CardId> {
881    get_sacrifice_targets(game, player, type_filter)
882        .into_iter()
883        .filter(|&cid| !cant_sacrifice(&game.cards, game.card(cid), ability, true))
884        .collect()
885}
886
887/// Find valid exile/return targets in a given zone for a player, filtered by type.
888pub fn get_zone_targets(
889    game: &GameState,
890    player: PlayerId,
891    zone: ZoneType,
892    type_filter: &str,
893) -> Vec<CardId> {
894    game.cards_in_zone(zone, player)
895        .to_vec()
896        .into_iter()
897        .filter(|&cid| {
898            if type_filter == "Card" || type_filter.is_empty() {
899                true
900            } else {
901                matches_change_type(game.card(cid), type_filter, &[])
902            }
903        })
904        .collect()
905}
906
907/// Find cards in exile across all players matching a type filter.
908/// Used by ExiledMoveToGrave and can_pay checks.
909pub fn get_exiled_targets(game: &GameState, type_filter: &str) -> Vec<CardId> {
910    game.players
911        .iter()
912        .flat_map(|p| game.cards_in_zone(ZoneType::Exile, p.id).to_vec())
913        .filter(|&cid| {
914            type_filter == "Card"
915                || type_filter.is_empty()
916                || matches_change_type(game.card(cid), type_filter, &[])
917        })
918        .collect()
919}
920
921/// Find valid tap-type targets (untapped permanents matching filter, excluding source).
922pub fn get_tap_type_targets(
923    game: &GameState,
924    player: PlayerId,
925    type_filter: &str,
926    exclude: CardId,
927) -> Vec<CardId> {
928    game.cards_in_zone(ZoneType::Battlefield, player)
929        .to_vec()
930        .into_iter()
931        .filter(|&cid| {
932            if cid == exclude {
933                return false;
934            }
935            let card = game.card(cid);
936            if card.tapped {
937                return false;
938            }
939            if type_filter == "Card" || type_filter.is_empty() {
940                true
941            } else {
942                matches_change_type(card, type_filter, &[])
943            }
944        })
945        .collect()
946}
947
948/// Find cards available to enlist: untapped, non-attacking, non-summoning-sick creatures you control.
949pub fn get_enlist_targets(game: &GameState, player: PlayerId) -> Vec<CardId> {
950    game.cards_in_zone(ZoneType::Battlefield, player)
951        .to_vec()
952        .into_iter()
953        .filter(|&cid| {
954            let c = game.card(cid);
955            // Mirror Java CostEnlist.getCardsForEnlisting():
956            // c.canTap() && !c.isSick() && !c.isAttacking()
957            // where isSick() is false for creatures with haste.
958            c.is_creature()
959                && !c.tapped
960                && !c.phased_out
961                && (!c.summoning_sick || c.has_haste())
962                && c.attacking_player.is_none()
963        })
964        .collect()
965}
966
967pub fn matches_exile_from_stack_filter(
968    game: &GameState,
969    card_id: CardId,
970    source: CardId,
971    _player: PlayerId,
972    type_filter: &str,
973) -> bool {
974    if type_filter == "All" || type_filter.is_empty() {
975        return true;
976    }
977    let card = game.card(card_id);
978    let source_card = game.card(source);
979    for clause in type_filter.split(';') {
980        let clause = clause.trim();
981        if clause.is_empty() {
982            continue;
983        }
984        let normalized = normalize_stack_clause_for_valid_cards(clause);
985        let selector = crate::parsing::cached_compiled_selector(&normalized);
986        if crate::card::valid_filter::matches_valid_card_selector_in_game(
987            &selector,
988            card,
989            source_card,
990            game,
991        ) {
992            return true;
993        }
994    }
995    false
996}
997
998fn is_valid_cards_type_token(token: &str) -> bool {
999    matches!(
1000        token,
1001        "Card"
1002            | "Permanent"
1003            | "Creature"
1004            | "Land"
1005            | "Artifact"
1006            | "Enchantment"
1007            | "Planeswalker"
1008            | "Instant"
1009            | "Sorcery"
1010            | "Plains"
1011            | "Island"
1012            | "Swamp"
1013            | "Mountain"
1014            | "Forest"
1015    )
1016}
1017
1018fn normalize_stack_clause_for_valid_cards(clause: &str) -> String {
1019    let mut tokens: Vec<&str> = clause
1020        .split(['.', '+'])
1021        .map(str::trim)
1022        .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("Spell"))
1023        .collect();
1024
1025    if tokens.is_empty() {
1026        return "Card".to_string();
1027    }
1028
1029    let type_idx = tokens
1030        .iter()
1031        .position(|t| is_valid_cards_type_token(t))
1032        .unwrap_or(usize::MAX);
1033
1034    if type_idx == usize::MAX {
1035        let mut out = String::from("Card");
1036        for t in tokens.drain(..) {
1037            out.push('.');
1038            out.push_str(t);
1039        }
1040        return out;
1041    }
1042
1043    let type_part = tokens[type_idx].to_string();
1044    let mut qualifiers: Vec<&str> = Vec::with_capacity(tokens.len().saturating_sub(1));
1045    qualifiers.extend(tokens[..type_idx].iter().copied());
1046    qualifiers.extend(tokens[type_idx + 1..].iter().copied());
1047
1048    if qualifiers.is_empty() {
1049        type_part
1050    } else {
1051        format!("{}.{}", type_part, qualifiers.join("."))
1052    }
1053}
1054
1055pub fn strip_exile_type_modifiers(type_filter: &str) -> String {
1056    let mut t = type_filter.to_string();
1057    if t.contains("FromTopGrave") {
1058        t = t.replace("FromTopGrave", "");
1059    }
1060    if let Some((left, _)) = t.split_once("+withTotalCMCEQ") {
1061        t = left.to_string();
1062    }
1063    if let Some((left, _)) = t.split_once("+withTotalCMCGE") {
1064        t = left.to_string();
1065    }
1066    if t.contains("+withSharedCardType") {
1067        t = t.replace("+withSharedCardType", "");
1068    }
1069    if let Some((left, _)) = t.split_once("+withTypesGE") {
1070        t = left.to_string();
1071    }
1072    t
1073}
1074
1075pub fn normalize_exile_base_filter(type_filter: &str) -> String {
1076    let t = strip_exile_type_modifiers(type_filter);
1077    if t.is_empty() || t.eq_ignore_ascii_case("All") || t.contains('X') {
1078        "Card".to_string()
1079    } else {
1080        t
1081    }
1082}
1083
1084pub(crate) fn parse_exile_total_cmc_eq(type_filter: &str) -> Option<&str> {
1085    type_filter
1086        .split_once("+withTotalCMCEQ")
1087        .map(|(_, rhs)| rhs.trim())
1088}
1089
1090pub(crate) fn parse_exile_total_cmc_ge(type_filter: &str) -> Option<&str> {
1091    type_filter
1092        .split_once("+withTotalCMCGE")
1093        .map(|(_, rhs)| rhs.trim())
1094}
1095
1096pub(crate) fn parse_exile_types_ge(type_filter: &str) -> Option<i32> {
1097    type_filter
1098        .split_once("+withTypesGE")
1099        .and_then(|(_, rhs)| rhs.trim().parse::<i32>().ok())
1100}
1101
1102pub(crate) fn exile_requires_shared_card_type(type_filter: &str) -> bool {
1103    type_filter.contains("+withSharedCardType")
1104}
1105
1106pub(crate) fn reveal_candidates(
1107    game: &GameState,
1108    player: PlayerId,
1109    source: CardId,
1110    type_filter: &str,
1111    from: &RevealFrom,
1112) -> Vec<CardId> {
1113    let mut cards: Vec<CardId> = match from {
1114        RevealFrom::Hand => game.cards_in_zone(ZoneType::Hand, player).to_vec(),
1115        RevealFrom::Exile => game.cards_in_zone(ZoneType::Exile, player).to_vec(),
1116        RevealFrom::HandOrBattlefield => {
1117            let mut v = game.cards_in_zone(ZoneType::Hand, player).to_vec();
1118            v.extend(
1119                game.cards_in_zone(ZoneType::Battlefield, player)
1120                    .iter()
1121                    .copied(),
1122            );
1123            v
1124        }
1125        RevealFrom::All => {
1126            let mut v = game.cards_in_zone(ZoneType::Hand, player).to_vec();
1127            v.extend(
1128                game.cards_in_zone(ZoneType::Battlefield, player)
1129                    .iter()
1130                    .copied(),
1131            );
1132            v.extend(
1133                game.cards_in_zone(ZoneType::Graveyard, player)
1134                    .iter()
1135                    .copied(),
1136            );
1137            v.extend(
1138                game.cards_in_zone(ZoneType::Library, player)
1139                    .iter()
1140                    .copied(),
1141            );
1142            v.extend(game.cards_in_zone(ZoneType::Exile, player).iter().copied());
1143            v
1144        }
1145    };
1146
1147    // Spell costs can't pay reveal from the source card itself while in hand.
1148    if matches!(
1149        from,
1150        RevealFrom::Hand | RevealFrom::HandOrBattlefield | RevealFrom::All
1151    ) && game.card(source).zone == ZoneType::Hand
1152    {
1153        cards.retain(|&cid| cid != source);
1154    }
1155
1156    if type_filter == "Card" || type_filter.is_empty() || type_filter == "Hand" {
1157        return cards;
1158    }
1159
1160    cards
1161        .into_iter()
1162        .filter(|&cid| matches_change_type(game.card(cid), type_filter, &[]))
1163        .collect()
1164}
1165
1166/// Check if a cost can be paid by the given player for the given source card.
1167/// `available_mana` is the total mana available (pool + untapped sources).
1168pub fn can_pay(
1169    cost: &Cost,
1170    game: &GameState,
1171    available_mana: Option<&ManaPool>,
1172    source: CardId,
1173    player: PlayerId,
1174    ability: Option<&SpellAbility>,
1175) -> bool {
1176    let _perf_scope =
1177        crate::perf::ParamsLookupScopeGuard::enter(crate::perf::ParamsLookupScope::Cost);
1178    for part in &cost.parts {
1179        if !can_pay_part_distributed(part, game, available_mana, source, player, ability) {
1180            return false;
1181        }
1182    }
1183    true
1184}
1185
1186/// Java parity helper: canPay(cost, ability-context).
1187pub fn can_pay_with_ability(
1188    cost: &Cost,
1189    game: &GameState,
1190    available_mana: &ManaPool,
1191    source: CardId,
1192    player: PlayerId,
1193    ability: Option<&SpellAbility>,
1194) -> bool {
1195    can_pay(cost, game, Some(available_mana), source, player, ability)
1196}
1197
1198pub fn can_pay_with_ability_and_reserved(
1199    cost: &Cost,
1200    game: &GameState,
1201    available_mana: &ManaPool,
1202    source: CardId,
1203    player: PlayerId,
1204    ability: Option<&SpellAbility>,
1205    reserved_sacrifices: &[CardId],
1206) -> bool {
1207    for part in &cost.parts {
1208        match part {
1209            CostPart::Sacrifice {
1210                type_filter,
1211                amount,
1212            } => {
1213                if type_filter == "CARDNAME"
1214                    || type_filter == "NICKNAME"
1215                    || type_filter == "OriginalHost"
1216                {
1217                    if !cost_sacrifice::can_pay(game, available_mana, source, player, ability, part)
1218                    {
1219                        return false;
1220                    }
1221                    continue;
1222                }
1223
1224                let mut valid = get_sacrifice_targets_for_cost(game, player, type_filter, ability);
1225                valid.retain(|cid| !reserved_sacrifices.contains(cid));
1226                if type_filter.eq_ignore_ascii_case("All") {
1227                    if valid.is_empty() {
1228                        return false;
1229                    }
1230                } else if (valid.len() as i32) < amount.resolve(game, source, player) {
1231                    return false;
1232                }
1233            }
1234            _ => {
1235                if !can_pay_part_distributed(
1236                    part,
1237                    game,
1238                    Some(available_mana),
1239                    source,
1240                    player,
1241                    ability,
1242                ) {
1243                    return false;
1244                }
1245            }
1246        }
1247    }
1248    true
1249}
1250
1251/// Check if a cost can be paid ignoring mana requirements.
1252/// Used for mana ability availability checks (to avoid circular dependency).
1253pub fn can_pay_ignoring_mana(
1254    cost: &Cost,
1255    game: &GameState,
1256    source: CardId,
1257    player: PlayerId,
1258) -> bool {
1259    can_pay(cost, game, None, source, player, None)
1260}
1261
1262/// Check if a cost can be paid ignoring mana requirements while preserving
1263/// the full spell/ability context for non-mana legality checks.
1264///
1265/// This is needed for action-space generation paths that separately validate
1266/// mana production (for example when some permanents are reserved to be
1267/// sacrificed and therefore cannot also be tapped for mana), but still need
1268/// `ValidCause$ Activated` / `ValidCause$ Spell` statics such as Yasharn to
1269/// see the real ability being paid.
1270pub fn can_pay_ignoring_mana_with_ability(
1271    cost: &Cost,
1272    game: &GameState,
1273    source: CardId,
1274    player: PlayerId,
1275    ability: &SpellAbility,
1276) -> bool {
1277    can_pay(cost, game, None, source, player, Some(ability))
1278}
1279
1280/// Check if a cost can be paid ignoring mana requirements, for a spell.
1281/// Passes a minimal SpellAbility with `is_spell = true` so that CantSacrifice
1282/// checks (e.g. Yasharn) can properly evaluate `ValidCause$ Spell` restrictions.
1283pub fn can_pay_ignoring_mana_for_spell(
1284    cost: &Cost,
1285    game: &GameState,
1286    source: CardId,
1287    player: PlayerId,
1288) -> bool {
1289    let mut stub = SpellAbility::new_empty(Some(source), player);
1290    stub.is_spell = true;
1291    can_pay(cost, game, None, source, player, Some(&stub))
1292}
1293
1294fn can_pay_part_distributed(
1295    part: &CostPart,
1296    game: &GameState,
1297    available_mana: Option<&ManaPool>,
1298    source: CardId,
1299    player: PlayerId,
1300    ability: Option<&SpellAbility>,
1301) -> bool {
1302    let empty_pool = ManaPool::new();
1303    let pool = available_mana.unwrap_or(&empty_pool);
1304
1305    match part {
1306        CostPart::Tap => cost_tap::can_pay(game, pool, source, player, ability, part),
1307        CostPart::Untap => cost_untap::can_pay(game, pool, source, player, ability, part),
1308        CostPart::Mana { .. } => {
1309            available_mana.is_none()
1310                || cost_part_mana::can_pay(game, pool, source, player, ability, part)
1311        }
1312        CostPart::PayLife(_) => cost_pay_life::can_pay(game, pool, source, player, ability, part),
1313        CostPart::Sacrifice { .. } => {
1314            cost_sacrifice::can_pay(game, pool, source, player, ability, part)
1315        }
1316        CostPart::Discard { .. } => {
1317            cost_discard::can_pay(game, pool, source, player, ability, part)
1318        }
1319        CostPart::SubCounter { .. } => {
1320            cost_remove_counter::can_pay(game, pool, source, player, ability, part)
1321        }
1322        CostPart::AddCounter { .. } => {
1323            cost_put_counter::can_pay(game, pool, source, player, ability, part)
1324        }
1325        CostPart::Exile { .. }
1326        | CostPart::ExileFromAnyGrave { .. }
1327        | CostPart::ExileFromSameGrave { .. } => {
1328            cost_exile::can_pay(game, pool, source, player, ability, part)
1329        }
1330        CostPart::Return { .. } => cost_return::can_pay(game, pool, source, player, ability, part),
1331        CostPart::TapType { .. } => {
1332            cost_tap_type::can_pay(game, pool, source, player, ability, part)
1333        }
1334        CostPart::UntapType { .. } => {
1335            cost_untap_type::can_pay(game, pool, source, player, ability, part)
1336        }
1337        CostPart::PayEnergy(_) => {
1338            cost_pay_energy::can_pay(game, pool, source, player, ability, part)
1339        }
1340        CostPart::PayShards(_) => {
1341            cost_pay_shards::can_pay(game, pool, source, player, ability, part)
1342        }
1343        CostPart::DamageYou(_) => cost_damage::can_pay(game, pool, source, player, ability, part),
1344        CostPart::Draw(_) => cost_draw::can_pay(game, pool, source, player, ability, part),
1345        CostPart::Mill(_) => cost_mill::can_pay(game, pool, source, player, ability, part),
1346        CostPart::Reveal { .. } => cost_reveal::can_pay(game, pool, source, player, ability, part),
1347        CostPart::Exert { .. } => cost_exert::can_pay(game, pool, source, player, ability, part),
1348        CostPart::GainLife(_) => cost_gain_life::can_pay(game, pool, source, player, ability, part),
1349        CostPart::GainControl { .. } => {
1350            cost_gain_control::can_pay(game, pool, source, player, ability, part)
1351        }
1352        CostPart::RemoveAnyCounter { .. } => {
1353            cost_remove_any_counter::can_pay(game, pool, source, player, ability, part)
1354        }
1355        CostPart::Unattach { .. } => {
1356            cost_unattach::can_pay(game, pool, source, player, ability, part)
1357        }
1358        CostPart::ExiledMoveToGrave { .. } => {
1359            cost_exiled_move_to_grave::can_pay(game, pool, source, player, ability, part)
1360        }
1361        CostPart::AddMana { .. } => {
1362            cost_add_mana::can_pay(game, pool, source, player, ability, part)
1363        }
1364        CostPart::Waterbend { .. } => {
1365            cost_waterbend::can_pay(game, available_mana, source, player, part)
1366        }
1367        CostPart::ChooseColor(_) => {
1368            cost_choose_color::can_pay(game, pool, source, player, ability, part)
1369        }
1370        CostPart::ChooseCreatureType(_) => {
1371            cost_choose_creature_type::can_pay(game, pool, source, player, ability, part)
1372        }
1373        CostPart::FlipCoin(_) => cost_flip_coin::can_pay(game, pool, source, player, ability, part),
1374        CostPart::RollDice { .. } => {
1375            cost_roll_dice::can_pay(game, pool, source, player, ability, part)
1376        }
1377        CostPart::ExileFromStack { .. } => {
1378            cost_exile_from_stack::can_pay(game, pool, source, player, ability, part)
1379        }
1380        CostPart::CollectEvidence(_) => {
1381            cost_collect_evidence::can_pay(game, pool, source, player, ability, part)
1382        }
1383        CostPart::Forage => cost_forage::can_pay(game, pool, source, player, ability, part),
1384        CostPart::PutCardToLib { .. } => {
1385            cost_put_card_to_lib::can_pay(game, pool, source, player, ability, part)
1386        }
1387        CostPart::Enlist { .. } => cost_enlist::can_pay(game, pool, source, player, ability, part),
1388        CostPart::PromiseGift => {
1389            cost_promise_gift::can_pay(game, pool, source, player, ability, part)
1390        }
1391        CostPart::RevealChosen { .. } => {
1392            cost_reveal_chosen::can_pay(game, pool, source, player, ability, part)
1393        }
1394        CostPart::Behold { exile, .. } => {
1395            if *exile {
1396                cost_behold_exile::can_pay(game, pool, source, player, ability, part)
1397            } else {
1398                cost_behold::can_pay(game, pool, source, player, ability, part)
1399            }
1400        }
1401        CostPart::Blight(_) => cost_blight::can_pay(game, source, player, part),
1402        CostPart::ExileCtrlOrGrave { .. } => {
1403            cost_exile_ctrl_or_grave::can_pay(game, source, player, ability, part)
1404        }
1405    }
1406}
1407
1408pub(crate) fn shares_creature_type(game: &GameState, a: CardId, b: CardId) -> bool {
1409    let ca = game.card(a);
1410    let cb = game.card(b);
1411    ca.shares_creature_type_with(cb)
1412}
1413
1414pub(crate) fn shares_card_type(game: &GameState, a: CardId, b: CardId) -> bool {
1415    let ca = game.card(a);
1416    let cb = game.card(b);
1417    ca.type_line
1418        .core_types
1419        .iter()
1420        .any(|t| cb.type_line.core_types.contains(t))
1421}
1422
1423pub(crate) fn cmc_can_sum_to(target: i32, values: &[i32]) -> bool {
1424    if target < 0 {
1425        return false;
1426    }
1427    let mut reachable: std::collections::BTreeSet<i32> = std::collections::BTreeSet::new();
1428    reachable.insert(0);
1429    for &v in values {
1430        if v < 0 {
1431            continue;
1432        }
1433        let mut next = reachable.clone();
1434        for &r in &reachable {
1435            let nv = r + v;
1436            if nv <= target {
1437                next.insert(nv);
1438            }
1439        }
1440        reachable = next;
1441        if reachable.contains(&target) {
1442            return true;
1443        }
1444    }
1445    reachable.contains(&target)
1446}
1447
1448#[cfg(test)]
1449mod tests {
1450    use super::*;
1451
1452    #[test]
1453    fn parse_tap_only() {
1454        let cost = parse_cost("T");
1455        assert!(cost.has_tap);
1456        assert_eq!(cost.parts.len(), 1);
1457        assert!(matches!(cost.parts[0], CostPart::Tap));
1458    }
1459
1460    #[test]
1461    fn parse_mana_only() {
1462        let cost = parse_cost("1 G");
1463        assert!(!cost.has_tap);
1464        assert_eq!(cost.parts.len(), 1);
1465        match &cost.parts[0] {
1466            CostPart::Mana { cost: mc, .. } => assert_eq!(mc.cmc(), 2),
1467            _ => panic!("expected Mana cost part"),
1468        }
1469    }
1470
1471    #[test]
1472    fn parse_tap_and_mana() {
1473        let cost = parse_cost("T 1 G");
1474        assert!(cost.has_tap);
1475        assert_eq!(cost.parts.len(), 2);
1476        // Tap should come first (payment_order = -1)
1477        assert!(matches!(cost.parts[0], CostPart::Tap));
1478        assert!(matches!(cost.parts[1], CostPart::Mana { .. }));
1479    }
1480
1481    #[test]
1482    fn parse_sacrifice() {
1483        let cost = parse_cost("Sac<1/CARDNAME>");
1484        assert_eq!(cost.parts.len(), 1);
1485        match &cost.parts[0] {
1486            CostPart::Sacrifice {
1487                amount,
1488                type_filter,
1489            } => {
1490                assert_eq!(amount.as_literal(), Some(1));
1491                assert_eq!(type_filter, "CARDNAME");
1492            }
1493            _ => panic!("expected Sacrifice cost part"),
1494        }
1495    }
1496
1497    #[test]
1498    fn parse_pay_life() {
1499        let cost = parse_cost("PayLife<3>");
1500        assert_eq!(cost.parts.len(), 1);
1501        match &cost.parts[0] {
1502            CostPart::PayLife(n) => assert_eq!(n.as_literal(), Some(3)),
1503            _ => panic!("expected PayLife cost part"),
1504        }
1505    }
1506
1507    #[test]
1508    fn parse_compound_cost() {
1509        let cost = parse_cost("T Sac<1/CARDNAME>");
1510        assert!(cost.has_tap);
1511        assert_eq!(cost.parts.len(), 2);
1512        // Tap first (order -1), then sacrifice (order 15)
1513        assert!(matches!(cost.parts[0], CostPart::Tap));
1514        assert!(matches!(cost.parts[1], CostPart::Sacrifice { .. }));
1515    }
1516
1517    #[test]
1518    fn parse_sacrifice_creature() {
1519        let cost = parse_cost("B Sac<1/Creature>");
1520        assert_eq!(cost.parts.len(), 2);
1521        // Mana (order 0) before Sacrifice (order 15)
1522        assert!(matches!(cost.parts[0], CostPart::Mana { .. }));
1523        match &cost.parts[1] {
1524            CostPart::Sacrifice {
1525                amount,
1526                type_filter,
1527            } => {
1528                assert_eq!(amount.as_literal(), Some(1));
1529                assert_eq!(type_filter, "Creature");
1530            }
1531            _ => panic!("expected Sacrifice cost part"),
1532        }
1533    }
1534
1535    #[test]
1536    fn payment_order_sorting() {
1537        // PayLife, Tap, Mana, Sacrifice — should sort to: Tap, Mana, PayLife, Sacrifice
1538        let cost = parse_cost("PayLife<2> T 1 G Sac<1/CARDNAME>");
1539        assert_eq!(cost.parts.len(), 4);
1540        assert!(matches!(cost.parts[0], CostPart::Tap));
1541        assert!(matches!(cost.parts[1], CostPart::Mana { .. }));
1542        assert!(matches!(cost.parts[2], CostPart::PayLife(_)));
1543        assert!(matches!(cost.parts[3], CostPart::Sacrifice { .. }));
1544    }
1545
1546    #[test]
1547    fn parse_exile_from_hand() {
1548        let cost = parse_cost("ExileFromHand<1/Card>");
1549        assert_eq!(cost.parts.len(), 1);
1550        match &cost.parts[0] {
1551            CostPart::Exile {
1552                amount,
1553                type_filter,
1554                from,
1555            } => {
1556                assert_eq!(amount.as_literal(), Some(1));
1557                assert_eq!(type_filter, "Card");
1558                assert_eq!(*from, ZoneType::Hand);
1559            }
1560            _ => panic!("expected Exile cost part"),
1561        }
1562    }
1563
1564    #[test]
1565    fn parse_add_counter() {
1566        let cost = parse_cost("AddCounter<1/LOYALTY>");
1567        assert_eq!(cost.parts.len(), 1);
1568        match &cost.parts[0] {
1569            CostPart::AddCounter {
1570                amount,
1571                counter_type,
1572            } => {
1573                assert_eq!(amount.as_literal(), Some(1));
1574                assert_eq!(*counter_type, CounterType::Loyalty);
1575            }
1576            _ => panic!("expected AddCounter cost part"),
1577        }
1578    }
1579
1580    #[test]
1581    fn parse_return() {
1582        let cost = parse_cost("Return<1/CARDNAME>");
1583        assert_eq!(cost.parts.len(), 1);
1584        match &cost.parts[0] {
1585            CostPart::Return {
1586                amount,
1587                type_filter,
1588            } => {
1589                assert_eq!(amount.as_literal(), Some(1));
1590                assert_eq!(type_filter, "CARDNAME");
1591            }
1592            _ => panic!("expected Return cost part"),
1593        }
1594    }
1595
1596    #[test]
1597    fn parse_tap_type() {
1598        let cost = parse_cost("tapXType<2/Creature>");
1599        assert_eq!(cost.parts.len(), 1);
1600        match &cost.parts[0] {
1601            CostPart::TapType {
1602                amount,
1603                type_filter,
1604                min_total_power,
1605            } => {
1606                assert_eq!(amount.as_literal(), Some(2));
1607                assert_eq!(type_filter, "Creature");
1608                assert_eq!(*min_total_power, None);
1609            }
1610            _ => panic!("expected TapType cost part"),
1611        }
1612    }
1613
1614    #[test]
1615    fn parse_tap_type_with_total_power() {
1616        let cost = parse_cost("tapXType<Any/Creature.Other+withTotalPowerGE{3}>");
1617        assert_eq!(cost.parts.len(), 1);
1618        match &cost.parts[0] {
1619            CostPart::TapType {
1620                amount,
1621                type_filter,
1622                min_total_power,
1623            } => {
1624                assert_eq!(amount.as_literal(), Some(1)); // "Any" defaults to 1
1625                assert_eq!(type_filter, "Creature.Other");
1626                assert_eq!(*min_total_power, Some(3));
1627            }
1628            _ => panic!("expected TapType cost part"),
1629        }
1630    }
1631
1632    #[test]
1633    fn parse_pay_energy() {
1634        let cost = parse_cost("PayEnergy<3>");
1635        assert_eq!(cost.parts.len(), 1);
1636        match &cost.parts[0] {
1637            CostPart::PayEnergy(n) => assert_eq!(n.as_literal(), Some(3)),
1638            _ => panic!("expected PayEnergy cost part"),
1639        }
1640    }
1641
1642    #[test]
1643    fn parse_explicit_mana_token() {
1644        let cost = parse_cost("Mana<2 G>");
1645        assert_eq!(cost.parts.len(), 1);
1646        assert!(matches!(cost.parts[0], CostPart::Mana { .. }));
1647    }
1648
1649    #[test]
1650    fn parse_collect_evidence() {
1651        let cost = parse_cost("CollectEvidence<6>");
1652        assert_eq!(cost.parts.len(), 1);
1653        assert!(
1654            matches!(&cost.parts[0], CostPart::CollectEvidence(n) if n.as_literal() == Some(6))
1655        );
1656    }
1657
1658    #[test]
1659    fn parse_forage() {
1660        let cost = parse_cost("Forage");
1661        assert_eq!(cost.parts.len(), 1);
1662        assert!(matches!(cost.parts[0], CostPart::Forage));
1663    }
1664
1665    #[test]
1666    fn parse_put_card_to_lib_from_grave() {
1667        let cost = parse_cost("PutCardToLibFromGrave<1/0/Card>");
1668        assert_eq!(cost.parts.len(), 1);
1669        match &cost.parts[0] {
1670            CostPart::PutCardToLib {
1671                amount,
1672                lib_pos,
1673                type_filter,
1674                from,
1675                same_zone,
1676            } => {
1677                assert_eq!(amount.as_literal(), Some(1));
1678                assert_eq!(*lib_pos, 0);
1679                assert_eq!(type_filter, "Card");
1680                assert_eq!(*from, ZoneType::Graveyard);
1681                assert!(!same_zone);
1682            }
1683            _ => panic!("expected PutCardToLib cost part"),
1684        }
1685    }
1686
1687    #[test]
1688    fn parse_exile_from_stack() {
1689        let cost = parse_cost("ExileFromStack<1/Spell>");
1690        assert_eq!(cost.parts.len(), 1);
1691        match &cost.parts[0] {
1692            CostPart::ExileFromStack {
1693                amount,
1694                type_filter,
1695            } => {
1696                assert_eq!(amount.as_literal(), Some(1));
1697                assert_eq!(type_filter, "Spell");
1698            }
1699            _ => panic!("expected ExileFromStack cost part"),
1700        }
1701    }
1702
1703    #[test]
1704    fn parse_exile_ctrl_or_grave() {
1705        let cost = parse_cost("ExileCtrlOrGrave<2/Artifact>");
1706        assert_eq!(cost.parts.len(), 1);
1707        match &cost.parts[0] {
1708            CostPart::ExileCtrlOrGrave {
1709                amount,
1710                type_filter,
1711            } => {
1712                assert_eq!(amount.as_literal(), Some(2));
1713                assert_eq!(type_filter, "Artifact");
1714            }
1715            _ => panic!("expected ExileCtrlOrGrave cost part"),
1716        }
1717    }
1718}