manabrew-engine 0.2.3

Magic: The Gathering rules engine — a Rust port of Forge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
//! CR 613 layer system — continuous effect application.
//!
//! Mirrors Java Forge's `GameAction.checkStaticAbilities()` and
//! `StaticAbilityContinuous.applyContinuousAbility()`.
//!
//! # How to use
//!
//! Call [`apply_continuous_effects`] after any event that could change which
//! static abilities are active (card entering/leaving the battlefield, spell
//! resolution, etc.):
//!
//! ```ignore
//! apply_continuous_effects(&mut game);
//! ```
//!
//! The function resets all derived fields (`static_power_modifier`,
//! `static_toughness_modifier`, `static_set_power`, `static_set_toughness`,
//! `granted_keywords`, `cant_attack_static`, `cant_block_static`) and
//! recomputes them from scratch.
//!
//! # Layer ordering (CR 613)
//!
//! 1. Copy effects (not yet implemented)
//! 2. Control-changing
//! 3. Text-changing (not yet implemented)
//! 4. Type-changing  → [`Layer::Type`]
//! 5. Color-changing → [`Layer::Color`]
//! 6. Ability-adding/removing → [`Layer::Ability`]
//! 7a. CDA P/T → [`Layer::Characteristic`]
//! 7b. Set P/T → [`Layer::SetPT`]
//! 7c. Modify P/T → [`Layer::ModifyPT`]
//! 7d. Counters (handled intrinsically by `Card::power()`)
//! 8. Forge rules-modifying layer → [`Layer::Rules`]

use std::collections::BTreeMap;

use forge_foundation::{CardTypeLine, CoreType, Supertype, ZoneType};

use crate::agent::PlayerAgent;
use crate::game::GameState;
use crate::ids::{CardId, PlayerId};
use crate::replacement::replacement_effect::ReplacementType;
use crate::staticability::{CardFilter, Layer, StaticAbility, StaticMode};

// ── Effect collection ────────────────────────────────────────────────────────

/// An effect ready to be applied to a specific target card.
struct PendingEffect {
    /// CR 613 layer (used for sort ordering).
    layer: Layer,
    /// Target card index.
    target: CardId,
    /// Payload.
    kind: EffectKind,
}

enum EffectKind {
    SetController {
        controller: PlayerId,
    },
    AddPT {
        power: i32,
        toughness: i32,
    },
    SetPT {
        power: Option<i32>,
        toughness: Option<i32>,
    },
    RemoveAllCardTraits {
        timestamp: i64,
        static_id: i64,
    },
    GrantKeyword(String),
    /// Grant an activated ability (from AddAbility$). The string is the ability text.
    GrantAbility {
        text: String,
        svars: BTreeMap<String, String>,
    },
    /// Add a type/subtype to the card (`AddType$`). Mirrors Java layer 4.
    AddType(String),
    /// Grant a triggered ability (from AddTrigger$). The string is the raw trigger text.
    GrantTrigger {
        text: String,
        svars: BTreeMap<String, String>,
    },
}

// ── Public API ───────────────────────────────────────────────────────────────

/// CR 613 layers a `Continuous` static contributes to.
///
/// Mirrors Java `StaticAbility.generateLayer()`. The classification is derived
/// at runtime from the authored params; `StaticAbilityIr` stores the parsed DSL
/// facts only.
pub fn classify_static_layers(sa: &StaticAbility) -> Vec<Layer> {
    if !sa.check_mode(&StaticMode::Continuous) {
        return Vec::new();
    }

    let ir = &sa.ir;
    let mut layers = Vec::new();

    push_layer(&mut layers, ir.gain_control_param, Layer::Control);
    push_layer(&mut layers, ir.has_text_layer_key, Layer::Text);
    push_layer(&mut layers, ir.has_type_layer_key, Layer::Type);
    push_layer(&mut layers, ir.has_color_layer_key, Layer::Color);
    push_layer(&mut layers, ir.has_ability_layer_key, Layer::Ability);

    if ir.set_power || ir.set_toughness {
        if ir.characteristic_defining {
            push_unique_layer(&mut layers, Layer::Characteristic);
        } else {
            push_unique_layer(&mut layers, Layer::SetPT);
        }
    }

    push_layer(
        &mut layers,
        ir.add_power || ir.add_toughness,
        Layer::ModifyPT,
    );
    push_layer(&mut layers, ir.has_rules_layer_key, Layer::Rules);

    if layers.is_empty() {
        layers.push(Layer::Rules);
    }

    layers
}

fn push_layer(layers: &mut Vec<Layer>, condition: bool, layer: Layer) {
    if condition {
        push_unique_layer(layers, layer);
    }
}

fn static_layer_trait_id(source_id: CardId, sa_idx: usize) -> i64 {
    -(((source_id.index() as i64) + 1) * 10_000 + sa_idx as i64 + 1)
}

fn push_unique_layer(layers: &mut Vec<Layer>, layer: Layer) {
    if !layers.contains(&layer) {
        layers.push(layer);
    }
}

fn type_line_has_token(type_line: &CardTypeLine, token: &str) -> bool {
    if let Some(st) = Supertype::from_name(token) {
        return type_line.supertypes.contains(&st);
    }
    if let Some(ct) = CoreType::from_name(token) {
        return type_line.core_types.contains(&ct);
    }
    type_line
        .subtypes
        .iter()
        .any(|subtype| subtype.eq_ignore_ascii_case(token))
}

