Skip to main content

manabrew_engine/card/
keyword_gen.rs

1//! Keyword-based ability and trigger generation for Card.
2//!
3//! These functions translate keywords like "Cycling", "Prowess", "Bushido", etc. into
4//! concrete activated abilities and triggered abilities. They're called during card
5//! initialization in `Card::from_rules()`.
6
7use crate::ability::activated::parse_activated_ability;
8use crate::card::svar_cache::ParsedSVarKind;
9use crate::parsing::keys;
10use crate::parsing::Params;
11use crate::staticability::parse_static_ability;
12use crate::trigger::parse_trigger;
13
14use super::Card;
15
16fn roman_chapter(mut chapter: usize) -> String {
17    let mut result = String::new();
18    for (value, numeral) in [
19        (1000, "M"),
20        (900, "CM"),
21        (500, "D"),
22        (400, "CD"),
23        (100, "C"),
24        (90, "XC"),
25        (50, "L"),
26        (40, "XL"),
27        (10, "X"),
28        (9, "IX"),
29        (5, "V"),
30        (4, "IV"),
31        (1, "I"),
32    ] {
33        while chapter >= value {
34            result.push_str(numeral);
35            chapter -= value;
36        }
37    }
38    result
39}
40
41impl Card {
42    fn parsed_svar_params(&mut self, name: &str) -> Option<Params> {
43        match self.parsed_s_var(name)?.kind {
44            ParsedSVarKind::Ability { params, .. } | ParsedSVarKind::ParamRecord { params } => {
45                Some(params)
46            }
47            ParsedSVarKind::Number { .. }
48            | ParsedSVarKind::Count { .. }
49            | ParsedSVarKind::NumericExpression { .. }
50            | ParsedSVarKind::Raw { .. } => None,
51        }
52    }
53
54    /// Generate intrinsic mana abilities for basic land subtypes (Plains → {W}, etc.).
55    /// Mirrors Java's `CardFactoryUtil.addIntrinsicAbilities()`.
56    pub(crate) fn generate_basic_land_mana_abilities(&mut self) {
57        const SUBTYPE_MANA: &[(&str, &str, &str)] = &[
58            ("Plains", "W", "Add {W}."),
59            ("Island", "U", "Add {U}."),
60            ("Swamp", "B", "Add {B}."),
61            ("Mountain", "R", "Add {R}."),
62            ("Forest", "G", "Add {G}."),
63        ];
64        for &(subtype, letter, desc) in SUBTYPE_MANA {
65            if self.type_line.has_subtype(subtype) {
66                let already_produces = self.activated_abilities.iter().any(|ab| {
67                    ab.is_mana_ability
68                        && ab
69                            .produced_ir
70                            .as_ref()
71                            .is_some_and(|ir| ir.as_script_text() == letter)
72                });
73                if !already_produces {
74                    let raw = format!(
75                        "AB$ Mana | Cost$ T | Produced$ {letter} | SpellDescription$ {desc}"
76                    );
77                    let idx = self.abilities.len();
78                    self.abilities.push(raw.clone());
79                    if let Some(ab) = parse_activated_ability(&raw, idx) {
80                        self.activated_abilities.push(ab);
81                    }
82                }
83            }
84        }
85    }
86
87    /// Generate activated abilities from keywords (e.g. Cycling → AB$ Draw).
88    /// Mirrors Java's `CardFactoryUtil.setupKeywordedAbilities()`.
89    pub(super) fn generate_keyword_abilities(&mut self) {
90        // Cycling: K:Cycling:{cost} → AB$ Draw | Cost$ {cost} Discard<1/CARDNAME> | ActivationZone$ Hand
91        if let Some(cycling_cost) = self.get_keyword_cost("Cycling") {
92            let ab_text = format!(
93                "AB$ Draw | Cost$ {cycling_cost} Discard<1/CARDNAME> | ActivationZone$ Hand | NumCards$ 1 | Defined$ You"
94            );
95            let next_idx = self.activated_abilities.len();
96            if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
97                self.activated_abilities.push(ab);
98            }
99        }
100
101        // TypeCycling: K:TypeCycling:{type}:{cost} → AB$ ChangeZone | Cost$ {cost} Discard<1/CARDNAME> | ActivationZone$ Hand
102        // Mirrors Java CardFactoryUtil lines 3852-3864.
103        for kw in self
104            .keywords
105            .iter_strings()
106            .chain(self.granted_keywords.iter_strings())
107        {
108            if let Some(rest) = kw.strip_prefix("TypeCycling:") {
109                let parts: Vec<&str> = rest.splitn(2, ':').collect();
110                if parts.len() == 2 {
111                    let cycle_type = parts[0].trim(); // e.g., "Swamp"
112                    let mana_cost = parts[1].trim(); // e.g., "1"
113                                                     // getTitleWithoutCost() = capitalize(descType) + "cycling"
114                    let precost_desc = format!(
115                        "{}cycling",
116                        cycle_type
117                            .chars()
118                            .next()
119                            .map(|c| c.to_uppercase().to_string())
120                            .unwrap_or_default()
121                            + &cycle_type[1..]
122                    );
123                    let ab_text = format!(
124                        "AB$ ChangeZone | Cost$ {mana_cost} Discard<1/CARDNAME> | ActivationZone$ Hand | PrecostDesc$ {precost_desc} | Origin$ Library | Destination$ Hand | ChangeType$ {cycle_type}"
125                    );
126                    let next_idx = self.activated_abilities.len();
127                    if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
128                        self.activated_abilities.push(ab);
129                    }
130                }
131            }
132        }
133
134        // Equip: K:Equip:{cost}[...]
135        // Forge keyword payload can include optional suffix data; we only need
136        // the activation cost + default target filter to mirror Java baseline.
137        for equip_raw in self
138            .keywords
139            .iter_strings()
140            .chain(self.granted_keywords.iter_strings())
141            .filter_map(|kw| crate::keyword::extract_keyword_cost_str(kw, "Equip"))
142        {
143            let payload = equip_raw.split(":::").next().unwrap_or(equip_raw).trim();
144            let mut parts = payload.split(':');
145            let equip_cost = parts.next().unwrap_or(payload).trim();
146            let target_filter = parts
147                .next()
148                .map(str::trim)
149                .filter(|s| !s.is_empty())
150                .unwrap_or("Creature.YouCtrl");
151            if !equip_cost.is_empty() {
152                let ab_text = format!(
153                    "AB$ Attach | Cost$ {equip_cost} | ValidTgts$ {target_filter} | SorcerySpeed$ True | SpellDescription$ Equip {equip_cost}"
154                );
155                let next_idx = self.activated_abilities.len();
156                if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
157                    self.activated_abilities.push(ab);
158                }
159            }
160        }
161
162        // Crew: K:Crew:N → AB$ Animate (tap creatures with total power ≥N).
163        // Mirrors Java CardFactoryUtil lines 3820-3835.
164        // Uses tapXType<Any/Creature.Other+withTotalPowerGE{N}> matching Java's format.
165        for kw in self
166            .keywords
167            .iter_strings()
168            .chain(self.granted_keywords.iter_strings())
169        {
170            if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Crew") {
171                let n = n_str.trim();
172                let ab_text = format!(
173                    "AB$ Animate | Cost$ tapXType<Any/Creature.Other+withTotalPowerGE{{{n}}}> | Defined$ Self | Types$ Artifact,Creature | Secondary$ True | SpellDescription$ Crew {n}"
174                );
175                let next_idx = self.activated_abilities.len();
176                if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
177                    self.activated_abilities.push(ab);
178                }
179            }
180        }
181
182        // Station: K:Station:N → AB$ PutCounter (tap another creature to add charge counters).
183        // Mirrors Java CardFactoryUtil lines 3587-3595.
184        // The ability is sorcery-speed and puts charge counters equal to the tapped
185        // creature's power onto this Spacecraft/Planet.
186        for kw in self
187            .keywords
188            .iter_strings()
189            .chain(self.granted_keywords.iter_strings())
190        {
191            if let Some(_n_str) = crate::keyword::extract_keyword_cost_str(kw, "Station") {
192                let ab_text = "AB$ PutCounter | Cost$ tapXType<1/Creature.Other> | Defined$ Self | CounterType$ CHARGE | CounterNum$ StationX | SorcerySpeed$ True | CostDesc$ | SpellDescription$ Station";
193                let next_idx = self.activated_abilities.len();
194                if let Some(ab) = parse_activated_ability(ab_text, next_idx) {
195                    self.activated_abilities.push(ab);
196                }
197                self.svars
198                    .entry("StationX".to_string())
199                    .or_insert_with(|| "TappedCards$TapPowerValue".to_string());
200            }
201        }
202
203        // Embalm: K:Embalm:cost → AB$ CopyPermanent from graveyard.
204        // Mirrors Java CardFactoryUtil lines 2879-2891.
205        for kw in self
206            .keywords
207            .iter_strings()
208            .chain(self.granted_keywords.iter_strings())
209        {
210            if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Embalm") {
211                let cost = cost_str.trim();
212                let ab_text = format!(
213                    "AB$ CopyPermanent | Cost$ {cost} ExileFromGrave<1/CARDNAME> | ActivationZone$ Graveyard | SorcerySpeed$ True | Defined$ Self | SetColor$ White | AddTypes$ Zombie | SpellDescription$ Embalm"
214                );
215                let next_idx = self.activated_abilities.len();
216                if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
217                    self.activated_abilities.push(ab);
218                }
219            }
220        }
221
222        // Eternalize: K:Eternalize:cost → AB$ CopyPermanent from graveyard as 4/4.
223        // Mirrors Java CardFactoryUtil lines 3023-3052.
224        for kw in self
225            .keywords
226            .iter_strings()
227            .chain(self.granted_keywords.iter_strings())
228        {
229            if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Eternalize") {
230                let cost = cost_str.trim();
231                let ab_text = format!(
232                    "AB$ CopyPermanent | Cost$ {cost} ExileFromGrave<1/CARDNAME> | ActivationZone$ Graveyard | SorcerySpeed$ True | Defined$ Self | SetColor$ Black | SetPower$ 4 | SetToughness$ 4 | AddTypes$ Zombie | SpellDescription$ Eternalize"
233                );
234                let next_idx = self.activated_abilities.len();
235                if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
236                    self.activated_abilities.push(ab);
237                }
238            }
239        }
240
241        // Enlist: K:Enlist -> intrinsic optional attack cost static ability.
242        if self
243            .keywords
244            .iter_strings()
245            .chain(self.granted_keywords.iter_strings())
246            .any(|k| k.eq_ignore_ascii_case("Enlist"))
247        {
248            let raw = "S:Mode$ OptionalAttackCost | ValidCard$ Card.Self | Cost$ Enlist<1/CARDNAME/creature> | Secondary$ True | Trigger$ TrigEnlist";
249            if let Some(sa) = parse_static_ability(raw) {
250                self.add_static_ability(sa);
251            }
252            self.svars.entry("TrigEnlist".to_string()).or_insert_with(|| {
253                "DB$ Pump | NumAtt$ TriggerRemembered$CardPower | SpellDescription$ When you do, add its power to this creature's until end of turn.".to_string()
254            });
255        }
256
257        // Morph / Megamorph: mark card as castable face-down for {3}.
258        // The actual casting logic is in game_action_util (playable check + cost handling).
259        if self
260            .keywords
261            .iter_strings()
262            .chain(self.granted_keywords.iter_strings())
263            .any(|k| k.starts_with("Morph:") || k.starts_with("Megamorph:"))
264        {
265            self.has_morph = true;
266        }
267
268        // Plot: K:Plot:{cost} → AB$ Plot | Cost$ {cost} | ActivationZone$ Hand | SorcerySpeed$ True
269        // Mirrors Java CardFactoryUtil lines 3398-3449.
270        // Exiles the card from hand; plotted cards can later be cast for free.
271        if let Some(plot_cost) = self.get_keyword_cost("Plot") {
272            let ab_text = format!(
273                "AB$ Plot | Cost$ {plot_cost} | ActivationZone$ Hand | SorcerySpeed$ True | Secondary$ True | SpellDescription$ Plot"
274            );
275            let next_idx = self.activated_abilities.len();
276            if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
277                self.activated_abilities.push(ab);
278            }
279        }
280
281        // Class: K:Class:{level}:{cost}:{params} → AB$ ClassLevelUp.
282        // Mirrors Java CardFactoryUtil lines 2789-2799.
283        let class_keywords: Vec<String> = self
284            .keywords
285            .iter_strings()
286            .chain(self.granted_keywords.iter_strings())
287            .filter(|kw| kw.starts_with("Class:"))
288            .map(|kw| kw.to_string())
289            .collect();
290        for kw in class_keywords {
291            if let Some(rest) = kw.strip_prefix("Class:") {
292                let mut parts = rest.splitn(3, ':');
293                let level = parts.next().unwrap_or_default().trim();
294                let cost = parts.next().unwrap_or_default().trim();
295                let params = parts.next().unwrap_or_default().trim();
296
297                let Ok(level_num) = level.parse::<i32>() else {
298                    continue;
299                };
300                if cost.is_empty() {
301                    continue;
302                }
303
304                let ab_text = format!(
305                    "AB$ ClassLevelUp | Cost$ {} | ClassLevel$ EQ{} | SorcerySpeed$ True | StackDescription$ SpellDescription | SpellDescription$ Level {}",
306                    cost,
307                    level_num - 1,
308                    level_num
309                );
310                let next_idx = self.activated_abilities.len();
311                if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
312                    self.activated_abilities.push(ab);
313                }
314
315                if !params.is_empty() {
316                    let parsed = Params::from_raw(params);
317                    let mut desc_parts: Vec<String> = Vec::new();
318
319                    if let Some(add_trigger) = parsed.get("AddTrigger") {
320                        for svar_name in add_trigger
321                            .split(" & ")
322                            .map(str::trim)
323                            .filter(|s| !s.is_empty())
324                        {
325                            if let Some(svar_params) = self.parsed_svar_params(svar_name) {
326                                if let Some(desc) = svar_params.get(keys::TRIGGER_DESCRIPTION) {
327                                    desc_parts.push(desc.to_string());
328                                }
329                            }
330                        }
331                    }
332
333                    if let Some(add_static) = parsed.get("AddStaticAbility") {
334                        for svar_name in add_static
335                            .split(" & ")
336                            .map(str::trim)
337                            .filter(|s| !s.is_empty())
338                        {
339                            if let Some(svar_params) = self.parsed_svar_params(svar_name) {
340                                if let Some(desc) = svar_params.get(keys::DESCRIPTION) {
341                                    desc_parts.push(desc.to_string());
342                                }
343                            }
344                        }
345                    }
346
347                    if let Some(add_replacement) = parsed.get("AddReplacementEffect") {
348                        for svar_name in add_replacement
349                            .split(" & ")
350                            .map(str::trim)
351                            .filter(|s| !s.is_empty())
352                        {
353                            if let Some(svar_params) = self.parsed_svar_params(svar_name) {
354                                if let Some(desc) = svar_params.get(keys::DESCRIPTION) {
355                                    desc_parts.push(desc.to_string());
356                                }
357                            }
358                        }
359                    }
360
361                    let mut effect = format!(
362                        "Mode$ Continuous | Affected$ Card.Self | ClassLevel$ {level_num} | {params}"
363                    );
364                    if !desc_parts.is_empty() {
365                        effect.push_str(" | Description$ ");
366                        effect.push_str(&desc_parts.join("\r\n"));
367                    }
368                    if let Some(st) = parse_static_ability(&effect) {
369                        self.add_static_ability(st);
370                    }
371                }
372            }
373        }
374    }
375
376    pub fn ensure_crew_activated_ability(&mut self) {
377        if self.activated_abilities.iter().any(|ab| {
378            ab.spell_description
379                .as_deref()
380                .is_some_and(|desc| desc.starts_with("Crew"))
381        }) {
382            return;
383        }
384        for kw in self.keywords.iter_strings() {
385            if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Crew") {
386                let n = n_str.trim();
387                let ab_text = format!(
388                    "AB$ Animate | Cost$ tapXType<Any/Creature.Other+withTotalPowerGE{{{n}}}> | Defined$ Self | Types$ Artifact,Creature | Secondary$ True | SpellDescription$ Crew {n}"
389                );
390                let next_idx = self.activated_abilities.len();
391                if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
392                    self.activated_abilities.push(ab);
393                    self.base_ability_count = self.activated_abilities.len();
394                }
395                return;
396            }
397        }
398    }
399
400    /// Generate triggered abilities from keywords (e.g. Prowess, Bushido, Annihilator, etc.).
401    /// Mirrors Java's `CardFactoryUtil.setupKeywordedTriggers()`.
402    pub fn generate_keyword_triggers(&mut self) {
403        let mut next_id = self.triggers.len() as u32;
404
405        for kw in self.keywords.as_string_list() {
406            self.generate_keyword_trigger_combat(&kw, &mut next_id);
407            self.generate_keyword_trigger_zone(&kw, &mut next_id);
408            self.generate_keyword_trigger_misc(&kw, &mut next_id);
409        }
410    }
411
412    fn generate_keyword_trigger_combat(&mut self, kw: &str, next_id: &mut u32) {
413        if kw == "Prowess" {
414            let raw = "Mode$ SpellCast | ValidCard$ Card.nonCreature | ValidActivatingPlayer$ You | Execute$ TrigProwess | TriggerZones$ Battlefield | TriggerDescription$ Prowess";
415            if let Some(mut trig) = parse_trigger(raw, next_id) {
416                trig.execute = "TrigProwess".to_string();
417                self.add_trigger(trig);
418            }
419            self.svars
420                .entry("TrigProwess".to_string())
421                .or_insert_with(|| "DB$ Pump | Defined$ Self | NumAtt$ 1 | NumDef$ 1".to_string());
422        }
423
424        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Bushido") {
425            if n_str.parse::<i32>().is_ok() {
426                let raw1 = format!(
427                    "Mode$ Blocks | ValidCard$ Card.Self | Execute$ TrigBushido | TriggerZones$ Battlefield | TriggerDescription$ Bushido {n_str}"
428                );
429                if let Some(mut trig) = parse_trigger(&raw1, next_id) {
430                    trig.execute = "TrigBushido".to_string();
431                    self.add_trigger(trig);
432                }
433                let raw2 = format!(
434                    "Mode$ AttackerBlocked | ValidCard$ Card.Self | Execute$ TrigBushido | TriggerZones$ Battlefield | TriggerDescription$ Bushido {n_str}"
435                );
436                if let Some(mut trig) = parse_trigger(&raw2, next_id) {
437                    trig.execute = "TrigBushido".to_string();
438                    self.add_trigger(trig);
439                }
440                self.svars
441                    .entry("TrigBushido".to_string())
442                    .or_insert_with(|| {
443                        format!("DB$ Pump | Defined$ Self | NumAtt$ {n_str} | NumDef$ {n_str}")
444                    });
445            }
446        }
447
448        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Annihilator") {
449            if n_str.parse::<i32>().is_ok() {
450                let raw = format!(
451                    "Mode$ Attacks | ValidCard$ Card.Self | Execute$ TrigAnnihilator | TriggerZones$ Battlefield | TriggerDescription$ Annihilator {n_str}"
452                );
453                if let Some(mut trig) = parse_trigger(&raw, next_id) {
454                    trig.execute = "TrigAnnihilator".to_string();
455                    self.add_trigger(trig);
456                }
457                self.svars
458                    .entry("TrigAnnihilator".to_string())
459                    .or_insert_with(|| {
460                        format!("DB$ Sacrifice | Defined$ TriggeredDefendingPlayer | SacValid$ Permanent | Amount$ {n_str}")
461                    });
462            }
463        }
464
465        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Afflict") {
466            if n_str.parse::<i32>().is_ok() {
467                let raw = format!(
468                    "Mode$ AttackerBlocked | ValidCard$ Card.Self | TriggerZones$ Battlefield | Secondary$ True | Execute$ TrigAfflict | TriggerDescription$ Afflict {n_str}"
469                );
470                if let Some(mut trig) = parse_trigger(&raw, next_id) {
471                    trig.execute = "TrigAfflict".to_string();
472                    self.add_trigger(trig);
473                }
474                self.svars
475                    .entry("TrigAfflict".to_string())
476                    .or_insert_with(|| {
477                        format!("DB$ LoseLife | Defined$ TriggeredDefendingPlayer | LifeAmount$ {n_str}")
478                    });
479            }
480        }
481
482        if kw == "Exalted" {
483            let raw = "Mode$ Attacks | ValidCard$ Creature.YouCtrl | Alone$ True | Execute$ TrigExalted | TriggerZones$ Battlefield | TriggerDescription$ Exalted";
484            if let Some(mut trig) = parse_trigger(raw, next_id) {
485                trig.execute = "TrigExalted".to_string();
486                self.add_trigger(trig);
487            }
488            self.svars
489                .entry("TrigExalted".to_string())
490                .or_insert_with(|| {
491                    "DB$ Pump | Defined$ TriggeredAttacker | NumAtt$ +1 | NumDef$ +1".to_string()
492                });
493        }
494
495        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Renown") {
496            if n_str.parse::<i32>().is_ok() {
497                let raw = format!(
498                    "Mode$ DamageDone | ValidSource$ Card.Self | ValidTarget$ Player | CombatDamage$ True | Execute$ TrigRenown | TriggerZones$ Battlefield | TriggerDescription$ Renown {n_str}"
499                );
500                if let Some(mut trig) = parse_trigger(&raw, next_id) {
501                    trig.execute = "TrigRenown".to_string();
502                    self.add_trigger(trig);
503                }
504                self.svars
505                    .entry("TrigRenown".to_string())
506                    .or_insert_with(|| {
507                        format!("DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ {n_str} | Renown$ True")
508                    });
509            }
510        }
511
512        if kw == "Flanking" {
513            let raw = "Mode$ AttackerBlockedByCreature | ValidBlocked$ Card.Self | ValidCard$ Creature.withoutFlanking | Execute$ TrigFlanking | TriggerZones$ Battlefield | TriggerDescription$ Flanking";
514            if let Some(mut trig) = parse_trigger(raw, next_id) {
515                trig.execute = "TrigFlanking".to_string();
516                self.add_trigger(trig);
517            }
518            self.svars
519                .entry("TrigFlanking".to_string())
520                .or_insert_with(|| {
521                    "DB$ Pump | Defined$ TriggeredBlocker | NumAtt$ -1 | NumDef$ -1".to_string()
522                });
523        }
524
525        if kw == "Extort" {
526            let raw = "Mode$ SpellCast | ValidActivatingPlayer$ You | Execute$ TrigExtort | TriggerZones$ Battlefield | TriggerDescription$ Extort";
527            if let Some(mut trig) = parse_trigger(raw, next_id) {
528                trig.execute = "TrigExtort".to_string();
529                trig.optional = true;
530                self.add_trigger(trig);
531            }
532            self.svars.entry("TrigExtort".to_string()).or_insert_with(|| {
533                "DB$ LoseLife | Defined$ Player.Opponent | LifeAmount$ 1 | SubAbility$ ExtortGain"
534                    .to_string()
535            });
536            self.svars
537                .entry("ExtortGain".to_string())
538                .or_insert_with(|| "DB$ GainLife | Defined$ You | LifeAmount$ 1".to_string());
539        }
540    }
541
542    fn generate_keyword_trigger_zone(&mut self, kw: &str, next_id: &mut u32) {
543        self.generate_keyword_trigger_zone_graveyard(kw, next_id);
544        self.generate_keyword_trigger_zone_battlefield(kw, next_id);
545    }
546
547    fn generate_keyword_trigger_zone_graveyard(&mut self, kw: &str, next_id: &mut u32) {
548        if kw == "Undying" {
549            let raw = "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self+counters_EQ0_P1P1 | TriggerZones$ Battlefield | Execute$ TrigUndying | TriggerDescription$ Undying";
550            if let Some(mut trig) = parse_trigger(raw, next_id) {
551                trig.execute = "TrigUndying".to_string();
552                self.add_trigger(trig);
553            }
554            self.svars.entry("TrigUndying".to_string()).or_insert_with(|| {
555                "DB$ ChangeZone | Defined$ TriggeredNewCardLKICopy | Origin$ Graveyard | Destination$ Battlefield | WithCountersType$ P1P1".to_string()
556            });
557        }
558
559        if kw == "Persist" {
560            let raw = "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self+counters_EQ0_M1M1 | TriggerZones$ Battlefield | Execute$ TrigPersist | TriggerDescription$ Persist";
561            if let Some(mut trig) = parse_trigger(raw, next_id) {
562                trig.execute = "TrigPersist".to_string();
563                self.add_trigger(trig);
564            }
565            self.svars.entry("TrigPersist".to_string()).or_insert_with(|| {
566                "DB$ ChangeZone | Defined$ TriggeredNewCardLKICopy | Origin$ Graveyard | Destination$ Battlefield | WithCountersType$ M1M1".to_string()
567            });
568        }
569
570        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Afterlife") {
571            if n_str.parse::<i32>().is_ok() {
572                let raw = format!(
573                    "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self | TriggerZones$ Battlefield | Execute$ TrigAfterlife | TriggerDescription$ Afterlife {n_str}"
574                );
575                if let Some(mut trig) = parse_trigger(&raw, next_id) {
576                    trig.execute = "TrigAfterlife".to_string();
577                    self.add_trigger(trig);
578                }
579                self.svars
580                    .entry("TrigAfterlife".to_string())
581                    .or_insert_with(|| {
582                        format!(
583                            "DB$ Token | TokenAmount$ {n_str} | TokenScript$ wb_1_1_spirit_flying"
584                        )
585                    });
586            }
587        }
588
589        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Modular") {
590            if let Ok(n) = n_str.parse::<i32>() {
591                self.etb_counters_p1p1 += n;
592
593                let raw = format!(
594                    "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self | TriggerZones$ Battlefield | Execute$ TrigModular | TriggerDescription$ Modular {n_str}"
595                );
596                if let Some(mut trig) = parse_trigger(&raw, next_id) {
597                    trig.execute = "TrigModular".to_string();
598                    trig.optional = true;
599                    self.add_trigger(trig);
600                }
601                self.svars
602                    .entry("TrigModular".to_string())
603                    .or_insert_with(|| "SP$ Charm | Choices$ ModularMove".to_string());
604                self.svars
605                    .entry("ModularMove".to_string())
606                    .or_insert_with(|| {
607                        format!("DB$ PutCounter | Defined$ Targeted | CounterType$ P1P1 | CounterNum$ {n_str} | Modular$ true | ValidTgts$ Creature.Artifact | SpellDescription$ Put +1/+1 counter(s) on target artifact creature")
608                    });
609            }
610        }
611    }
612
613    fn generate_keyword_trigger_zone_battlefield(&mut self, kw: &str, next_id: &mut u32) {
614        if kw == "Exploit" {
615            let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigExploit | TriggerDescription$ Exploit";
616            if let Some(mut trig) = parse_trigger(raw, next_id) {
617                trig.execute = "TrigExploit".to_string();
618                self.add_trigger(trig);
619            }
620            self.svars
621                .entry("TrigExploit".to_string())
622                .or_insert_with(|| {
623                    "DB$ Sacrifice | SacValid$ Creature | Optional$ True | Exploit$ True"
624                        .to_string()
625                });
626        }
627
628        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Fabricate") {
629            if n_str.parse::<i32>().is_ok() {
630                let raw = format!(
631                    "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigFabricate | Secondary$ True | TriggerDescription$ Fabricate {n_str}"
632                );
633                if let Some(mut trig) = parse_trigger(&raw, next_id) {
634                    trig.execute = "TrigFabricate".to_string();
635                    self.add_trigger(trig);
636                }
637                self.svars
638                    .entry("TrigFabricate".to_string())
639                    .or_insert_with(|| {
640                        format!(
641                            "DB$ Token | TokenAmount$ {n_str} | TokenScript$ c_1_1_a_servo \
642                             | UnlessCost$ AddCounter<{n_str}/P1P1> | UnlessPayer$ You \
643                             | SpellDescription$ Fabricate {n_str}"
644                        )
645                    });
646            }
647        }
648
649        if kw == "Living Weapon" {
650            let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Secondary$ True | TriggerDescription$ Living Weapon";
651            if let Some(mut trig) = parse_trigger(raw, next_id) {
652                trig.execute = "TrigLivingWeapon".to_string();
653                self.add_trigger(trig);
654            }
655            self.svars
656                .entry("TrigLivingWeapon".to_string())
657                .or_insert_with(|| {
658                    "DB$ Token | TokenScript$ b_0_0_phyrexian_germ | TokenOwner$ You | RememberTokens$ True | SubAbility$ DBLivingWeaponAttach".to_string()
659                });
660            self.svars
661                .entry("DBLivingWeaponAttach".to_string())
662                .or_insert_with(|| {
663                    "DB$ Attach | Defined$ Remembered | SubAbility$ DBLivingWeaponCleanup"
664                        .to_string()
665                });
666            self.svars
667                .entry("DBLivingWeaponCleanup".to_string())
668                .or_insert_with(|| "DB$ Cleanup | ClearRemembered$ True".to_string());
669        }
670
671        if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Bloodthirst") {
672            if n_str.parse::<i32>().is_ok() {
673                let raw = format!(
674                    "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigBloodthirst | TriggerDescription$ Bloodthirst {n_str}"
675                );
676                if let Some(mut trig) = parse_trigger(&raw, next_id) {
677                    trig.execute = "TrigBloodthirst".to_string();
678                    self.add_trigger(trig);
679                }
680                self.svars
681                    .entry("TrigBloodthirst".to_string())
682                    .or_insert_with(|| {
683                        format!("DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ {n_str} | Bloodthirst$ True")
684                    });
685            }
686        }
687
688        if kw == "Riot" {
689            let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigRiot | TriggerDescription$ Riot";
690            if let Some(mut trig) = parse_trigger(raw, next_id) {
691                trig.execute = "TrigRiot".to_string();
692                self.add_trigger(trig);
693            }
694            self.svars
695                .entry("TrigRiot".to_string())
696                .or_insert_with(|| "SP$ Charm | Choices$ RiotCounter,RiotHaste".to_string());
697            self.svars
698                .entry("RiotCounter".to_string())
699                .or_insert_with(|| {
700                    "DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ 1 | SpellDescription$ Put a +1/+1 counter on this creature".to_string()
701                });
702            self.svars
703                .entry("RiotHaste".to_string())
704                .or_insert_with(|| {
705                    "DB$ Pump | Defined$ Self | KW$ Haste | SpellDescription$ This creature gains haste".to_string()
706                });
707        }
708
709        if kw == "Unleash" {
710            let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigUnleash | TriggerDescription$ Unleash";
711            if let Some(mut trig) = parse_trigger(raw, next_id) {
712                trig.execute = "TrigUnleash".to_string();
713                self.add_trigger(trig);
714            }
715            self.svars
716                .entry("TrigUnleash".to_string())
717                .or_insert_with(|| {
718                    "DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ 1".to_string()
719                });
720        }
721    }
722
723    pub(crate) fn generate_keyword_chapter_triggers(&mut self) {
724        if !self.has_subtype("Saga") {
725            return;
726        }
727
728        let mut next_id = self.triggers.len() as u32;
729        for kw in self.keywords.as_string_list() {
730            if !kw.starts_with("Chapter") {
731                continue;
732            }
733            let Some((count, svars)) = kw
734                .strip_prefix("Chapter:")
735                .and_then(|value| value.split_once(':'))
736            else {
737                panic!("invalid Chapter keyword: {kw}");
738            };
739            let count = count
740                .parse::<usize>()
741                .unwrap_or_else(|_| panic!("invalid Chapter count: {count}"));
742            let svars: Vec<&str> = svars.split(',').collect();
743            assert!(
744                !svars.iter().any(|svar| svar.is_empty()),
745                "Chapter ability list must not contain empty SVars"
746            );
747            assert_eq!(svars.len(), count, "Saga max differ from Ability amount");
748
749            let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
750            for (chapter, svar) in svars.iter().enumerate() {
751                let chapter = chapter + 1;
752                if let Some((_, chapters)) = groups
753                    .iter_mut()
754                    .find(|(existing_svar, _)| existing_svar == svar)
755                {
756                    chapters.push(chapter);
757                } else {
758                    groups.push(((*svar).to_string(), vec![chapter]));
759                }
760            }
761
762            for (svar, chapters) in groups {
763                let description = self
764                    .get_s_var(&svar)
765                    .and_then(|raw| {
766                        raw.split('|').find_map(|param| {
767                            param
768                                .trim()
769                                .strip_prefix("SpellDescription$")
770                                .map(str::trim)
771                        })
772                    })
773                    .map(str::to_string)
774                    .unwrap_or_default();
775                let grouped_chapters = chapters
776                    .iter()
777                    .map(|chapter| roman_chapter(*chapter))
778                    .collect::<Vec<_>>()
779                    .join(", ");
780
781                for (index, chapter) in chapters.iter().enumerate() {
782                    let mut trigger = format!(
783                        "Mode$ CounterAdded | ValidCard$ Card.Self | TriggerZones$ Battlefield | Chapter$ {chapter} | CounterType$ LORE | CounterAmount$ EQ{chapter} | Execute$ {svar}"
784                    );
785                    if index > 0 {
786                        trigger.push_str(" | Secondary$ True");
787                    }
788                    trigger.push_str(&format!(
789                        " | TriggerDescription$ {grouped_chapters} — {description}"
790                    ));
791                    let Some(trigger) = parse_trigger(&trigger, &mut next_id) else {
792                        panic!("invalid Chapter trigger");
793                    };
794                    self.add_trigger(trigger);
795                }
796            }
797        }
798    }
799
800    fn generate_keyword_trigger_misc(&mut self, kw: &str, next_id: &mut u32) {
801        if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Ward") {
802            let raw = "Mode$ BecomesTarget | ValidSource$ SpellAbility.OppCtrl | ValidTarget$ Card.Self | Secondary$ True | TriggerZones$ Battlefield | TriggerDescription$ Ward";
803            if let Some(mut trig) = parse_trigger(raw, next_id) {
804                trig.execute = "TrigWard".to_string();
805                self.add_trigger(trig);
806            }
807            self.svars.entry("TrigWard".to_string()).or_insert_with(|| {
808                format!("DB$ Counter | Defined$ TriggeredSourceSA | UnlessCost$ {cost_str}")
809            });
810        }
811
812        if let Some(rest) = kw.strip_prefix("Cumulative upkeep:") {
813            let cost_spec = rest.split(':').next().unwrap_or(rest);
814            let raw = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Battlefield | TriggerDescription$ Cumulative upkeep";
815            if let Some(mut trig) = parse_trigger(raw, next_id) {
816                trig.execute = "TrigCumulativeUpkeep".to_string();
817                self.add_trigger(trig);
818            }
819            self.svars
820                .entry("TrigCumulativeUpkeep".to_string())
821                .or_insert_with(|| {
822                    format!("DB$ Sacrifice | SacValid$ Self | CumulativeUpkeep$ {cost_spec}")
823                });
824        }
825
826        if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Echo") {
827            let cost_spec = cost_str.split(':').next().unwrap_or(cost_str);
828            let raw = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Battlefield | IsPresent$ Card.Self+cameUnderControlSinceLastUpkeep | Secondary$ True | TriggerDescription$ Echo";
829            if let Some(mut trig) = parse_trigger(raw, next_id) {
830                trig.execute = "TrigEcho".to_string();
831                self.add_trigger(trig);
832            }
833            self.svars
834                .entry("TrigEcho".to_string())
835                .or_insert_with(|| format!("DB$ Sacrifice | SacValid$ Self | Echo$ {cost_spec}"));
836        }
837
838        if let Some(madness_cost) = crate::keyword::extract_keyword_cost_str(kw, "Madness") {
839            let raw = "Mode$ ChangesZone | Origin$ Hand | Destination$ Exile | ValidCard$ Card.Self | Secondary$ True | TriggerZones$ Exile | TriggerDescription$ You may cast this card for its madness cost.";
840            if let Some(mut trig) = parse_trigger(raw, next_id) {
841                trig.execute = "TrigMadnessPlay".to_string();
842                self.add_trigger(trig);
843            }
844            self.svars
845                .entry("TrigMadnessPlay".to_string())
846                .or_insert_with(|| {
847                    format!(
848                        "DB$ Play | Defined$ Self | ValidSA$ Spell | PlayCost$ {madness_cost} | Optional$ True | RememberPlayed$ True | SubAbility$ MadnessMoveToYard"
849                    )
850                });
851            self.svars
852                .entry("MadnessMoveToYard".to_string())
853                .or_insert_with(|| {
854                    "DB$ ChangeZone | Defined$ Self | Origin$ Exile | Destination$ Graveyard | TrackDiscarded$ True | ConditionDefined$ Remembered | ConditionPresent$ Card | ConditionCompare$ EQ0 | SubAbility$ MadnessCleanup".to_string()
855                });
856            self.svars
857                .entry("MadnessCleanup".to_string())
858                .or_insert_with(|| "DB$ Cleanup | ClearRemembered$ True".to_string());
859        }
860
861        if let Some(partner_name) = kw.strip_prefix("Partner with:") {
862            let mut partner_name = partner_name.trim().to_string();
863            let raw = format!(
864                "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Secondary$ True | TriggerDescription$ Partner with {partner_name}"
865            );
866            if let Some(mut trig) = parse_trigger(&raw, next_id) {
867                trig.execute = "TrigPartnerWith".to_string();
868                self.add_trigger(trig);
869            }
870            partner_name = partner_name.replace(',', ";");
871            self.svars
872                .entry("TrigPartnerWith".to_string())
873                .or_insert_with(|| {
874                    format!(
875                        "DB$ ChangeZone | ValidTgts$ Player | Origin$ Library | Destination$ Hand | ChangeType$ Card.named{partner_name} | Hidden$ True | Chooser$ Targeted | Optional$ True"
876                    )
877                });
878        }
879    }
880}