manabrew-engine 0.4.1

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
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
//! Replacement effect dispatcher.
//!
//! Mirrors the Java Forge `ReplacementHandler.java` in
//! `forge/game/replacement/`.
//!
//! The entry point is [`apply_replacements`], which accepts a mutable
//! [`ReplacementEvent`] and iterates through the five CR 616 layers
//! (CantHappen → Control → Copy → Transform → Other), applying the first
//! matching effect in each layer.

use std::collections::{HashMap, HashSet};

use forge_foundation::{PhaseType, ZoneType};

use crate::agent::GameEntity;
use crate::card::Card;
use crate::card::CounterType;
use crate::card_trait_base::CardTrait;
use crate::game::GameState;
use crate::game_rng::GameRng;
use crate::ids::{CardId, PlayerId};
use crate::mana::ManaPool;
use crate::replacement::replacement_effect::{
    resolve_replace_with_chain, GameLossReason, ReplacementChainIr, ReplacementEffect,
};
use crate::replacement::replacement_layer::ReplacementLayer;
use crate::replacement::replacement_result::ReplacementResult;
use crate::replacement::replacement_type::ReplacementType;
use crate::trigger::TriggerHandler;

#[derive(Debug, Clone)]
pub struct CounterMapValue {
    pub source: Option<PlayerId>,
    pub counters: std::collections::BTreeMap<CounterType, i32>,
}

// ── ReplacementEvent ──────────────────────────────────────────────────────────

/// A game event that may be subject to one or more replacement effects.
///
/// Each variant carries the mutable parameters of the event so that a
/// replacement effect can modify them (e.g. reduce damage to 0, redirect a
/// zone move, etc.).
///
/// Mirrors the `runParams` map passed to `ReplacementHandler.run()` in Java,
/// but typed for safety.
#[derive(Debug, Clone)]
pub enum ReplacementEvent {
    /// A card is being drawn by a player.
    /// `extra_draws` is incremented by replacements (e.g. Alhammarret's Archive DrawTwo).
    /// `is_first_in_draw_step` is true for the first draw in the draw step (not extra draws).
    Draw {
        player: PlayerId,
        extra_draws: i32,
        is_first_in_draw_step: bool,
    },

    /// Damage is being dealt to a permanent.
    DamageToCard {
        target: CardId,
        amount: i32,
        /// The card dealing the damage, if known.
        source: Option<CardId>,
        /// Whether this is combat damage.
        is_combat: bool,
    },

    /// Damage is being dealt to a player.
    DamageToPlayer {
        target: PlayerId,
        amount: i32,
        /// The card dealing the damage, if known.
        source: Option<CardId>,
        /// Whether this is combat damage.
        is_combat: bool,
    },

    /// A permanent is being destroyed (lethal damage or destroy effect).
    Destroy { target: CardId },

    /// A card is moving between zones.
    Moved {
        card: CardId,
        origin: ZoneType,
        destination: ZoneType,
        /// True when this move originates from a discard action.
        /// Mirrors Java's `AbilityKey.Discard` in replacement params.
        is_discard: bool,
        counter_map: Option<Vec<CounterMapValue>>,
        counter_cause: Option<Box<crate::spellability::SpellAbility>>,
        counter_is_effect: bool,
        after_replacement_static_abilities: Vec<(CardId, Vec<String>)>,
    },

    /// A player is gaining life.
    GainLife { player: PlayerId, amount: i32 },

    /// Token(s) are being created.
    /// `is_effect` is `true` when created by a spell/ability effect, `false` for game rules.
    CreateToken {
        player: PlayerId,
        count: i32,
        is_effect: bool,
    },

    /// Counter(s) are being added to a permanent.
    /// `is_effect` is `true` when placed by a spell/ability, `false` for ETB keywords/game rules.
    AddCounter {
        target: GameEntity,
        source: Option<PlayerId>,
        counter_type: CounterType,
        count: i32,
        counter_map: Vec<CounterMapValue>,
        after_replacement_static_abilities: Vec<(CardId, Vec<String>)>,
        cause: Option<Box<crate::spellability::SpellAbility>>,
        is_effect: bool,
    },

    /// A player is losing the game.
    GameLoss {
        player: PlayerId,
        reason: GameLossReason,
    },

    /// A player is winning the game.
    GameWin { player: PlayerId },

    /// A spell is being countered.
    Counter { card: CardId },

    /// Mana is being produced (for doublers like Mirari's Wake, Nyxbloom Ancient).
    /// `mana` is the produced mana string (e.g. "G" or "U U") that may be modified.
    ProduceMana {
        source: CardId,
        activator: PlayerId,
        mana: String,
    },

    /// A permanent is being tapped.
    Tap { card: CardId },

    /// A permanent is being untapped.
    Untap {
        card: CardId,
        player: Option<PlayerId>,
    },

    /// Life is being reduced (distinct from damage).
    LifeReduced {
        player: PlayerId,
        amount: i32,
        is_damage: bool,
    },

    /// Counter(s) are being removed from a permanent.
    RemoveCounter {
        target: CardId,
        counter_type: CounterType,
        count: i32,
    },

    /// Damage has been dealt (post-damage).
    DealtDamage {
        target: CardId,
        amount: i32,
        source: Option<CardId>,
    },

    /// Multiple cards are being drawn.
    DrawCards { player: PlayerId, count: i32 },

    /// Cards are being milled.
    Mill { player: PlayerId, count: i32 },

    /// Life is being paid as a cost.
    PayLife { player: PlayerId, amount: i32 },

    /// A player is scrying.
    Scry { player: PlayerId, count: i32 },

    /// An aura/equipment is being attached.
    Attached { card: CardId, target: CardId },

    /// A phase is beginning.
    BeginPhase {
        player: PlayerId,
        phase: forge_foundation::PhaseType,
    },

    /// A turn is beginning.
    BeginTurn { player: PlayerId },

    /// A creature is exploring.
    Explore { card: CardId },

    /// Blockers are being declared.
    DeclareBlocker { player: PlayerId },

    /// Damage is being assigned before dealing.
    AssignDealDamage { card: CardId },

    /// A DFC is transforming.
    Transform { card: CardId },

    /// A face-down card is turning face up.
    TurnFaceUp { card: CardId },

    /// A spell is being copied.
    CopySpell { player: PlayerId, count: i32 },

    /// A player is proliferating.
    Proliferate { player: PlayerId, count: i32 },

    /// Cascade is triggering.
    Cascade { player: PlayerId },

    /// A player is learning.
    Learn { player: PlayerId },

    /// Mana is being lost.
    LoseMana { player: PlayerId },

    /// Dice are being rolled.
    RollDice {
        player: PlayerId,
        sides: i32,
        number: i32,
        ignore: i32,
        ignore_chosen: HashMap<PlayerId, i32>,
        dice_pt_exchanges: HashSet<CardId>,
    },

    /// The planar die is being rolled.
    RollPlanarDice { player: PlayerId },

    /// A planar dice result is being applied.
    PlanarDiceResult { player: PlayerId },

    /// A player is planeswalking.
    Planeswalk { player: PlayerId },

    /// A scheme is being set in motion.
    SetInMotion { player: PlayerId },

    /// A contraption is being assembled.
    AssembleContraption { player: PlayerId },
}

// ── ReplacementHandler struct ─────────────────────────────────────────────────

use crate::agent::PlayerAgent;

pub struct ReplacementRuntime<'a> {
    pub trigger_handler: &'a mut TriggerHandler,
    pub token_templates: &'a HashMap<String, Card>,
    pub token_art_variants: &'a HashMap<(String, String), usize>,
    pub token_fallback: &'a HashMap<String, String>,
    pub edition_dates: &'a HashMap<String, String>,
    pub mana_pools: &'a mut Vec<ManaPool>,
    pub rng: &'a mut dyn GameRng,
}

/// Struct-based replacement handler with loop prevention and optional agent access.
///
/// Mirrors Java `ReplacementHandler` class. The `has_run` set prevents infinite
/// loops when effects re-trigger themselves.
///
/// Usage:
/// - `ReplacementHandler::new().run(game, Some(agents), event)` — with agent choice
/// - `apply_replacements(game, event)` — free function wrapper (no agent, auto-selects first)
pub struct ReplacementHandler {
    /// Tracks (card_id, layer, effect_index) tuples that have already been applied
    /// during this handler invocation, to prevent infinite re-application.
    has_run: HashSet<(CardId, ReplacementLayer, usize)>,
}