/// Recompute all continuously-applied static-ability effects for the current
/// game state.
///
/// This is the Rust equivalent of Java Forge's
/// `GameAction.checkStaticAbilities()` + `StaticAbilityContinuous.applyContinuousAbility()`.
///
/// **Call this** after:
/// - Any permanent enters or leaves the battlefield.
/// - Any spell or ability resolves.
/// - Any triggered ability fires.
/// - Before querying `can_attack()` / `can_block()` for combat legality.
pub fn apply_continuous_effects(game: &mut GameState) {
    let _perf_timer = crate::perf::ScopeTimer::start(
        crate::perf::Metric::ContinuousEffectsCalls,
        crate::perf::Metric::ContinuousEffectsNs,
    );
    let _params_lookup_scope =
        crate::perf::ParamsLookupScopeGuard::enter(crate::perf::ParamsLookupScope::Continuous);
    // ── 1. Reset all derived fields ──────────────────────────────────────
    for card in game.cards.iter_mut() {
        card.clear_static_layer_changed_card_traits();
        // Remove abilities granted by continuous effects (AddAbility$).
        // The base_ability_count tracks how many abilities the card originally had.
        if card.activated_abilities.len() > card.base_ability_count {
            card.activated_abilities.truncate(card.base_ability_count);
        }
        for (ability_idx, ability) in card.activated_abilities.iter_mut().enumerate() {
            ability.ability_index = ability_idx;
        }
        let intrinsic_trigger_count = card.base_trigger_count + card.pump_trigger_count;
        if card.triggers.len() > intrinsic_trigger_count {
            card.triggers.truncate(intrinsic_trigger_count);
        }
        card.static_power_modifier = 0;
        card.static_toughness_modifier = 0;
        // Preserve face-down morph P/T override (2/2); only reset for face-up cards.
        if !card.face_down {
            card.static_set_power = None;
            card.static_set_toughness = None;
        }
        card.granted_keywords.clear();
        card.granted_svars.clear();
        // Restore the pre-layer type line before applying AddType$ statics.
        if let Some(type_line) = card.static_type_line_base.take() {
            card.set_type_line(type_line);
        }
        card.static_added_subtypes.clear();
        card.cant_attack_static = false;
        card.cant_block_static = false;
    }
    for player in game.players.iter_mut() {
        player.max_land_plays_per_turn = 1;
        player.unlimited_land_plays = false;
    }

    // ── 1b. Keyword-derived restrictions ────────────────────────────────
    // Unleash: creatures with Unleash keyword and a +1/+1 counter can't block.
    for card in game.cards.iter_mut() {
        if card.zone == ZoneType::Battlefield
            && card.has_keyword("Unleash")
            && card.counter_count(&crate::card::CounterType::P1P1) > 0
        {
            card.cant_block_static = true;
        }
    }

    for player_idx in 0..game.player_order.len() {
        let pid = game.player_order[player_idx];
        let player = game.player_mut(pid);
        player.max_hand_size = 7;
        player.unlimited_hand_size = false;
    }
    let player_ids: Vec<PlayerId> = game.player_order.clone();
    for player_idx in 0..player_ids.len() {
        let pid = player_ids[player_idx];
        let battlefield_cards: Vec<CardId> =
            game.cards_in_zone(ZoneType::Battlefield, pid).to_vec();
        for source_id in battlefield_cards {
            let static_ability_count = game.card(source_id).static_abilities.len();
            for sa_idx in 0..static_ability_count {
                let card = game.card(source_id);
                let sa = &card.static_abilities[sa_idx];
                if !sa.check_conditions(card, game) {
                    continue;
                }
                if !sa.check_mode(&StaticMode::Continuous) {
                    continue;
                }
                let affected = sa.ir.affected_text.as_deref().unwrap_or("");
                if !affected.eq_ignore_ascii_case("You") {
                    continue;
                }
                let controller = card.controller;
                let set_value = sa.ir.set_max_hand_size.clone();
                let raise_value = sa.ir.raise_max_hand_size.clone();
                if let Some(value) = set_value {
                    let player = game.player_mut(controller);
                    if value.eq_ignore_ascii_case("Unlimited") {
                        player.unlimited_hand_size = true;
                    } else if let Ok(n) = value.parse::<i32>() {
                        player.max_hand_size = n;
                    }
                }
                if let Some(value) = raise_value {
                    if let Ok(n) = value.parse::<i32>() {
                        let player = game.player_mut(controller);
                        player.max_hand_size = player.max_hand_size.saturating_add(n);
                    }
                }
            }
        }
    }

    // ── 2. Build list of effects-to-apply (deferred to allow sorting) ────
    let mut pending: Vec<PendingEffect> = Vec::new();
    let mut cant_attack_targets: Vec<CardId> = Vec::new();
    let mut cant_block_targets: Vec<CardId> = Vec::new();
    let mut granted_player_rules: Vec<(CardId, StaticAbility)> = Vec::new();

    let source_ids: Vec<CardId> = game.cards.iter().map(|card| card.id).collect();
    for source_id in source_ids {
        let static_ability_count = game.card(source_id).static_abilities.len();

        for sa_idx in 0..static_ability_count {
            let source_card = game.card(source_id).clone();
            let sa = game.card(source_id).static_abilities[sa_idx].clone();

            // Full static-ability condition gate (IsPresent$, CheckSVar$, Condition$, etc.).
            // Mirrors Java static ability checks before applying continuous effects.
            if !sa.check_conditions(&source_card, game) {
                continue;
            }

            if sa.check_mode(&StaticMode::Continuous) {
                apply_player_rules_effects(game, source_id, &sa);
            }

            // CharacteristicDefining statics always affect only the host card.
            // Mirrors Java StaticAbilityContinuous.getAffectedCards() line 1036.
            let is_cda = sa.ir.characteristic_defining;

            // Determine which cards are affected by this static ability.
            let affected_str = sa
                .ir
                .affected_text
                .as_deref()
                .or(sa.ir.valid_cards_text.as_deref())
                .or(sa.ir.valid_card_text.as_deref())
                .unwrap_or("Creature.YouControl");

            let mut apply_to_target = |target: CardId| {
                if sa.check_mode(&StaticMode::Continuous) {
                    if let Some(gain_control) = sa.ir.gain_control_text.as_deref() {
                        let new_controller = match gain_control {
                            "You" | "YouCtrl" => Some(source_card.controller),
                            "Opponent" => Some(game.opponent_of(source_card.controller)),
                            _ => None,
                        };
                        if let Some(controller) = new_controller {
                            pending.push(PendingEffect {
                                layer: Layer::Control,
                                target,
                                kind: EffectKind::SetController { controller },
                            });
                        }
                    }

                    let add_power = sa.ir.add_power_text.as_deref();
                    let add_toughness = sa.ir.add_toughness_text.as_deref();
                    if add_power.is_some() || add_toughness.is_some() {
                        let p = resolve_add_pt_value(game, source_id, add_power);
                        let t = resolve_add_pt_value(game, source_id, add_toughness);
                        pending.push(PendingEffect {
                            layer: Layer::ModifyPT,
                            target,
                            kind: EffectKind::AddPT {
                                power: p,
                                toughness: t,
                            },
                        });
                    }

                    let add_type = sa.ir.add_type_text.as_deref();
                    let source = game.card(source_id);
                    for added_type in resolve_added_types(source, add_type) {
                        pending.push(PendingEffect {
                            layer: Layer::Type,
                            target,
                            kind: EffectKind::AddType(added_type),
                        });
                    }

                    let set_power = sa.ir.set_power_text.as_deref();
                    let set_toughness = sa.ir.set_toughness_text.as_deref();
                    if set_power.is_some() || set_toughness.is_some() {
                        let sp = resolve_set_pt_value(game, source_id, set_power);
                        let st = resolve_set_pt_value(game, source_id, set_toughness);
                        // Java parity: CharacteristicDefining$ True routes
                        // SetP/T through layer 7a, otherwise 7b.
                        let layer = if is_cda {
                            Layer::Characteristic
                        } else {
                            Layer::SetPT
                        };
                        pending.push(PendingEffect {
                            layer,
                            target,
                            kind: EffectKind::SetPT {
                                power: sp,
                                toughness: st,
                            },
                        });
                    }

                    if let Some(kws) = sa.ir.add_keyword_text.as_deref() {
                        // AddKeyword$ supports multiple keywords separated by " & ".
                        for kw in kws.split('&').map(str::trim).filter(|s| !s.is_empty()) {
                            pending.push(PendingEffect {
                                layer: Layer::Ability,
                                target,
                                kind: EffectKind::GrantKeyword(kw.to_string()),
                            });
                        }
                    }

                    if sa.ir.remove_all_abilities {
                        pending.push(PendingEffect {
                            layer: Layer::Ability,
                            target,
                            kind: EffectKind::RemoveAllCardTraits {
                                timestamp: source_card.zone_timestamp as i64,
                                static_id: static_layer_trait_id(source_id, sa_idx),
                            },
                        });
                    }

                    // AddAbility$ — grant an activated ability to the affected card.
                    // The value is an SVar name on the source card containing the ability text.
                    // E.g. Abundant Growth: AddAbility$ AbundantGrowthTap
                    //   SVar:AbundantGrowthTap:AB$ Mana | Cost$ T | Produced$ Any
                    if let Some(svar_name) = sa.ir.add_ability_text.as_deref() {
                        if let Some(ab_text) = source_card.svars.get(svar_name).cloned() {
                            pending.push(PendingEffect {
                                layer: Layer::Ability,
                                target,
                                kind: EffectKind::GrantAbility {
                                    text: ab_text,
                                    svars: source_card.svars.clone(),
                                },
                            });
                        }
                    }

                    if let Some(add_trigger) = sa.ir.add_trigger_text.as_deref() {
                        for svar_name in add_trigger
                            .split(" & ")
                            .map(str::trim)
                            .filter(|s| !s.is_empty())
                        {
                            if let Some(trig_text) = source_card.svars.get(svar_name).cloned() {
                                pending.push(PendingEffect {
                                    layer: Layer::Ability,
                                    target,
                                    kind: EffectKind::GrantTrigger {
                                        text: trig_text,
                                        svars: source_card.svars.clone(),
                                    },
                                });
                            }
                        }
                    }

                    if let Some(add_static) = sa.ir.add_static_ability_text.as_deref() {
                        for svar_name in add_static
                            .split(" & ")
                            .map(str::trim)
                            .filter(|s| !s.is_empty())
                        {
                            if let Some(static_text) = source_card.svars.get(svar_name).cloned() {
                                if let Some(granted) =
                                    crate::staticability::parse_static_ability(&static_text)
                                {
                                    granted_player_rules.push((target, granted));
                                }
                            }
                        }
                    }

                    for subtype in resolve_added_basic_land_types(&source_card, add_type) {
                        if let Some(ab_text) = basic_land_mana_ability_text(&subtype) {
                            pending.push(PendingEffect {
                                layer: Layer::Ability,
                                target,
                                kind: EffectKind::GrantAbility {
                                    text: ab_text.to_string(),
                                    svars: BTreeMap::new(),
                                },
                            });
                        }
                    }
                }

                if sa.check_mode(&StaticMode::CantAttack) {
                    cant_attack_targets.push(target);
                }
                if sa.check_mode(&StaticMode::CantBlock) {
                    cant_block_targets.push(target);
                }
            };

            if is_cda {
                // CDAs always affect only the source card itself.
                if source_card.zone == ZoneType::Battlefield {
                    apply_to_target(source_id);
                }
            } else if affected_str.eq_ignore_ascii_case("Card.Self")
                || affected_str.starts_with("Card.Self+")
            {
                // Self-referencing static: only affects the source card itself,
                // but qualifiers after "+" must still be checked (e.g.
                // "Card.Self+counters_GE2_CHARGE" only matches when the card
                // has >=2 charge counters). Mirrors Java's
                // StaticAbilityContinuous.getAffectedCards() which validates
                // all qualifiers even for self-referencing statics.
                if source_card.zone == ZoneType::Battlefield
                    && crate::card::valid_filter::matches_valid_card(
                        affected_str,
                        &source_card,
                        &source_card,
                    )
                {
                    apply_to_target(source_id);
                }
            } else if affected_str.eq_ignore_ascii_case("Card.EnchantedBy")
                || affected_str.contains(".EquippedBy")
                || affected_str.contains(".EnchantedBy")
            {
                // Aura / Equipment static effects: affect what this source is
                // attached to. Java treats EquippedBy and EnchantedBy
                // identically: both resolve to the entity the source is
                // attached to. (e.g. Short Sword: "Creature.EquippedBy",
                // Control Magic: "Card.EnchantedBy")
                if let Some(cid) = source_card.attached_to {
                    if game.card(cid).zone == ZoneType::Battlefield {
                        apply_to_target(cid);
                    }
                }
            } else {
                let filter = CardFilter::parse(affected_str);
                // AffectedZone$ overrides the default Battlefield filter (e.g.
                // Ashling, the Limitless grants Evoke:4 to Elementals in Hand).
                let affected_zones = if sa.ir.affected_zones.is_empty() {
                    None
                } else {
                    Some(sa.ir.affected_zones.as_slice())
                };
                for card in &game.cards {
                    let zone_matches = match &affected_zones {
                        Some(zones) => zones.contains(&card.zone),
                        None => card.zone == ZoneType::Battlefield,
                    };
                    if zone_matches && filter.matches_with_game(card, &source_card, game) {
                        apply_to_target(card.id);
                    }
                }
            }
        }
    }

    for (source_id, granted) in granted_player_rules {
        apply_player_rules_effects(game, source_id, &granted);
    }

    for target in cant_attack_targets {
        game.cards[target.index()].cant_attack_static = true;
    }
    for target in cant_block_targets {
        game.cards[target.index()].cant_block_static = true;
    }

    // ── 4. Sort by layer then apply ──────────────────────────────────────
    // CR 613.1: apply layers 1→7c in order. Within the same layer, timestamp
    // ordering is preserved by the stable sort (sources were collected in
    // card-declaration order, which approximates timestamp order).
    pending.sort_by_key(|e| e.layer);

    for effect in pending {
        match effect.kind {
            EffectKind::SetController { controller } => {
                game.change_controller(effect.target, controller);
            }
            EffectKind::AddPT { power, toughness } => {
                let card = &mut game.cards[effect.target.index()];
                card.static_power_modifier += power;
                card.static_toughness_modifier += toughness;
            }
            EffectKind::SetPT { power, toughness } => {
                let card = &mut game.cards[effect.target.index()];
                // Layer 7b: override the base P/T for this calculation cycle.
                // We use `static_set_power` rather than mutating `base_power`
                // so the original base value is preserved for the next reset.
                if let Some(p) = power {
                    card.static_set_power = Some(p);
                }
                if let Some(t) = toughness {
                    card.static_set_toughness = Some(t);
                }
            }
            EffectKind::RemoveAllCardTraits {
                timestamp,
                static_id,
            } => {
                game.cards[effect.target.index()].add_changed_card_traits(
                    crate::card::card_trait_changes::CardTraitChanges::remove_all_layer(
                        Vec::new(),
                        Vec::new(),
                        Vec::new(),
                        Vec::new(),
                    ),
                    timestamp,
                    static_id,
                );
            }
            EffectKind::GrantKeyword(kw) => {
                let card = &mut game.cards[effect.target.index()];
                card.granted_keywords.add(&kw);
                if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(&kw, "Ward") {
                    let next_id = card
                        .triggers
                        .iter()
                        .map(|t| t.id)
                        .max()
                        .unwrap_or(0)
                        .saturating_add(1);
                    let mut next_id_mut = next_id;
                    let execute = format!("TrigWardGranted{}", next_id);
                    let raw = format!(
                        "Mode$ BecomesTarget | ValidSource$ SpellAbility.OppCtrl | ValidTarget$ Card.Self | Secondary$ True | Execute$ {} | TriggerZones$ Battlefield | TriggerDescription$ Ward",
                        execute
                    );
                    if let Some(mut trig) = crate::trigger::parse_trigger(&raw, &mut next_id_mut) {
                        trig.execute = execute.clone();
                        card.add_trigger(trig);
                    }
                    card.granted_svars.insert(
                        execute,
                        format!(
                            "DB$ Counter | Defined$ TriggeredSourceSA | UnlessCost$ {cost_str}"
                        ),
                    );
                }
            }
            EffectKind::AddType(t) => {
                let card = &mut game.cards[effect.target.index()];
                if !type_line_has_token(&card.type_line, &t) {
                    if card.static_type_line_base.is_none() {
                        card.static_type_line_base = Some(card.type_line.clone());
                    }
                    card.add_type(&t);
                    card.static_added_subtypes.push(t);
                }
            }
            EffectKind::GrantAbility { text, svars } => {
                // Parse the ability text and add it to the target's activated abilities.
                // This grants abilities like "{T}: Add one mana of any color."
                game.cards[effect.target.index()]
                    .granted_svars
                    .extend(svars);
                let target_idx = effect.target.index();
                let next_idx = game.cards[target_idx].activated_abilities.len();
                if let Some(ab) =
                    crate::ability::activated::parse_activated_ability(&text, next_idx)
                {
                    game.cards[target_idx].activated_abilities.push(ab);
                }
            }
            EffectKind::GrantTrigger { text, svars } => {
                game.cards[effect.target.index()]
                    .granted_svars
                    .extend(svars);
                let next_id = game.cards[effect.target.index()]
                    .triggers
                    .iter()
                    .map(|t| t.id)
                    .max()
                    .unwrap_or(0)
                    .saturating_add(1);
                let mut next_id_mut = next_id;
                if let Some(trig) = crate::trigger::parse_trigger(&text, &mut next_id_mut) {
                    game.cards[effect.target.index()].add_trigger(trig);
                }
            }
        }
    }

    // Rebuild intrinsic basic-land mana abilities after type-changing continuous
    // effects have been applied (e.g. Urborg making lands into Swamps).
    for card in game.cards.iter_mut() {
        if card.zone == ZoneType::Battlefield {
            card.generate_basic_land_mana_abilities();
        }
    }
}

fn apply_player_rules_effects(game: &mut GameState, source_id: CardId, sa: &StaticAbility) {
    let Some(adjust_land_plays) = sa.ir.adjust_land_plays_text.as_deref() else {
        return;
    };
    let affected_players = affected_players_for_static(game, source_id, sa);
    if affected_players.is_empty() {
        return;
    }
    if adjust_land_plays.eq_ignore_ascii_case("Unlimited") {
        for player in affected_players {
            game.player_mut(player).unlimited_land_plays = true;
        }
        return;
    }
    let amount = resolve_rules_amount(game, source_id, adjust_land_plays);
    for player in affected_players {
        game.player_mut(player).max_land_plays_per_turn += amount;
    }
}

fn affected_players_for_static(
    game: &GameState,
    source_id: CardId,
    sa: &StaticAbility,
) -> Vec<PlayerId> {
    let Some(affected) = sa.ir.affected_text.as_deref() else {
        return Vec::new();
    };
    let source = game.card(source_id);
    game.player_order
        .iter()
        .copied()
        .filter(|&player| {
            !sa.ignore_effect_players.contains(&player)
                && crate::card::valid_filter::matches_valid(
                    affected,
                    None,
                    Some(player),
                    source,
                    source.controller,
                )
        })
        .collect()
}