impl Default for ReplacementHandler {
    fn default() -> Self {
        Self::new()
    }
}

impl ReplacementHandler {
    pub fn new() -> Self {
        Self {
            has_run: HashSet::new(),
        }
    }

    /// Apply all applicable replacement effects to a game event.
    ///
    /// Processes effects in CR 616 layer order:
    /// CantHappen → Control → Copy → Transform → Other.
    ///
    /// When `agents` is `Some` and multiple effects match in the same layer,
    /// the affected player's agent is asked to choose via
    /// `choose_single_replacement_effect()`.
    ///
    /// Mirrors Java `ReplacementHandler.run(ReplacementType, Map<AbilityKey,Object>)`.
    pub fn run(
        &mut self,
        game: &mut GameState,
        mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
        mut runtime: Option<&mut ReplacementRuntime<'_>>,
        event: &mut ReplacementEvent,
    ) -> ReplacementResult {
        for layer in [
            ReplacementLayer::CantHappen,
            ReplacementLayer::Control,
            ReplacementLayer::Copy,
            ReplacementLayer::Transform,
            ReplacementLayer::Other,
        ] {
            let result = self.run_layer(
                game,
                agents.as_deref_mut(),
                runtime.as_deref_mut(),
                event,
                layer,
            );
            match result {
                ReplacementResult::NotReplaced => continue,
                ReplacementResult::Updated => {
                    // Java preserves Updated unless a later replacement fully
                    // replaces the event during the re-run.
                    return match self.run(game, agents, runtime, event) {
                        ReplacementResult::NotReplaced | ReplacementResult::Updated => {
                            ReplacementResult::Updated
                        }
                        other => other,
                    };
                }
                other => return other,
            }
        }
        ReplacementResult::NotReplaced
    }

    /// Apply one CR 616 layer of replacement effects.
    fn run_layer(
        &mut self,
        game: &mut GameState,
        mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
        mut runtime: Option<&mut ReplacementRuntime<'_>>,
        event: &mut ReplacementEvent,
        layer: ReplacementLayer,
    ) -> ReplacementResult {
        let effects = collect_effects(game, event, layer);
        let mut declined_effects: HashSet<(CardId, usize)> = HashSet::new();

        if effects.is_empty() {
            return ReplacementResult::NotReplaced;
        }

        loop {
            let eligible: Vec<_> = effects
                .iter()
                .filter(|(card_id, _re, effect_idx)| {
                    !self.has_run.contains(&(*card_id, layer, *effect_idx))
                        && !declined_effects.contains(&(*card_id, *effect_idx))
                })
                .cloned()
                .collect();

            if eligible.is_empty() {
                return ReplacementResult::NotReplaced;
            }

            let chosen_idx = if !eligible.is_empty() && layer != ReplacementLayer::CantHappen {
                if let Some(agents) = agents.as_deref_mut() {
                    let descriptions: Vec<String> = eligible
                        .iter()
                        .map(|(card_id, re, _)| {
                            let host = game.card(*card_id);
                            let card_name = &host.card_name;
                            let desc = re.description(host, game);
                            format!("{card_name}: {desc}")
                        })
                        .collect();

                    let affected_player = affected_player_for_event(event, game);
                    let agent = &mut agents[affected_player.index()];
                    agent
                        .choose_single_replacement_effect(affected_player, &descriptions)
                        .min(eligible.len() - 1)
                } else {
                    0
                }
            } else {
                0
            };

            let (source_card_id, ref effect, effect_idx) = eligible[chosen_idx];
            self.has_run.insert((source_card_id, layer, effect_idx));
            let result = execute_effect(
                game,
                source_card_id,
                effect,
                event,
                agents.as_deref_mut(),
                runtime.as_deref_mut(),
            );
            if result == ReplacementResult::NotReplaced {
                self.has_run.remove(&(source_card_id, layer, effect_idx));
                declined_effects.insert((source_card_id, effect_idx));
                continue;
            }
            return result;
        }
    }
}

/// Determine which player is "affected" by the event (for choosing among effects).
fn affected_player_for_event(event: &ReplacementEvent, game: &GameState) -> PlayerId {
    match event {
        ReplacementEvent::Draw { player, .. } => *player,
        ReplacementEvent::DamageToCard { target, .. } => game.cards[target.index()].controller,
        ReplacementEvent::DamageToPlayer { target, .. } => *target,
        ReplacementEvent::Destroy { target } => game.cards[target.index()].controller,
        ReplacementEvent::Moved { card, .. } => game.cards[card.index()].controller,
        ReplacementEvent::GainLife { player, .. } => *player,
        ReplacementEvent::CreateToken { player, .. } => *player,
        ReplacementEvent::AddCounter { target, .. } => match target {
            GameEntity::Card(target) => game.cards[target.index()].controller,
            GameEntity::Player(target) => *target,
        },
        ReplacementEvent::GameLoss { player, .. } => *player,
        ReplacementEvent::GameWin { player } => *player,
        ReplacementEvent::Counter { card } => game.cards[card.index()].controller,
        ReplacementEvent::ProduceMana { activator, .. } => *activator,
        ReplacementEvent::Tap { card } => game.cards[card.index()].controller,
        ReplacementEvent::Untap { card, .. } => game.cards[card.index()].controller,
        ReplacementEvent::LifeReduced { player, .. } => *player,
        ReplacementEvent::RemoveCounter { target, .. } => game.cards[target.index()].controller,
        ReplacementEvent::DealtDamage { target, .. } => game.cards[target.index()].controller,
        ReplacementEvent::DrawCards { player, .. } => *player,
        ReplacementEvent::Mill { player, .. } => *player,
        ReplacementEvent::PayLife { player, .. } => *player,
        ReplacementEvent::Scry { player, .. } => *player,
        ReplacementEvent::Attached { card, .. } => game.cards[card.index()].controller,
        ReplacementEvent::BeginPhase { player, .. } => *player,
        ReplacementEvent::BeginTurn { player } => *player,
        ReplacementEvent::Explore { card } => game.cards[card.index()].controller,
        ReplacementEvent::DeclareBlocker { player } => *player,
        ReplacementEvent::AssignDealDamage { card } => game.cards[card.index()].controller,
        ReplacementEvent::Transform { card } => game.cards[card.index()].controller,
        ReplacementEvent::TurnFaceUp { card } => game.cards[card.index()].controller,
        ReplacementEvent::CopySpell { player, .. } => *player,
        ReplacementEvent::Proliferate { player, .. } => *player,
        ReplacementEvent::Cascade { player } => *player,
        ReplacementEvent::Learn { player } => *player,
        ReplacementEvent::LoseMana { player } => *player,
        ReplacementEvent::RollDice { player, .. } => *player,
        ReplacementEvent::RollPlanarDice { player } => *player,
        ReplacementEvent::PlanarDiceResult { player } => *player,
        ReplacementEvent::Planeswalk { player } => *player,
        ReplacementEvent::SetInMotion { player } => *player,
        ReplacementEvent::AssembleContraption { player } => *player,
    }
}

// ── Public free-function API (backward compatibility) ─────────────────────────

/// Apply all applicable replacement effects to a game event.
///
/// Free function wrapper — auto-selects first effect (no agent prompt).
/// Used by callers that don't have access to agents (e.g. `action.rs`).
///
/// Mirrors Java `ReplacementHandler.run(ReplacementType, Map<AbilityKey,Object>)`.
pub fn apply_replacements(game: &mut GameState, event: &mut ReplacementEvent) -> ReplacementResult {
    let mut handler = ReplacementHandler::new();
    handler.run(game, None, None, event)
}