fn resolve_rules_amount(game: &GameState, source_id: CardId, value: &str) -> i32 {
    if let Ok(n) = value.trim().parse::<i32>() {
        return n;
    }
    let source = game.card(source_id);
    if let Some(svar_expr) = source.svars.get(value.trim()) {
        if svar_expr.starts_with("Count$") {
            return crate::ability::effects::resolve_count_svar(
                svar_expr,
                game,
                source_id,
                source.controller,
            );
        }
        return crate::ability::effects::evaluate_svar(
            svar_expr,
            &crate::spellability::SpellAbility::new_empty(Some(source_id), source.controller),
        );
    }
    0
}

/// Apply ETB-tapped effects to `entering_card` as it enters the battlefield.
///
/// Checks:
/// 1. The card's own static abilities for `Mode$ ETBTapped` (intrinsic).
/// 2. Any other battlefield permanent with `Mode$ ETBTapped` whose filter
///    matches the entering card (extrinsic, e.g. Imposing Sovereign).
///
/// Call this immediately after [`GameState::move_card`] resolves a
/// `Battlefield` destination and before triggers are fired.
pub fn apply_etb_tapped(game: &mut GameState, entering_card: CardId) {
    apply_etb_tapped_with_agents(game, entering_card, None);
}

fn applicable_etb_tapped_replacement_sources(
    game: &GameState,
    entering_card: CardId,
) -> Vec<(CardId, String)> {
    let mut repl_sources: Vec<(CardId, String, String)> = Vec::new();
    for c in &game.cards {
        if c.zone != ZoneType::Battlefield {
            continue;
        }
        for re in &c.replacement_effects {
            if re.event == ReplacementType::Moved
                && re.replace_with() == Some("ETBTapped")
                && re.ir.destination_zone == Some(ZoneType::Battlefield)
                && re.active_in_zone(ZoneType::Battlefield)
            {
                let filter = re
                    .ir
                    .valid_card_text
                    .as_deref()
                    .unwrap_or("Card.Self")
                    .to_string();
                let desc = re.description(c, game);
                repl_sources.push((c.id, filter, desc));
            }
        }
    }

    repl_sources
        .into_iter()
        .filter_map(|(source_id, filter_str, desc)| {
            let tapped = if filter_str == "Card.Self" || filter_str.is_empty() {
                source_id == entering_card
            } else {
                let source = &game.cards[source_id.index()];
                let filter = CardFilter::parse(&filter_str);
                filter.matches_with_game(&game.cards[entering_card.index()], source, game)
            };
            tapped.then_some((source_id, desc))
        })
        .collect()
}