/// Apply Moved replacement effects (Rest in Peace, Leyline of the Void) for a card
/// being moved to the Graveyard. Uses agents for proper RNG consumption when
/// multiple effects apply. Returns the final destination zone.
///
/// If `dest` is not `Graveyard`, returns `dest` unchanged (no replacement needed).
pub fn apply_moved_replacement(
    game: &mut GameState,
    card_id: CardId,
    dest: ZoneType,
    agents: Option<&mut [Box<dyn crate::agent::PlayerAgent>]>,
) -> ZoneType {
    if dest != ZoneType::Graveyard {
        return dest;
    }
    let src_zone = game.cards[card_id.index()].zone;
    let mut event = ReplacementEvent::Moved {
        card: card_id,
        origin: src_zone,
        destination: ZoneType::Graveyard,
        is_discard: false,
        counter_map: None,
        counter_cause: None,
        counter_is_effect: false,
        after_replacement_static_abilities: Vec::new(),
    };
    let mut handler = ReplacementHandler::new();
    handler.run(game, agents, None, &mut event);
    if let ReplacementEvent::Moved { destination, .. } = event {
        destination
    } else {
        ZoneType::Graveyard
    }
}

pub fn apply_replacements_with_agents(
    game: &mut GameState,
    agents: &mut [Box<dyn PlayerAgent>],
    event: &mut ReplacementEvent,
) -> ReplacementResult {
    let mut handler = ReplacementHandler::new();
    handler.run(game, Some(agents), None, event)
}

pub fn apply_replacements_with_agents_and_runtime(
    game: &mut GameState,
    agents: &mut [Box<dyn PlayerAgent>],
    runtime: &mut ReplacementRuntime<'_>,
    event: &mut ReplacementEvent,
) -> ReplacementResult {
    let mut handler = ReplacementHandler::new();
    handler.run(game, Some(agents), Some(runtime), event)
}

pub(crate) fn replacement_event_amount(event: &ReplacementEvent) -> Option<i32> {
    match event {
        ReplacementEvent::DamageToCard { amount, .. } => Some(*amount),
        ReplacementEvent::DamageToPlayer { amount, .. } => Some(*amount),
        ReplacementEvent::GainLife { amount, .. } => Some(*amount),
        ReplacementEvent::LifeReduced { amount, .. } => Some(*amount),
        ReplacementEvent::CreateToken { count, .. } => Some(*count),
        ReplacementEvent::AddCounter { count, .. } => Some(*count),
        ReplacementEvent::DrawCards { count, .. } => Some(*count),
        ReplacementEvent::Mill { count, .. } => Some(*count),
        ReplacementEvent::PayLife { amount, .. } => Some(*amount),
        ReplacementEvent::Scry { count, .. } => Some(*count),
        ReplacementEvent::CopySpell { count, .. } => Some(*count),
        ReplacementEvent::Proliferate { count, .. } => Some(*count),
        ReplacementEvent::RollDice { number, .. } => Some(*number),
        _ => None,
    }
}

pub(crate) fn set_replacement_event_amount(event: &mut ReplacementEvent, value: i32) -> bool {
    match event {
        ReplacementEvent::DamageToCard { amount, .. } => *amount = value.max(0),
        ReplacementEvent::DamageToPlayer { amount, .. } => *amount = value.max(0),
        ReplacementEvent::GainLife { amount, .. } => *amount = value.max(0),
        ReplacementEvent::LifeReduced { amount, .. } => *amount = value.max(0),
        ReplacementEvent::CreateToken { count, .. } => *count = value.max(0),
        ReplacementEvent::AddCounter { count, .. } => *count = value.max(0),
        ReplacementEvent::DrawCards { count, .. } => *count = value.max(0),
        ReplacementEvent::Mill { count, .. } => *count = value.max(0),
        ReplacementEvent::PayLife { amount, .. } => *amount = value.max(0),
        ReplacementEvent::Scry { count, .. } => *count = value.max(0),
        ReplacementEvent::CopySpell { count, .. } => *count = value.max(0),
        ReplacementEvent::Proliferate { count, .. } => *count = value.max(0),
        ReplacementEvent::RollDice { number, .. } => *number = value.max(0),
        _ => return false,
    }
    true
}

fn amount_after_math(mut amount: i32, ops: &str) -> i32 {
    if ops.is_empty() {
        return amount;
    }
    let parts: Vec<&str> = ops.split('.').collect();
    let op = parts.first().copied().unwrap_or("");
    let rhs = parts
        .get(1)
        .and_then(|value| value.parse::<i32>().ok())
        .unwrap_or(0);
    if op.contains("Plus") {
        amount += rhs;
    } else if op.contains("Minus") {
        amount -= rhs;
    } else if op.contains("Twice") {
        amount *= 2;
    } else if op.contains("Thrice") {
        amount *= 3;
    } else if op.contains("HalfUp") {
        amount = ((amount as f64) / 2.0).ceil() as i32;
    } else if op.contains("HalfDown") {
        amount = ((amount as f64) / 2.0).floor() as i32;
    }
    amount
}

pub(crate) fn resolve_replace_value(
    expr: &str,
    game: &GameState,
    source_card_id: CardId,
    event: &ReplacementEvent,
) -> Option<i32> {
    let expr = expr.trim();
    if let Ok(value) = expr.parse::<i32>() {
        return Some(value);
    }
    if let Some(svar) = game.card(source_card_id).svars.get(expr) {
        return resolve_replace_value(svar, game, source_card_id, event);
    }
    let rest = expr.strip_prefix("ReplaceCount$")?;
    let (field, ops) = rest.split_once('/').unwrap_or((rest, ""));
    let base = match field {
        "DamageAmount" | "LifeGained" | "Amount" | "Number" | "TokenNum" | "CounterNum" | "Num" => {
            replacement_event_amount(event)?
        }
        "Ignore" => match event {
            ReplacementEvent::RollDice { ignore, .. } => *ignore,
            _ => return None,
        },
        _ => return None,
    };
    Some(amount_after_math(base, ops))
}

pub(crate) fn execute_replace_with_numeric_update(
    effect: &ReplacementEffect,
    event: &mut ReplacementEvent,
    game: &GameState,
    source_card_id: CardId,
    var_name: &str,
) -> Option<ReplacementResult> {
    let chain = resolve_replace_with_chain(effect, game.card(source_card_id))?;
    execute_replace_effect_ir(&chain, event, game, source_card_id, Some(var_name))
}