pub fn prompt_etb_tapped_replacement_with_agents(
    game: &mut GameState,
    entering_card: CardId,
    agents: &mut [Box<dyn PlayerAgent>],
) {
    let applicable = applicable_etb_tapped_replacement_sources(game, entering_card);
    if applicable.is_empty() {
        return;
    }

    let affected_player = game.cards[entering_card.index()].controller;
    let descriptions: Vec<String> = applicable
        .iter()
        .map(|(source_id, desc)| format!("{}: {}", game.card(*source_id).card_name, desc))
        .collect();
    let _chosen = agents[affected_player.index()]
        .choose_single_replacement_effect(affected_player, &descriptions)
        .min(applicable.len().saturating_sub(1));
}

pub fn apply_etb_tapped_with_agents(
    game: &mut GameState,
    entering_card: CardId,
    agents: Option<&mut [Box<dyn PlayerAgent>]>,
) {
    // Collect all ETBTapped sources: (source_id, filter_str).
    // We need owned data to avoid aliasing the cards slice while mutating.
    let etb_sources: Vec<(CardId, String)> = game
        .cards
        .iter()
        .filter(|c| c.zone == ZoneType::Battlefield)
        .flat_map(|c| {
            c.static_abilities.iter().filter_map(move |sa| {
                if sa.check_mode(&StaticMode::ETBTapped) {
                    let filter_str = sa
                        .ir
                        .valid_cards_text
                        .clone()
                        .or_else(|| sa.ir.affected_text.clone())
                        // Default: the card itself (intrinsic self-ETBTapped).
                        .unwrap_or_else(|| "Card.Self".to_string());
                    Some((c.id, filter_str))
                } else {
                    None
                }
            })
        })
        .collect();

    for (source_id, filter_str) in etb_sources {
        // "Card.Self" means only the card that owns the ability.
        let tapped = if filter_str == "Card.Self" || filter_str.is_empty() {
            source_id == entering_card
        } else {
            let source = &game.cards[source_id.index()];
            let filter = CardFilter::parse(&filter_str);
            filter.matches_with_game(&game.cards[entering_card.index()], source, game)
        };

        if tapped {
            game.cards[entering_card.index()].tapped = true;
            return; // once tapped, no need to check further sources
        }
    }

    // ── Second pass: check replacement effects for ReplaceWith$ ETBTapped ──
    // Many cards (e.g. Path of Ancestry, Temple of Mystery) use:
    //   R:Event$ Moved | Destination$ Battlefield | ValidCard$ Card.Self | ReplaceWith$ ETBTapped
    // Extrinsic sources (e.g. Kismet) may use broader ValidCard filters.
    let applicable = applicable_etb_tapped_replacement_sources(game, entering_card);
    if applicable.is_empty() {
        return;
    }

    if let Some(agents) = agents {
        prompt_etb_tapped_replacement_with_agents(game, entering_card, agents);
    }

    game.cards[entering_card.index()].tapped = true;
}