pub(crate) fn execute_replace_effect_ir(
    chain: &ReplacementChainIr,
    event: &mut ReplacementEvent,
    game: &GameState,
    source_card_id: CardId,
    required_var_name: Option<&str>,
) -> Option<ReplacementResult> {
    match chain {
        ReplacementChainIr::ReplaceToken {
            token_type,
            amount_expr,
        } => execute_replace_token_chain(
            token_type.as_deref(),
            amount_expr.as_deref(),
            event,
            game,
            source_card_id,
        ),
        ReplacementChainIr::ReplaceCounter { amount_expr, .. } => {
            execute_replace_counter_chain(amount_expr, event, game, source_card_id)
        }
        ReplacementChainIr::ReplaceEffect {
            var_name,
            var_type,
            var_key,
            var_value,
            sub_ability,
        } => {
            let mut updated = false;
            if let Some(var_name) = var_name.as_deref() {
                if required_var_name.is_none_or(|required| required == var_name) {
                    match var_name {
                        "DicePTExchanges" => {
                            if var_type.as_deref() == Some("CardSet") {
                                if let Some(var_value) = var_value.as_deref() {
                                    if let Some(card_id) =
                                        resolve_replace_card_key(var_value, source_card_id)
                                    {
                                        if let ReplacementEvent::RollDice {
                                            dice_pt_exchanges,
                                            ..
                                        } = event
                                        {
                                            dice_pt_exchanges.insert(card_id);
                                            updated = true;
                                        }
                                    }
                                }
                            }
                        }
                        _ => {
                            if let Some(var_value) = var_value.as_deref() {
                                if let Some(value) =
                                    resolve_replace_value(var_value, game, source_card_id, event)
                                {
                                    match var_name {
                                        "Ignore" => {
                                            if let ReplacementEvent::RollDice { ignore, .. } = event
                                            {
                                                *ignore = value.max(0);
                                                updated = true;
                                            }
                                        }
                                        "IgnoreChosen" => {
                                            if var_type.as_deref() == Some("Map") {
                                                if let Some(var_key) = var_key.as_deref() {
                                                    if let Some(player) = resolve_replace_player_key(
                                                        var_key,
                                                        game,
                                                        source_card_id,
                                                        event,
                                                    ) {
                                                        if let ReplacementEvent::RollDice {
                                                            ignore_chosen,
                                                            ..
                                                        } = event
                                                        {
                                                            ignore_chosen
                                                                .insert(player, value.max(0));
                                                            updated = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        _ => {
                                            if set_replacement_event_amount(event, value) {
                                                updated = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if let Some(sub_ability) = sub_ability.as_deref() {
                updated |=
                    execute_replace_effect_ir(sub_ability, event, game, source_card_id, None)
                        .is_some();
            }

            updated.then_some(ReplacementResult::Updated)
        }
    }
}

/// Handle `DB$ ReplaceToken` SVars.
///
/// Mirrors Java `ReplaceTokenEffect.resolve()`.
/// - `Type$ Amount`: multiplies token count using `Amount$` param (default `Twice`).
fn execute_replace_token_chain(
    token_type: Option<&str>,
    amount_expr: Option<&str>,
    event: &mut ReplacementEvent,
    game: &GameState,
    source_card_id: CardId,
) -> Option<ReplacementResult> {
    let token_type = token_type.unwrap_or("Amount");
    match token_type {
        "Amount" => {
            // Get current count from event
            let current = replacement_event_amount(event)?;
            // Amount$ param, defaults to "Twice" per Java
            let amount_expr = amount_expr.unwrap_or("Twice");
            let new_value = do_x_math(current, amount_expr, game, source_card_id, event);
            set_replacement_event_amount(event, new_value);
            Some(ReplacementResult::Updated)
        }
        _ => {
            // Other types (AddToken, ReplaceToken, ReplaceController) not yet needed
            None
        }
    }
}

/// Handle `DB$ ReplaceCounter` SVars.
///
/// Mirrors Java `ReplaceCounterEffect.resolve()`.
/// Applies `Amount$` expression to the counter count.
fn execute_replace_counter_chain(
    amount_expr: &str,
    event: &mut ReplacementEvent,
    game: &GameState,
    source_card_id: CardId,
) -> Option<ReplacementResult> {
    // Ensure event has a valid amount before resolving
    let _current = replacement_event_amount(event)?;
    let value = resolve_replace_value(amount_expr, game, source_card_id, event)?;
    if value <= 0 {
        // Java removes the counter entry when value <= 0
        set_replacement_event_amount(event, 0);
    } else {
        set_replacement_event_amount(event, value);
    }
    Some(ReplacementResult::Updated)
}

/// Simple math evaluation mirroring Java `AbilityUtils.doXMath()`.
///
/// Handles common expressions: "Twice", "Thrice", "Half", integer literals,
/// and `Plus.N` / `Minus.N` style ops.
fn do_x_math(
    base: i32,
    expr: &str,
    game: &GameState,
    source_card_id: CardId,
    event: &ReplacementEvent,
) -> i32 {
    match expr {
        "Twice" => base * 2,
        "Thrice" => base * 3,
        "Half" => ((base as f64) / 2.0).ceil() as i32,
        _ => {
            // Try resolving as an SVar or ReplaceCount$ expression
            if let Some(val) = resolve_replace_value(expr, game, source_card_id, event) {
                val
            } else {
                base
            }
        }
    }
}

fn resolve_replace_player_key(
    expr: &str,
    game: &GameState,
    source_card_id: CardId,
    event: &ReplacementEvent,
) -> Option<PlayerId> {
    match expr.trim() {
        "You" => Some(game.card(source_card_id).controller),
        "Affected" => match event {
            ReplacementEvent::RollDice { player, .. } => Some(*player),
            _ => None,
        },
        "Opponent" => Some(game.opponent_of(game.card(source_card_id).controller)),
        _ => None,
    }
}

fn resolve_replace_card_key(expr: &str, source_card_id: CardId) -> Option<CardId> {
    match expr.trim() {
        "Self" => Some(source_card_id),
        _ => None,
    }
}

// ── Scan-parity helper functions ──────────────────────────────────────────────

/// Check if any `CantHappen`-layer replacement effect would prevent this event.
///
/// Walks all battlefield cards' replacement effects, filtering by the
/// `CantHappen` layer. Returns `true` if at least one effect matches.
///
/// Mirrors Java `ReplacementHandler.cantHappenCheck()`.
pub fn cant_happen_check(game: &GameState, event: &ReplacementEvent) -> bool {
    let effects = collect_effects(game, event, ReplacementLayer::CantHappen);
    !effects.is_empty()
}

/// Apply replacement effects specifically for damage events.
///
/// Delegates to `apply_replacements`. This is a convenience entry point
/// matching Java's batch-damage processing path in `ReplacementHandler`.
///
/// Mirrors Java `ReplacementHandler.runReplaceDamage()`.
pub fn run_replace_damage(game: &mut GameState, event: &mut ReplacementEvent) -> ReplacementResult {
    apply_replacements(game, event)
}

/// Parse a raw `R$` replacement-effect line. Re-export of
/// `replacement_effect::parse_replacement_effect` for scan parity.
///
/// Mirrors Java `ReplacementHandler.parseReplacement()`.
pub fn parse_replacement(raw: &str) -> Option<ReplacementEffect> {
    super::replacement_effect::parse_replacement_effect(raw)
}

/// Check if any `BeginPhase` replacement effect in the `Control` layer would
/// skip the given phase for the given player.
///
/// Walks all battlefield cards looking for matching `BeginPhase` effects
/// with `Layer$ Control` (or `CantHappen`) whose `ActivePhases$` includes
/// the target phase and whose `ValidPlayer$` matches the player.
///
/// Mirrors Java `ReplacementHandler.wouldPhaseBeSkipped()`.
pub fn would_phase_be_skipped(game: &GameState, player: PlayerId, phase: PhaseType) -> bool {
    for card in game.cards.iter() {
        if card.zone != ZoneType::Battlefield {
            continue;
        }
        for re in &card.replacement_effects {
            if re.event != ReplacementType::BeginPhase {
                continue;
            }
            // Must be Control or CantHappen layer to skip a phase
            if re.layer != ReplacementLayer::Control && re.layer != ReplacementLayer::CantHappen {
                continue;
            }
            // Check ActivePhases$ matches the target phase
            if !re.matches_phase(phase) {
                continue;
            }
            // Check ValidPlayer$ matches the player
            if let Some(vp) = re.ir.valid_player_selector.as_ref() {
                if !re.matches_compiled_valid_player(vp, player, card) {
                    continue;
                }
            }
            return true;
        }
    }
    false
}

/// Check if any `BeginTurn` replacement effect in the `Other` layer would
/// skip an extra turn for the given player.
///
/// Mirrors Java `ReplacementHandler.wouldExtraTurnBeSkipped()`.
pub fn would_extra_turn_be_skipped(game: &GameState, player: PlayerId) -> bool {
    for card in game.cards.iter() {
        if card.zone != ZoneType::Battlefield {
            continue;
        }
        for re in &card.replacement_effects {
            if re.event != ReplacementType::BeginTurn {
                continue;
            }
            if re.layer != ReplacementLayer::Other && re.layer != ReplacementLayer::CantHappen {
                continue;
            }
            // Check ValidPlayer$ matches the player
            if let Some(vp) = re.ir.valid_player_selector.as_ref() {
                if !re.matches_compiled_valid_player(vp, player, card) {
                    continue;
                }
            }
            return true;
        }
    }
    false
}

/// Walk all battlefield cards and collect `(card_id, effect_index)` pairs for
/// replacement effects matching the given event type and optional layer.
///
/// This is the scan-parity equivalent of Java's `ReplacementHandler.visit()`.
pub fn visit(
    game: &GameState,
    event: &ReplacementType,
    layer: Option<ReplacementLayer>,
) -> Vec<(CardId, usize)> {
    let mut result = Vec::new();
    let mut global_idx = 0usize;

    for (i, card) in game.cards.iter().enumerate() {
        let card_id = CardId(i as u32);
        for re in &card.replacement_effects {
            let current_idx = global_idx;
            global_idx += 1;

            // Layer filter
            if let Some(target_layer) = layer {
                if re.layer != target_layer {
                    continue;
                }
            }
            // Zone filter — effect must be active in the card's current zone
            if !re.active_in_zone(card.zone) {
                continue;
            }
            // Mode check — effect's event must match the requested event
            if !re.mode_check(event) {
                continue;
            }
            // has_run check (always false in our architecture)
            if re.has_run() {
                continue;
            }
            // Requirements check
            if !re.requirements_check(game, card) {
                continue;
            }

            result.push((card_id, current_idx));
        }
    }

    result
}

// ── Internal helpers ──────────────────────────────────────────────────────────

/// Collect all `(source_card_id, effect, effect_index)` triples that apply to `event` in `layer`.
///
/// Iterates over every card in the game and checks each of its replacement
/// effects.  Only effects whose source card is in an active zone are included.
///
/// The `effect_index` is a global unique index used for `has_run` tracking.
///
/// Mirrors `ReplacementHandler.getReplacementList()`.
fn collect_effects(
    game: &GameState,
    event: &ReplacementEvent,
    layer: ReplacementLayer,
) -> Vec<(CardId, ReplacementEffect, usize)> {
    let _perf_scope =
        crate::perf::ParamsLookupScopeGuard::enter(crate::perf::ParamsLookupScope::Replacement);
    use super::{
        replace_add_counter,
        // Format/mechanic-specific replacements
        replace_assemble_contraption,
        replace_assign_deal_damage,
        replace_attached,
        replace_begin_phase,
        replace_begin_turn,
        replace_cascade,
        replace_copy_spell,
        replace_counter,
        replace_damage,
        replace_dealt_damage,
        replace_declare_blocker,
        replace_destroy,
        replace_draw,
        replace_draw_cards,
        replace_explore,
        replace_gain_life,
        replace_game_loss,
        replace_game_win,
        replace_learn,
        replace_life_reduced,
        replace_lose_mana,
        replace_mill,
        replace_moved,
        replace_pay_life,
        replace_planar_dice_result,
        replace_planeswalk,
        replace_produce_mana,
        replace_proliferate,
        replace_remove_counter,
        replace_roll_dice,
        replace_roll_planar_dice,
        replace_scry,
        replace_set_in_motion,
        replace_tap,
        replace_token,
        replace_transform,
        replace_turn_face_up,
        replace_untap,
    };

    let mut result = Vec::new();
    for (i, card) in game.cards.iter().enumerate() {
        let card_id = CardId(i as u32);

        for (effect_idx_in_card, re) in card.replacement_effects.iter().enumerate() {
            let current_idx = effect_idx_in_card;
            // Layer filter.
            if re.layer != layer {
                continue;
            }
            // Zone filter — effect is only active when host is in a valid zone.
            let entering_self_counter = matches!(
                event,
                ReplacementEvent::Moved {
                    card: moved,
                    destination: ZoneType::Battlefield,
                    counter_map: Some(_),
                    ..
                } if *moved == card_id
                    && re.event == ReplacementType::AddCounter
                    && re.ir.valid_card_text.as_deref().is_some_and(|valid| valid.starts_with("Card.Self"))
            );
            if !re.active_in_zone(card.zone) && !entering_self_counter {
                continue;
            }
            if !re.requirements_check(game, card) {
                continue;
            }
            // Dispatch to per-type module for applicability check.
            let applies = match re.event {
                ReplacementType::DamageDone => replace_damage::can_replace(re, event, game, card),
                ReplacementType::Draw => replace_draw::can_replace(re, event, game, card),
                ReplacementType::Destroy => replace_destroy::can_replace(re, event, game, card),
                ReplacementType::Moved => replace_moved::can_replace(re, event, game, card),
                ReplacementType::GainLife => replace_gain_life::can_replace(re, event, game, card),
                ReplacementType::CreateToken => replace_token::can_replace(re, event, game, card),
                ReplacementType::AddCounter => {
                    replace_add_counter::can_replace(re, event, game, card)
                }
                ReplacementType::GameLoss => replace_game_loss::can_replace(re, event, game, card),
                ReplacementType::GameWin => replace_game_win::can_replace(re, event, game, card),
                ReplacementType::Counter => replace_counter::can_replace(re, event, game, card),
                ReplacementType::ProduceMana => {
                    replace_produce_mana::can_replace(re, event, game, card)
                }
                // Format/mechanic-specific replacements
                ReplacementType::DrawCards => {
                    replace_draw_cards::can_replace(re, event, game, card)
                }
                ReplacementType::AssembleContraption => {
                    replace_assemble_contraption::can_replace(re, event, game, card)
                }
                ReplacementType::AssignDealDamage => {
                    replace_assign_deal_damage::can_replace(re, event, game, card)
                }
                ReplacementType::Attached => replace_attached::can_replace(re, event, game, card),
                ReplacementType::BeginPhase => {
                    replace_begin_phase::can_replace(re, event, game, card)
                }
                ReplacementType::BeginTurn => {
                    replace_begin_turn::can_replace(re, event, game, card)
                }
                ReplacementType::Cascade => replace_cascade::can_replace(re, event, game, card),
                ReplacementType::CopySpell => {
                    replace_copy_spell::can_replace(re, event, game, card)
                }
                ReplacementType::DealtDamage => {
                    replace_dealt_damage::can_replace(re, event, game, card)
                }
                ReplacementType::DeclareBlocker => {
                    replace_declare_blocker::can_replace(re, event, game, card)
                }
                ReplacementType::Explore => replace_explore::can_replace(re, event, game, card),
                ReplacementType::Learn => replace_learn::can_replace(re, event, game, card),
                ReplacementType::LifeReduced => {
                    replace_life_reduced::can_replace(re, event, game, card)
                }
                ReplacementType::LoseMana => replace_lose_mana::can_replace(re, event, game, card),
                ReplacementType::Mill => replace_mill::can_replace(re, event, game, card),
                ReplacementType::PayLife => replace_pay_life::can_replace(re, event, game, card),
                ReplacementType::PlanarDiceResult => {
                    replace_planar_dice_result::can_replace(re, event, game, card)
                }
                ReplacementType::Planeswalk => {
                    replace_planeswalk::can_replace(re, event, game, card)
                }
                ReplacementType::Proliferate => {
                    replace_proliferate::can_replace(re, event, game, card)
                }
                ReplacementType::RemoveCounter => {
                    replace_remove_counter::can_replace(re, event, game, card)
                }
                ReplacementType::RollDice => replace_roll_dice::can_replace(re, event, game, card),
                ReplacementType::RollPlanarDice => {
                    replace_roll_planar_dice::can_replace(re, event, game, card)
                }
                ReplacementType::Scry => replace_scry::can_replace(re, event, game, card),
                ReplacementType::SetInMotion => {
                    replace_set_in_motion::can_replace(re, event, game, card)
                }
                ReplacementType::Tap => replace_tap::can_replace(re, event, game, card),
                ReplacementType::Transform => replace_transform::can_replace(re, event, game, card),
                ReplacementType::TurnFaceUp => {
                    replace_turn_face_up::can_replace(re, event, game, card)
                }
                ReplacementType::Untap => replace_untap::can_replace(re, event, game, card),
                ReplacementType::Other(_) => false,
            };

            if applies {
                result.push((card_id, re.clone(), current_idx));
            }
        }
    }

    result
}

/// Execute a single replacement effect, mutating the event parameters.
///
/// Dispatches to the per-type module's `execute()` function.
///
/// Mirrors `ReplacementHandler.executeReplacement()`.
fn execute_effect(
    game: &mut GameState,
    card_id: CardId,
    effect: &ReplacementEffect,
    event: &mut ReplacementEvent,
    mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
    runtime: Option<&mut ReplacementRuntime<'_>>,
) -> ReplacementResult {
    use super::{
        replace_add_counter,
        // Format/mechanic-specific replacements
        replace_assemble_contraption,
        replace_assign_deal_damage,
        replace_attached,
        replace_begin_phase,
        replace_begin_turn,
        replace_cascade,
        replace_copy_spell,
        replace_counter,
        replace_damage,
        replace_dealt_damage,
        replace_declare_blocker,
        replace_destroy,
        replace_draw,
        replace_draw_cards,
        replace_explore,
        replace_gain_life,
        replace_game_loss,
        replace_game_win,
        replace_learn,
        replace_life_reduced,
        replace_lose_mana,
        replace_mill,
        replace_moved,
        replace_pay_life,
        replace_planar_dice_result,
        replace_planeswalk,
        replace_produce_mana,
        replace_proliferate,
        replace_remove_counter,
        replace_roll_dice,
        replace_roll_planar_dice,
        replace_scry,
        replace_set_in_motion,
        replace_tap,
        replace_token,
        replace_transform,
        replace_turn_face_up,
        replace_untap,
    };

    if effect.ir.optional {
        let decider = optional_decider_for_effect(effect, game, card_id, event)
            .unwrap_or_else(|| affected_player_for_event(event, game));
        let host = game.card(card_id);
        let question = replacement_question(effect, host, game, event);
        let confirmed = if let Some(agents) = agents.as_deref_mut() {
            agents[decider.index()].confirm_replacement_effect(
                decider,
                &question,
                &effect.description(host, game),
                Some(card_id),
            )
        } else {
            true
        };
        if !confirmed {
            return ReplacementResult::NotReplaced;
        }
    }

    match effect.event {
        ReplacementType::DamageDone => replace_damage::execute(effect, event, game, card_id),
        ReplacementType::Draw => replace_draw::execute(effect, event, game, card_id),
        ReplacementType::Destroy => replace_destroy::execute(effect, event, game, card_id),
        ReplacementType::Moved => {
            replace_moved::execute(effect, event, game, card_id, agents, runtime)
        }
        ReplacementType::GainLife => replace_gain_life::execute(effect, event, game, card_id),
        ReplacementType::CreateToken => replace_token::execute(effect, event, game, card_id),
        ReplacementType::AddCounter => {
            replace_add_counter::execute(effect, event, game, card_id, agents)
        }
        ReplacementType::GameLoss => replace_game_loss::execute(effect, event, game, card_id),
        ReplacementType::GameWin => replace_game_win::execute(effect, event, game, card_id),
        ReplacementType::Counter => replace_counter::execute(effect, event, game, card_id),
        ReplacementType::ProduceMana => replace_produce_mana::execute(effect, event, game, card_id),
        // Format/mechanic-specific replacements
        ReplacementType::DrawCards => replace_draw_cards::execute(effect, event, game, card_id),
        ReplacementType::AssembleContraption => {
            replace_assemble_contraption::execute(effect, event, game, card_id)
        }
        ReplacementType::AssignDealDamage => {
            replace_assign_deal_damage::execute(effect, event, game, card_id)
        }
        ReplacementType::Attached => replace_attached::execute(effect, event, game, card_id),
        ReplacementType::BeginPhase => replace_begin_phase::execute(effect, event, game, card_id),
        ReplacementType::BeginTurn => replace_begin_turn::execute(effect, event, game, card_id),
        ReplacementType::Cascade => replace_cascade::execute(effect, event, game, card_id),
        ReplacementType::CopySpell => replace_copy_spell::execute(effect, event, game, card_id),
        ReplacementType::DealtDamage => replace_dealt_damage::execute(effect, event, game, card_id),
        ReplacementType::DeclareBlocker => {
            replace_declare_blocker::execute(effect, event, game, card_id)
        }
        ReplacementType::Explore => replace_explore::execute(effect, event, game, card_id),
        ReplacementType::Learn => replace_learn::execute(effect, event, game, card_id),
        ReplacementType::LifeReduced => replace_life_reduced::execute(effect, event, game, card_id),
        ReplacementType::LoseMana => replace_lose_mana::execute(effect, event, game, card_id),
        ReplacementType::Mill => replace_mill::execute(effect, event, game, card_id),
        ReplacementType::PayLife => replace_pay_life::execute(effect, event, game, card_id),
        ReplacementType::PlanarDiceResult => {
            replace_planar_dice_result::execute(effect, event, game, card_id)
        }
        ReplacementType::Planeswalk => replace_planeswalk::execute(effect, event, game, card_id),
        ReplacementType::Proliferate => replace_proliferate::execute(effect, event, game, card_id),
        ReplacementType::RemoveCounter => {
            replace_remove_counter::execute(effect, event, game, card_id)
        }
        ReplacementType::RollDice => replace_roll_dice::execute(effect, event, game, card_id),
        ReplacementType::RollPlanarDice => {
            replace_roll_planar_dice::execute(effect, event, game, card_id)
        }
        ReplacementType::Scry => replace_scry::execute(effect, event, game, card_id),
        ReplacementType::SetInMotion => {
            replace_set_in_motion::execute(effect, event, game, card_id)
        }
        ReplacementType::Tap => replace_tap::execute(effect, event, game, card_id),
        ReplacementType::Transform => replace_transform::execute(effect, event, game, card_id),
        ReplacementType::TurnFaceUp => replace_turn_face_up::execute(effect, event, game, card_id),
        ReplacementType::Untap => replace_untap::execute(effect, event, game, card_id),
        ReplacementType::Other(_) => ReplacementResult::NotReplaced,
    }
}

fn optional_decider_for_effect(
    effect: &ReplacementEffect,
    game: &GameState,
    source_card_id: CardId,
    event: &ReplacementEvent,
) -> Option<PlayerId> {
    let expr = effect.ir.optional_decider_text.as_deref()?.trim();
    match expr {
        "You" | "Controller" => Some(game.card(source_card_id).controller),
        "Owner" => Some(game.card(source_card_id).owner),
        "Affected" | "AffectedController" => Some(affected_player_for_event(event, game)),
        "Opponent" => Some(game.opponent_of(game.card(source_card_id).controller)),
        _ => None,
    }
}

fn replacement_question(
    effect: &ReplacementEffect,
    host: &crate::card::Card,
    game: &GameState,
    event: &ReplacementEvent,
) -> String {
    // `description(host, game)` already handles CARDNAME/NICKNAME + text changes.
    let desc = effect.description(host, game);
    match event {
        ReplacementEvent::Moved { card, .. } => format!(
            "Apply {} to {}?\n{}",
            host.card_name,
            game.card(*card).card_name,
            desc
        ),
        _ => format!("Apply {}?\n{}", host.card_name, desc),
    }
}

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

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

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

    // ── Test helpers ──────────────────────────────────────────────────────

    fn make_game() -> GameState {
        GameState::new(&["Alice", "Bob"], 20)
    }

    fn add_creature_with_abilities(
        game: &mut GameState,
        owner: PlayerId,
        name: &str,
        abilities: Vec<String>,
    ) -> CardId {
        let card = Card::new(
            CardId(0), // placeholder; create_card assigns real ID
            name.to_string(),
            owner,
            CardTypeLine::parse("Creature - Bear"),
            ManaCost::parse("1 G"),
            ColorSet::GREEN,
            Some(2),
            Some(2),
            vec![],
            abilities,
        );
        game.create_card(card)
    }

    fn put_on_battlefield(game: &mut GameState, card_id: CardId, owner: PlayerId) {
        game.move_card(card_id, ZoneType::Battlefield, owner);
    }

    struct ConfirmReplacementAgent {
        confirm: bool,
    }

    impl PlayerAgent for ConfirmReplacementAgent {
        fn mulligan_decision(
            &mut self,
            _player: PlayerId,
            _hand: &[CardId],
            _mulligan_count: u32,
        ) -> bool {
            true
        }

        fn choose_action(
            &mut self,
            player: PlayerId,
            action_space: Option<&crate::agent::PriorityActionSpace>,
            request_action_space: &mut dyn FnMut() -> crate::agent::PriorityActionSpace,
        ) -> crate::player::actions::PlayerAction {
            crate::player::actions::PlayerAction::PassPriority
        }

        fn choose_attackers(
            &mut self,
            _player: PlayerId,
            _available: &[CardId],
            _possible_defenders: &[crate::combat::DefenderId],
        ) -> Vec<(CardId, crate::combat::DefenderId)> {
            vec![]
        }

        fn choose_blockers(
            &mut self,
            _player: PlayerId,
            _attackers: &[CardId],
            _available_blockers: &[CardId],
            _max_blockers: Option<usize>,
        ) -> Vec<(CardId, CardId)> {
            vec![]
        }

        fn choose_target_player(
            &mut self,
            _player: PlayerId,
            valid: &[PlayerId],
            _sa: Option<&crate::spellability::SpellAbility>,
        ) -> Option<PlayerId> {
            valid.first().copied()
        }

        fn choose_target_card(
            &mut self,
            _player: PlayerId,
            valid: &[CardId],
            _sa: Option<&crate::spellability::SpellAbility>,
        ) -> Option<CardId> {
            valid.first().copied()
        }

        fn choose_target_any(
            &mut self,
            _player: PlayerId,
            valid_players: &[PlayerId],
            valid_cards: &[CardId],
            _sa: Option<&crate::spellability::SpellAbility>,
        ) -> crate::agent::TargetChoice {
            if let Some(player) = valid_players.first() {
                crate::agent::TargetChoice::Player(*player)
            } else if let Some(card) = valid_cards.first() {
                crate::agent::TargetChoice::Card(*card)
            } else {
                crate::agent::TargetChoice::None
            }
        }

        fn choose_land_or_spell(&mut self, _player: PlayerId) -> Option<bool> {
            Some(true)
        }

        fn confirm_replacement_effect(
            &mut self,
            _player: PlayerId,
            _question: &str,
            _effect_description: &str,
            _source: Option<crate::ids::CardId>,
        ) -> bool {
            self.confirm
        }

        fn choose_targets_for(
            &mut self,
            _sa: &mut crate::spellability::SpellAbility,
            _game: &GameState,
            _mana_pools: &[ManaPool],
        ) -> bool {
            false
        }
    }

    // ── Draw replacement tests ────────────────────────────────────────────

    #[test]
    fn draw_skip_for_controller() {
        let mut game = make_game();
        let alice = PlayerId(0);
        // Card with "skip your draw step" effect.
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "SkipDraw",
            vec!["R$ Event$ Draw | ValidPlayer$ You | Prevent$ True".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        let mut event = ReplacementEvent::Draw {
            player: alice,
            extra_draws: 0,
            is_first_in_draw_step: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Skipped);
    }

    #[test]
    fn draw_not_skipped_for_opponent() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let bob = PlayerId(1);
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "SkipDraw",
            vec!["R$ Event$ Draw | ValidPlayer$ You | Prevent$ True".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        // Bob's draw is not affected by Alice's effect.
        let mut event = ReplacementEvent::Draw {
            player: bob,
            extra_draws: 0,
            is_first_in_draw_step: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::NotReplaced);
    }

    #[test]
    fn draw_not_applied_when_card_not_on_battlefield() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "SkipDraw",
            vec![
                "R$ Event$ Draw | ActiveZones$ Battlefield | ValidPlayer$ You | Prevent$ True"
                    .to_string(),
            ],
        );
        // Card stays in hand, not battlefield.
        game.move_card(cid, ZoneType::Hand, alice);

        let mut event = ReplacementEvent::Draw {
            player: alice,
            extra_draws: 0,
            is_first_in_draw_step: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::NotReplaced);
    }

    // ── Damage prevention tests ───────────────────────────────────────────

    #[test]
    fn damage_to_player_prevented() {
        let mut game = make_game();
        let alice = PlayerId(0);
        // "Prevent all damage dealt to you."
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Shield",
            vec!["R$ Event$ DamageDone | ValidTarget$ Player | Prevent$ True".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        let mut event = ReplacementEvent::DamageToPlayer {
            target: alice,
            amount: 5,
            source: None,
            is_combat: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Prevented);
        // Amount should be zeroed out.
        if let ReplacementEvent::DamageToPlayer { amount, .. } = event {
            assert_eq!(amount, 0);
        } else {
            panic!("unexpected event type");
        }
    }

    #[test]
    fn damage_zero_not_replaced() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Shield",
            vec!["R$ Event$ DamageDone | ValidTarget$ Player | Prevent$ True".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        // Zero damage — effect should not apply.
        let mut event = ReplacementEvent::DamageToPlayer {
            target: alice,
            amount: 0,
            source: None,
            is_combat: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::NotReplaced);
    }

    #[test]
    fn damage_to_card_prevented() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let shield = add_creature_with_abilities(
            &mut game,
            alice,
            "Shield",
            vec!["R$ Event$ DamageDone | ValidTarget$ Card | Prevent$ True".to_string()],
        );
        put_on_battlefield(&mut game, shield, alice);

        let target_creature = add_creature_with_abilities(&mut game, alice, "Target", vec![]);
        put_on_battlefield(&mut game, target_creature, alice);

        let mut event = ReplacementEvent::DamageToCard {
            target: target_creature,
            amount: 3,
            source: None,
            is_combat: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Prevented);
        if let ReplacementEvent::DamageToCard { amount, .. } = event {
            assert_eq!(amount, 0);
        } else {
            panic!("unexpected event type");
        }
    }

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

        let replacer = add_creature_with_abilities(
            &mut game,
            alice,
            "Boss",
            vec![
                "R$ Event$ DamageDone | ActiveZones$ Battlefield | ValidSource$ Card.YouCtrl | ValidTarget$ Player.Opponent | ReplaceWith$ DmgPlus".to_string(),
            ],
        );
        game.card_mut(replacer).set_s_var(
            "DmgPlus",
            "DB$ ReplaceEffect | VarName$ DamageAmount | VarValue$ ReplaceCount$DamageAmount/Plus.1",
        );
        put_on_battlefield(&mut game, replacer, alice);

        let source = add_creature_with_abilities(&mut game, alice, "Source", vec![]);
        put_on_battlefield(&mut game, source, alice);

        let mut event = ReplacementEvent::DamageToPlayer {
            target: bob,
            amount: 2,
            source: Some(source),
            is_combat: false,
        };
        let _ = apply_replacements(&mut game, &mut event);
        if let ReplacementEvent::DamageToPlayer { amount, .. } = event {
            assert_eq!(amount, 3);
        } else {
            panic!("unexpected event type");
        }
    }

    #[test]
    fn damage_replace_with_respects_max_speed() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let bob = PlayerId(1);
        game.player_mut(alice).speed = 4;

        let replacer = add_creature_with_abilities(
            &mut game,
            alice,
            "Far Fortune",
            vec![
                "R$ Event$ DamageDone | MaxSpeed$ True | ActiveZones$ Battlefield | ValidSource$ Card.YouCtrl | ValidTarget$ Player.Opponent | ReplaceWith$ DmgPlus".to_string(),
            ],
        );
        game.card_mut(replacer).set_s_var(
            "DmgPlus",
            "DB$ ReplaceEffect | VarName$ DamageAmount | VarValue$ ReplaceCount$DamageAmount/Plus.1",
        );
        put_on_battlefield(&mut game, replacer, alice);

        let source = add_creature_with_abilities(&mut game, alice, "Source", vec![]);
        put_on_battlefield(&mut game, source, alice);

        let mut event = ReplacementEvent::DamageToPlayer {
            target: bob,
            amount: 1,
            source: Some(source),
            is_combat: false,
        };
        let _ = apply_replacements(&mut game, &mut event);
        if let ReplacementEvent::DamageToPlayer { amount, .. } = event {
            assert_eq!(amount, 2);
        } else {
            panic!("unexpected event type");
        }
    }

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

        let replacer = add_creature_with_abilities(
            &mut game,
            alice,
            "Barbarian Class",
            vec![
                "R$ Event$ RollDice | ActiveZones$ Battlefield | ValidPlayer$ You | ReplaceWith$ PlusRoll".to_string(),
            ],
        );
        game.card_mut(replacer).set_s_var(
            "PlusRoll",
            "DB$ ReplaceEffect | VarName$ Number | VarValue$ ReplaceCount$Number/Plus.1 | SubAbility$ IgnoreLowest",
        );
        game.card_mut(replacer).set_s_var(
            "IgnoreLowest",
            "DB$ ReplaceEffect | VarName$ Ignore | VarValue$ ReplaceCount$Ignore/Plus.1",
        );
        put_on_battlefield(&mut game, replacer, alice);

        let mut event = ReplacementEvent::RollDice {
            player: alice,
            sides: 20,
            number: 1,
            ignore: 0,
            ignore_chosen: HashMap::new(),
            dice_pt_exchanges: HashSet::new(),
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Updated);
        if let ReplacementEvent::RollDice { number, ignore, .. } = event {
            assert_eq!(number, 2);
            assert_eq!(ignore, 1);
        } else {
            panic!("unexpected event type");
        }
    }

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

        let replacer = add_creature_with_abilities(
            &mut game,
            alice,
            "Bamboozling Beeble",
            vec![
                "R$ Event$ RollDice | ActiveZones$ Battlefield | ValidPlayer$ You | ReplaceWith$ RigRoll".to_string(),
            ],
        );
        game.card_mut(replacer).set_s_var(
            "RigRoll",
            "DB$ ReplaceEffect | VarName$ IgnoreChosen | VarType$ Map | VarKey$ You | VarValue$ 1",
        );
        put_on_battlefield(&mut game, replacer, alice);

        let mut event = ReplacementEvent::RollDice {
            player: alice,
            sides: 6,
            number: 2,
            ignore: 0,
            ignore_chosen: HashMap::new(),
            dice_pt_exchanges: HashSet::new(),
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Updated);
        if let ReplacementEvent::RollDice { ignore_chosen, .. } = event {
            assert_eq!(ignore_chosen.get(&alice), Some(&1));
        } else {
            panic!("unexpected event type");
        }
    }

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

        let replacer = add_creature_with_abilities(
            &mut game,
            alice,
            "Vedalken Squirrel-Whacker",
            vec![
                "R$ Event$ RollDice | ActiveZones$ Battlefield | ValidPlayer$ You | ValidSides$ 6 | ReplaceWith$ SwapRoll".to_string(),
            ],
        );
        game.card_mut(replacer).set_s_var(
            "SwapRoll",
            "DB$ ReplaceEffect | VarName$ DicePTExchanges | VarType$ CardSet | VarValue$ Self",
        );
        put_on_battlefield(&mut game, replacer, alice);

        let mut event = ReplacementEvent::RollDice {
            player: alice,
            sides: 6,
            number: 2,
            ignore: 0,
            ignore_chosen: HashMap::new(),
            dice_pt_exchanges: HashSet::new(),
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Updated);
        if let ReplacementEvent::RollDice {
            dice_pt_exchanges, ..
        } = event
        {
            assert!(dice_pt_exchanges.contains(&replacer));
        } else {
            panic!("unexpected event type");
        }
    }

    // ── Destroy replacement tests ─────────────────────────────────────────

    #[test]
    fn indestructible_destroy_replaced() {
        let mut game = make_game();
        let alice = PlayerId(0);
        // Indestructible: "If ~ would be destroyed, instead it isn't."
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Indestructible Bear",
            vec!["R$ Event$ Destroy | ValidCard$ Card.Self".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        let mut event = ReplacementEvent::Destroy { target: cid };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Replaced);
    }

    #[test]
    fn destroy_not_replaced_for_other_card() {
        let mut game = make_game();
        let alice = PlayerId(0);
        // Indestructible creature — protects only itself.
        let indestructible = add_creature_with_abilities(
            &mut game,
            alice,
            "Indestructible Bear",
            vec!["R$ Event$ Destroy | ValidCard$ Card.Self".to_string()],
        );
        let other = add_creature_with_abilities(&mut game, alice, "Mortal Bear", vec![]);
        put_on_battlefield(&mut game, indestructible, alice);
        put_on_battlefield(&mut game, other, alice);

        let mut event = ReplacementEvent::Destroy { target: other };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::NotReplaced);
    }

    // ── Moved replacement tests ───────────────────────────────────────────

    #[test]
    fn moved_destination_updated_to_exile() {
        let mut game = make_game();
        let alice = PlayerId(0);
        // "If ~ would be put into a graveyard from the battlefield, exile it instead."
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Exile Bear",
            vec!["R$ Event$ Moved | Destination$ Graveyard | Origin$ Battlefield | ValidCard$ Card.Self | NewDestination$ Exile".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        let mut event = ReplacementEvent::Moved {
            card: cid,
            origin: ZoneType::Battlefield,
            destination: ZoneType::Graveyard,
            is_discard: false,
            counter_map: None,
            counter_cause: None,
            counter_is_effect: false,
            after_replacement_static_abilities: Vec::new(),
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::Updated);
        if let ReplacementEvent::Moved { destination, .. } = event {
            assert_eq!(destination, ZoneType::Exile);
        } else {
            panic!("unexpected event type");
        }
    }

    #[test]
    fn moved_not_replaced_wrong_origin() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Exile Bear",
            vec!["R$ Event$ Moved | Destination$ Graveyard | Origin$ Battlefield | ValidCard$ Card.Self | NewDestination$ Exile".to_string()],
        );
        put_on_battlefield(&mut game, cid, alice);

        // Card moving from Hand → Graveyard: Origin doesn't match Battlefield.
        let mut event = ReplacementEvent::Moved {
            card: cid,
            origin: ZoneType::Hand,
            destination: ZoneType::Graveyard,
            is_discard: false,
            counter_map: None,
            counter_cause: None,
            counter_is_effect: false,
            after_replacement_static_abilities: Vec::new(),
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::NotReplaced);
    }

    #[test]
    fn declined_optional_replacement_falls_through_to_next_candidate() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Optional Bear",
            vec![
                "R$ Event$ Moved | Destination$ Graveyard | Origin$ Battlefield | ValidCard$ Card.Self | Optional$ True | OptionalDecider$ You | NewDestination$ Command".to_string(),
                "R$ Event$ Moved | Destination$ Graveyard | Origin$ Battlefield | ValidCard$ Card.Self | NewDestination$ Exile".to_string(),
            ],
        );
        put_on_battlefield(&mut game, cid, alice);

        let mut agents: Vec<Box<dyn PlayerAgent>> = vec![
            Box::new(ConfirmReplacementAgent { confirm: false }),
            Box::new(ConfirmReplacementAgent { confirm: false }),
        ];
        let mut event = ReplacementEvent::Moved {
            card: cid,
            origin: ZoneType::Battlefield,
            destination: ZoneType::Graveyard,
            is_discard: false,
            counter_map: None,
            counter_cause: None,
            counter_is_effect: false,
            after_replacement_static_abilities: Vec::new(),
        };
        let result = apply_replacements_with_agents(&mut game, agents.as_mut_slice(), &mut event);
        assert_eq!(result, ReplacementResult::Updated);
        if let ReplacementEvent::Moved { destination, .. } = event {
            assert_eq!(destination, ZoneType::Exile);
        } else {
            panic!("unexpected event type");
        }
    }

    #[test]
    fn accepted_optional_replacement_updates_destination() {
        let mut game = make_game();
        let alice = PlayerId(0);
        let cid = add_creature_with_abilities(
            &mut game,
            alice,
            "Optional Bear",
            vec![
                "R$ Event$ Moved | Destination$ Graveyard | Origin$ Battlefield | ValidCard$ Card.Self | Optional$ True | OptionalDecider$ You | NewDestination$ Command".to_string(),
            ],
        );
        put_on_battlefield(&mut game, cid, alice);

        let mut agents: Vec<Box<dyn PlayerAgent>> = vec![
            Box::new(ConfirmReplacementAgent { confirm: true }),
            Box::new(ConfirmReplacementAgent { confirm: true }),
        ];
        let mut event = ReplacementEvent::Moved {
            card: cid,
            origin: ZoneType::Battlefield,
            destination: ZoneType::Graveyard,
            is_discard: false,
            counter_map: None,
            counter_cause: None,
            counter_is_effect: false,
            after_replacement_static_abilities: Vec::new(),
        };
        let result = apply_replacements_with_agents(&mut game, agents.as_mut_slice(), &mut event);
        assert_eq!(result, ReplacementResult::Updated);
        if let ReplacementEvent::Moved { destination, .. } = event {
            assert_eq!(destination, ZoneType::Command);
        } else {
            panic!("unexpected event type");
        }
    }

    // ── No effects test ───────────────────────────────────────────────────

    #[test]
    fn no_effects_returns_not_replaced() {
        let mut game = make_game();
        let mut event = ReplacementEvent::Draw {
            player: PlayerId(0),
            extra_draws: 0,
            is_first_in_draw_step: false,
        };
        let result = apply_replacements(&mut game, &mut event);
        assert_eq!(result, ReplacementResult::NotReplaced);
    }
}