/// Check if a card has a shock-land-style "enters tapped unless you pay life" effect.
///
/// Looks for `R:Event$ Moved | Destination$ Battlefield | ReplaceWith$ <SVar>`
/// where the SVar is `DB$ Tap | ETB$ True | UnlessCost$ PayLife<N>`.
///
/// Returns `Some(life_cost)` if found (e.g. `Some(2)` for shock lands), `None` otherwise.
/// Called from `play_card` / `resolve_stack` where agents are available for prompting.
pub fn get_etb_unless_life_cost(card: &crate::card::Card) -> Option<i32> {
    for re in &card.replacement_effects {
        if re.event != ReplacementType::Moved {
            continue;
        }
        if re.ir.destination_zone != Some(ZoneType::Battlefield) {
            continue;
        }
        if let Some(svar_name) = re.replace_with() {
            if svar_name == "ETBTapped" {
                continue;
            }
            if let Some(svar_val) = card.svars.get(svar_name) {
                if svar_val.contains("DB$ Tap") && svar_val.contains("ETB$ True") {
                    // Parse life cost from "UnlessCost$ PayLife<N>"
                    if let Some(pos) = svar_val.find("PayLife<") {
                        let after = &svar_val[pos + 8..]; // skip "PayLife<"
                        if let Some(end) = after.find('>') {
                            if let Ok(n) = after[..end].parse::<i32>() {
                                return Some(n);
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Check if a card has a "enters tapped unless you reveal a <type> from hand" effect.
///
/// Looks for `R:Event$ Moved | Destination$ Battlefield | ReplaceWith$ <SVar>`
/// where the SVar is `DB$ Tap | ETB$ True | UnlessCost$ Reveal<N/Filter>`.
///
/// Returns `Some((n, filter))` if found (e.g. `Some((1, "Merfolk"))` for Wanderwine Hub).
pub fn get_etb_unless_reveal_cost(card: &crate::card::Card) -> Option<(i32, String)> {
    for re in &card.replacement_effects {
        if re.event != ReplacementType::Moved {
            continue;
        }
        if re.ir.destination_zone != Some(ZoneType::Battlefield) {
            continue;
        }
        if let Some(svar_name) = re.replace_with() {
            if svar_name == "ETBTapped" {
                continue;
            }
            if let Some(svar_val) = card.svars.get(svar_name) {
                if svar_val.contains("DB$ Tap") && svar_val.contains("ETB$ True") {
                    // Parse reveal cost from "UnlessCost$ Reveal<N/Filter>"
                    if let Some(pos) = svar_val.find("Reveal<") {
                        let after = &svar_val[pos + 7..]; // skip "Reveal<"
                        if let Some(end) = after.find('>') {
                            let inner = &after[..end]; // "1/Merfolk" or "1/Filter"
                            let mut parts = inner.splitn(2, '/');
                            let n = parts
                                .next()
                                .and_then(|s| s.trim().parse::<i32>().ok())
                                .unwrap_or(1);
                            let filter = parts.next().unwrap_or("").trim().to_string();
                            return Some((n, filter));
                        }
                    }
                }
            }
        }
    }
    None
}

/// Resolve an AddPower$/AddToughness$ parameter that may be a literal integer
/// or an SVar reference (e.g. "X" → Count$Valid Enchantment.YouCtrl).
fn resolve_add_pt_value(game: &GameState, source_id: CardId, val_str: Option<&str>) -> i32 {
    let val_str = match val_str {
        Some(val_str) => val_str,
        None => return 0,
    };

    // Try direct integer parse first
    if let Ok(n) = val_str.trim().parse::<i32>() {
        return n;
    }

    // It's an SVar reference — look it up on the source card
    let source = game.card(source_id);
    if let Some(svar_expr) = source.svars.get(val_str.trim()) {
        if svar_expr.starts_with("Count$") {
            return crate::ability::effects::resolve_count_svar(
                svar_expr,
                game,
                source_id,
                source.controller,
            );
        }
        return crate::ability::effects::evaluate_svar(
            svar_expr,
            &crate::spellability::SpellAbility::new_empty(Some(source_id), source.controller),
        );
    }

    0
}

/// Resolve a SetPower$/SetToughness$ parameter that may be a literal integer or
/// an SVar reference (e.g. "X" → SVar:X:Count$Valid Creature.ChosenType).
/// Mirrors Java `AbilityUtils.calculateAmount(hostCard, param, stAb)`.
fn resolve_set_pt_value(game: &GameState, source_id: CardId, val_str: Option<&str>) -> Option<i32> {
    let val_str = val_str?;
    // Try direct integer parse first
    if let Ok(n) = val_str.trim().parse::<i32>() {
        return Some(n);
    }

    // It's an SVar reference — look it up on the source card
    let source = game.card(source_id);
    if let Some(svar_expr) = source.svars.get(val_str.trim()) {
        if svar_expr.starts_with("Count$") {
            return Some(crate::ability::effects::resolve_count_svar(
                svar_expr,
                game,
                source_id,
                source.controller,
            ));
        }
        // Simple SVar evaluation (e.g. Number$2)
        return Some(crate::ability::effects::evaluate_svar(
            svar_expr,
            &crate::spellability::SpellAbility::new_empty(Some(source_id), source.controller),
        ));
    }

    None
}

fn basic_land_mana_ability_text(subtype: &str) -> Option<&'static str> {
    match subtype {
        "Plains" => Some("AB$ Mana | Cost$ T | Produced$ W | SpellDescription$ Add {W}."),
        "Island" => Some("AB$ Mana | Cost$ T | Produced$ U | SpellDescription$ Add {U}."),
        "Swamp" => Some("AB$ Mana | Cost$ T | Produced$ B | SpellDescription$ Add {B}."),
        "Mountain" => Some("AB$ Mana | Cost$ T | Produced$ R | SpellDescription$ Add {R}."),
        "Forest" => Some("AB$ Mana | Cost$ T | Produced$ G | SpellDescription$ Add {G}."),
        _ => None,
    }
}

fn resolve_added_basic_land_types(
    source: &crate::card::Card,
    add_type: Option<&str>,
) -> Vec<String> {
    resolve_added_types(source, add_type)
        .into_iter()
        .filter(|added| basic_land_mana_ability_text(added).is_some())
        .collect()
}

fn resolve_added_types(source: &crate::card::Card, add_type: Option<&str>) -> Vec<String> {
    let Some(add_type) = add_type else {
        return Vec::new();
    };
    let mut resolved = Vec::new();
    for raw in add_type.split('&').map(str::trim).filter(|s| !s.is_empty()) {
        match raw {
            "ChosenType" => {
                if let Some(chosen) = source.chosen_type.as_ref() {
                    resolved.push(chosen.clone());
                }
            }
            "ChosenType2" => {
                if let Some(chosen) = source.chosen_type2.as_ref() {
                    resolved.push(chosen.clone());
                }
            }
            "AllBasicLandType" => {
                resolved.extend(
                    ["Plains", "Island", "Swamp", "Mountain", "Forest"]
                        .into_iter()
                        .map(str::to_string),
                );
            }
            other => resolved.push(other.to_string()),
        }
    }
    resolved
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use forge_foundation::{CardTypeLine, ColorSet, ManaCost, ZoneType};

    use crate::card::Card;
    use crate::ids::{CardId, PlayerId};

    // Build a minimal two-player game with empty zones.
    fn new_game() -> GameState {
        GameState::new(&["Alice", "Bob"], 20)
    }

    fn add_creature(
        game: &mut GameState,
        owner: PlayerId,
        power: i32,
        toughness: i32,
        keywords: Vec<String>,
        abilities: Vec<String>,
    ) -> CardId {
        let card = Card::new(
            CardId(0), // reassigned by create_card
            "Creature".to_string(),
            owner,
            CardTypeLine::parse("Creature"),
            ManaCost::parse("1 G"),
            ColorSet::GREEN,
            Some(power),
            Some(toughness),
            keywords,
            abilities,
        );
        let id = game.create_card(card);
        game.move_card(id, ZoneType::Battlefield, owner);
        id
    }

    fn add_enchantment(game: &mut GameState, owner: PlayerId, abilities: Vec<String>) -> CardId {
        let card = Card::new(
            CardId(0),
            "Enchantment".to_string(),
            owner,
            CardTypeLine::parse("Enchantment"),
            ManaCost::parse("2 W"),
            ColorSet::WHITE,
            None,
            None,
            vec![],
            abilities,
        );
        let id = game.create_card(card);
        game.move_card(id, ZoneType::Battlefield, owner);
        id
    }

    fn add_land(
        game: &mut GameState,
        owner: PlayerId,
        name: &str,
        type_line: &str,
        abilities: Vec<String>,
    ) -> CardId {
        let card = Card::new(
            CardId(0),
            name.to_string(),
            owner,
            CardTypeLine::parse(type_line),
            ManaCost::no_cost(),
            ColorSet::COLORLESS,
            None,
            None,
            vec![],
            abilities,
        );
        let id = game.create_card(card);
        game.move_card(id, ZoneType::Battlefield, owner);
        id
    }

    fn add_effect(game: &mut GameState, owner: PlayerId, abilities: Vec<String>) -> CardId {
        let card = Card::new(
            CardId(0),
            "Effect".to_string(),
            owner,
            CardTypeLine::parse("Effect"),
            ManaCost::parse("0"),
            ColorSet::COLORLESS,
            None,
            None,
            vec![],
            abilities,
        );
        let id = game.create_card(card);
        game.move_card(id, ZoneType::Command, owner);
        id
    }

    // ── Anthem (+1/+1) ────────────────────────────────────────────────────

    #[test]
    fn anthem_boosts_your_creatures() {
        let mut game = new_game();
        let alice = PlayerId(0);
        let bob = PlayerId(1);

        // Add two creatures for Alice and one for Bob.
        let a1 = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        let a2 = add_creature(&mut game, alice, 1, 1, vec![], vec![]);
        let b1 = add_creature(&mut game, bob, 2, 2, vec![], vec![]);

        // Add Glorious Anthem-style enchantment controlled by Alice.
        let _anthem = add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1 | Description$ Creatures you control get +1/+1.".to_string()],
        );

        apply_continuous_effects(&mut game);

        // Alice's creatures get +1/+1.
        assert_eq!(game.card(a1).power(), 3, "Alice's 2/2 should be 3/3");
        assert_eq!(game.card(a1).toughness(), 3);
        assert_eq!(game.card(a2).power(), 2, "Alice's 1/1 should be 2/2");
        assert_eq!(game.card(a2).toughness(), 2);

        // Bob's creature is unaffected.
        assert_eq!(
            game.card(b1).power(),
            2,
            "Bob's creature should be unchanged"
        );
        assert_eq!(game.card(b1).toughness(), 2);
    }

    #[test]
    fn command_effect_adjusts_land_plays_for_affected_player() {
        let mut game = new_game();
        let alice = PlayerId(0);
        let bob = PlayerId(1);

        let effect = add_effect(
            &mut game,
            alice,
            vec![
                "S$ Mode$ Continuous | EffectZone$ Command | Affected$ You | AdjustLandPlays$ 1"
                    .to_string(),
            ],
        );

        apply_continuous_effects(&mut game);

        assert_eq!(game.player(alice).max_land_plays_per_turn, 2);
        assert_eq!(game.player(bob).max_land_plays_per_turn, 1);

        game.move_card(effect, ZoneType::Exile, alice);
        apply_continuous_effects(&mut game);

        assert_eq!(game.player(alice).max_land_plays_per_turn, 1);
    }

    #[test]
    fn anthem_resets_when_removed() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        let anthem = add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
        );

        apply_continuous_effects(&mut game);
        assert_eq!(game.card(creature).power(), 3);

        // Remove the anthem from the battlefield.
        game.move_card(anthem, ZoneType::Graveyard, alice);
        apply_continuous_effects(&mut game);

        assert_eq!(
            game.card(creature).power(),
            2,
            "Bonus should be gone after anthem leaves"
        );
    }

    #[test]
    fn stacking_anthems() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 1, 1, vec![], vec![]);
        // Two separate +1/+1 anthems.
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
        );
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
        );

        apply_continuous_effects(&mut game);
        assert_eq!(game.card(creature).power(), 3, "Two anthems should give +2");
        assert_eq!(game.card(creature).toughness(), 3);
    }

    // ── Keyword granting ──────────────────────────────────────────────────

    #[test]
    fn grant_flying_to_your_creatures() {
        let mut game = new_game();
        let alice = PlayerId(0);
        let bob = PlayerId(1);

        let a1 = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        let b1 = add_creature(&mut game, bob, 2, 2, vec![], vec![]);

        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddKeyword$ Flying | Description$ Creatures you control have flying.".to_string()],
        );

        apply_continuous_effects(&mut game);

        assert!(
            game.card(a1).has_flying(),
            "Alice's creature should have flying"
        );
        assert!(
            !game.card(b1).has_flying(),
            "Bob's creature should not have flying"
        );
    }

    #[test]
    fn grant_multiple_keywords() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddKeyword$ Flying & First Strike".to_string()],
        );

        apply_continuous_effects(&mut game);

        assert!(game.card(creature).has_flying());
        assert!(game.card(creature).has_first_strike());
    }

    // ── SetPT (Layer 7b) ──────────────────────────────────────────────────

    #[test]
    fn set_pt_overrides_base() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 5, 5, vec![], vec![]);
        // Effect: set all your creatures to 0/1 (e.g. Humility).
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | SetPower$ 0 | SetToughness$ 1".to_string()],
        );

        apply_continuous_effects(&mut game);
        assert_eq!(game.card(creature).power(), 0);
        assert_eq!(game.card(creature).toughness(), 1);
    }

    #[test]
    fn modify_pt_adds_on_top_of_set_pt() {
        // CR 613.7c: ModifyPT applies after SetPT within the same turn.
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 5, 5, vec![], vec![]);
        // Layer 7b: set to 0/1.
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | SetPower$ 0 | SetToughness$ 1".to_string()],
        );
        // Layer 7c: +1/+1 anthem on top.
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
        );

        apply_continuous_effects(&mut game);
        // 0 + 1 = 1 power, 1 + 1 = 2 toughness.
        assert_eq!(game.card(creature).power(), 1);
        assert_eq!(game.card(creature).toughness(), 2);
    }

    // ── CantAttack / CantBlock ────────────────────────────────────────────

    #[test]
    fn cant_attack_flag_set() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        // Pacifism-like effect.
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ CantAttack | Affected$ Creature.YouControl | Description$ Creatures you control can't attack.".to_string()],
        );

        apply_continuous_effects(&mut game);
        assert!(game.card(creature).cant_attack_static);
    }

    #[test]
    fn cant_block_flag_set() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ CantBlock | Affected$ Creature.YouControl".to_string()],
        );

        apply_continuous_effects(&mut game);
        assert!(game.card(creature).cant_block_static);
    }

    #[test]
    fn flags_reset_on_reapplication() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        let restrictor = add_enchantment(
            &mut game,
            alice,
            vec!["S$ Mode$ CantAttack | Affected$ Creature.YouControl".to_string()],
        );

        apply_continuous_effects(&mut game);
        assert!(game.card(creature).cant_attack_static);

        game.move_card(restrictor, ZoneType::Graveyard, alice);
        apply_continuous_effects(&mut game);
        assert!(
            !game.card(creature).cant_attack_static,
            "Flag should clear after enchantment leaves"
        );
    }

    #[test]
    fn lands_gain_swamp_mana_ability_from_urborg_style_effect() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let urborg = add_land(
            &mut game,
            alice,
            "Urborg, Tomb of Yawgmoth",
            "Legendary Land",
            vec!["S$ Mode$ Continuous | Affected$ Land | AddType$ Swamp | Description$ Each land is a Swamp in addition to its other land types.".to_string()],
        );
        let black_gate = add_land(
            &mut game,
            alice,
            "The Black Gate",
            "Legendary Land Gate",
            vec![],
        );

        apply_continuous_effects(&mut game);

        for land_id in [urborg, black_gate] {
            let land = game.card(land_id);
            assert!(
                land.type_line.has_subtype("Swamp"),
                "{} should gain the Swamp subtype",
                land.card_name
            );
            assert!(
                land.activated_abilities.iter().any(|ab| {
                    ab.is_mana_ability
                        && ab
                            .produced_ir
                            .as_ref()
                            .is_some_and(|ir| ir.as_script_text() == "B")
                }),
                "{} should gain an intrinsic black mana ability from Swamp",
                land.card_name
            );
        }
    }

    // ── ETB Tapped ────────────────────────────────────────────────────────

    #[test]
    fn self_etb_tapped() {
        let mut game = new_game();
        let alice = PlayerId(0);

        // A permanent with ETBTapped on itself.
        let card = Card::new(
            CardId(0),
            "TappedLand".to_string(),
            alice,
            CardTypeLine::parse("Land"),
            ManaCost::parse(""),
            ColorSet::from_mask(0),
            None,
            None,
            vec![],
            vec!["S$ Mode$ ETBTapped | Description$ Enters tapped.".to_string()],
        );
        let id = game.create_card(card);
        game.move_card(id, ZoneType::Battlefield, alice);
        apply_etb_tapped(&mut game, id);

        assert!(
            game.card(id).tapped,
            "Card with ETBTapped should enter tapped"
        );
    }

    #[test]
    fn no_etb_tapped_without_ability() {
        let mut game = new_game();
        let alice = PlayerId(0);

        let id = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
        // Fresh ETB, no static — should not be tapped.
        assert!(
            !game.card(id).tapped,
            "Normal creature should not enter tapped"
        );
    }

    #[test]
    fn etb_tapped_via_replacement_effect() {
        let mut game = new_game();
        let alice = PlayerId(0);

        // A land with R:Event$ Moved replacement effect (like Path of Ancestry).
        let card = Card::new(
            CardId(0),
            "PathOfAncestry".to_string(),
            alice,
            CardTypeLine::parse("Land"),
            ManaCost::parse(""),
            ColorSet::from_mask(0),
            None,
            None,
            vec![],
            vec!["R:Event$ Moved | Destination$ Battlefield | ValidCard$ Card.Self | ReplaceWith$ ETBTapped | Description$ ~ enters tapped.".to_string()],
        );
        let id = game.create_card(card);
        game.move_card(id, ZoneType::Battlefield, alice);
        apply_etb_tapped(&mut game, id);

        assert!(
            game.card(id).tapped,
            "Card with ReplaceWith$ ETBTapped replacement should enter tapped"
        );
    }
}