ftui-runtime 0.4.0

Elm-style runtime loop and subscriptions for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Input macro recording and playback.
//!
//! Record terminal input events with timing information for deterministic
//! replay through the [`ProgramSimulator`](crate::simulator::ProgramSimulator).
//!
//! # Example
//!
//! ```ignore
//! use ftui_runtime::input_macro::{InputMacro, MacroRecorder, MacroPlayer};
//! use ftui_runtime::simulator::ProgramSimulator;
//! use ftui_core::event::Event;
//! use std::time::Duration;
//!
//! // Record events
//! let mut recorder = MacroRecorder::new("test_flow");
//! recorder.record_event(some_event.clone());
//! // ... time passes ...
//! recorder.record_event(another_event.clone());
//! let macro_recording = recorder.finish();
//!
//! // Replay through simulator
//! let mut sim = ProgramSimulator::new(my_model);
//! sim.init();
//! let mut player = MacroPlayer::new(&macro_recording);
//! player.replay_all(&mut sim);
//! ```

use ftui_core::event::Event;
use web_time::{Duration, Instant};

/// A recorded input event with timing relative to recording start.
#[derive(Debug, Clone)]
pub struct TimedEvent {
    /// The recorded event.
    pub event: Event,
    /// Delay from the previous event (or from recording start for the first event).
    pub delay: Duration,
}

impl TimedEvent {
    /// Create a new timed event with the given delay.
    pub fn new(event: Event, delay: Duration) -> Self {
        Self { event, delay }
    }

    /// Create a timed event with zero delay.
    pub fn immediate(event: Event) -> Self {
        Self {
            event,
            delay: Duration::ZERO,
        }
    }
}

/// Metadata about a recorded macro.
#[derive(Debug, Clone)]
pub struct MacroMetadata {
    /// Human-readable name for this macro.
    pub name: String,
    /// Terminal size at recording time.
    pub terminal_size: (u16, u16),
    /// Total duration of the recording.
    pub total_duration: Duration,
}

/// A recorded sequence of input events with timing.
///
/// An `InputMacro` captures events and their relative timing so they can
/// be replayed deterministically through a [`ProgramSimulator`](crate::simulator::ProgramSimulator).
#[derive(Debug, Clone)]
pub struct InputMacro {
    /// The recorded events with timing.
    events: Vec<TimedEvent>,
    /// Recording metadata.
    metadata: MacroMetadata,
}

impl InputMacro {
    /// Create a new macro from events and metadata.
    pub fn new(events: Vec<TimedEvent>, metadata: MacroMetadata) -> Self {
        Self { events, metadata }
    }

    /// Create a macro from events with no timing (all zero delay).
    ///
    /// Useful for building test macros programmatically.
    pub fn from_events(name: impl Into<String>, events: Vec<Event>) -> Self {
        let timed: Vec<TimedEvent> = events.into_iter().map(TimedEvent::immediate).collect();
        Self {
            metadata: MacroMetadata {
                name: name.into(),
                terminal_size: (80, 24),
                total_duration: Duration::ZERO,
            },
            events: timed,
        }
    }

    /// Get the recorded events.
    pub fn events(&self) -> &[TimedEvent] {
        &self.events
    }

    /// Get the metadata.
    #[inline]
    pub fn metadata(&self) -> &MacroMetadata {
        &self.metadata
    }

    /// Get the number of recorded events.
    #[inline]
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Check if the macro has no events.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Get the total duration of the recording.
    #[inline]
    pub fn total_duration(&self) -> Duration {
        self.metadata.total_duration
    }

    /// Extract just the events (without timing) in order.
    pub fn bare_events(&self) -> Vec<Event> {
        self.events.iter().map(|te| te.event.clone()).collect()
    }

    /// Replay this macro through a simulator, honoring recorded delays.
    pub fn replay_with_timing<M: crate::program::Model>(
        &self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
    ) {
        let mut player = MacroPlayer::new(self);
        player.replay_with_timing(sim);
    }

    /// Replay this macro through a simulator with a custom sleep function.
    ///
    /// Useful for tests that want deterministic timing without wall-clock sleep.
    pub fn replay_with_sleeper<M, F>(
        &self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
        sleep: F,
    ) where
        M: crate::program::Model,
        F: FnMut(Duration),
    {
        let mut player = MacroPlayer::new(self);
        player.replay_with_sleeper(sim, sleep);
    }
}

/// Records input events with timing into an [`InputMacro`].
///
/// Call [`record_event`](Self::record_event) for each event, then
/// [`finish`](Self::finish) to produce the final macro.
pub struct MacroRecorder {
    name: String,
    terminal_size: (u16, u16),
    events: Vec<TimedEvent>,
    last_event_time: Instant,
    recorded_duration: Duration,
}

impl MacroRecorder {
    /// Start a new recording session.
    pub fn new(name: impl Into<String>) -> Self {
        let now = Instant::now();
        Self {
            name: name.into(),
            terminal_size: (80, 24),
            events: Vec::new(),
            last_event_time: now,
            recorded_duration: Duration::ZERO,
        }
    }

    /// Set the terminal size metadata.
    #[must_use]
    pub fn with_terminal_size(mut self, width: u16, height: u16) -> Self {
        self.terminal_size = (width, height);
        self
    }

    /// Record an event at the current time.
    ///
    /// The delay is measured from the previous event (or recording start).
    pub fn record_event(&mut self, event: Event) {
        let now = Instant::now();
        let delay = now.saturating_duration_since(self.last_event_time);
        #[cfg(feature = "tracing")]
        tracing::debug!(event = ?event, delay = ?delay, "macro record event");
        self.events.push(TimedEvent::new(event, delay));
        self.recorded_duration = self.recorded_duration.saturating_add(delay);
        self.last_event_time = now;
    }

    /// Record an event with an explicit delay from the previous event.
    pub fn record_event_with_delay(&mut self, event: Event, delay: Duration) {
        #[cfg(feature = "tracing")]
        tracing::debug!(event = ?event, delay = ?delay, "macro record event");
        self.events.push(TimedEvent::new(event, delay));
        self.recorded_duration = self.recorded_duration.saturating_add(delay);
        // Advance the synthetic clock when representable. Overflow should not
        // make explicit-delay recording panic; the accumulated duration above
        // remains authoritative.
        self.last_event_time = self
            .last_event_time
            .checked_add(delay)
            .unwrap_or_else(Instant::now);
    }

    /// Get the number of events recorded so far.
    pub fn event_count(&self) -> usize {
        self.events.len()
    }

    /// Finish recording and produce the macro.
    pub fn finish(self) -> InputMacro {
        InputMacro {
            events: self.events,
            metadata: MacroMetadata {
                name: self.name,
                terminal_size: self.terminal_size,
                total_duration: self.recorded_duration,
            },
        }
    }
}

/// Replays an [`InputMacro`] through a [`ProgramSimulator`].
///
/// Events are injected in order. Timing information is available
/// for inspection but does not cause real delays (the simulator
/// is deterministic and instant).
pub struct MacroPlayer<'a> {
    input_macro: &'a InputMacro,
    position: usize,
    elapsed: Duration,
}

impl<'a> MacroPlayer<'a> {
    /// Create a player for the given macro.
    pub fn new(input_macro: &'a InputMacro) -> Self {
        Self {
            input_macro,
            position: 0,
            elapsed: Duration::ZERO,
        }
    }

    /// Get current playback position (event index).
    pub fn position(&self) -> usize {
        self.position
    }

    /// Get elapsed virtual time.
    pub fn elapsed(&self) -> Duration {
        self.elapsed
    }

    /// Check if playback is complete.
    pub fn is_done(&self) -> bool {
        self.position >= self.input_macro.len()
    }

    /// Get the number of remaining events.
    pub fn remaining(&self) -> usize {
        self.input_macro.len().saturating_sub(self.position)
    }

    /// Step one event, injecting it into the simulator.
    ///
    /// Returns `true` if an event was played, `false` if playback is complete.
    pub fn step<M: crate::program::Model>(
        &mut self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
    ) -> bool {
        if self.is_done() {
            return false;
        }

        let timed = &self.input_macro.events[self.position];
        #[cfg(feature = "tracing")]
        tracing::debug!(event = ?timed.event, delay = ?timed.delay, "macro playback event");
        self.elapsed = self.elapsed.saturating_add(timed.delay);
        sim.inject_events(std::slice::from_ref(&timed.event));
        self.position += 1;
        true
    }

    /// Replay all remaining events into the simulator.
    ///
    /// Stops early if the simulator quits.
    pub fn replay_all<M: crate::program::Model>(
        &mut self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
    ) {
        while !self.is_done() && sim.is_running() {
            self.step(sim);
        }
    }

    /// Replay all remaining events, honoring recorded delays.
    ///
    /// This uses real wall-clock sleeping for each recorded delay before
    /// injecting the event. Stops early if the simulator quits.
    pub fn replay_with_timing<M: crate::program::Model>(
        &mut self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
    ) {
        self.replay_with_sleeper(sim, std::thread::sleep);
    }

    /// Replay all remaining events with a custom sleep function.
    ///
    /// Useful for tests that want to avoid real sleeping while still verifying
    /// the delay schedule.
    pub fn replay_with_sleeper<M, F>(
        &mut self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
        mut sleep: F,
    ) where
        M: crate::program::Model,
        F: FnMut(Duration),
    {
        while !self.is_done() && sim.is_running() {
            let timed = &self.input_macro.events[self.position];
            if timed.delay > Duration::ZERO {
                sleep(timed.delay);
            }
            self.step(sim);
        }
    }

    /// Replay events up to the given virtual time.
    ///
    /// Only events whose cumulative delay is within `until` are played.
    pub fn replay_until<M: crate::program::Model>(
        &mut self,
        sim: &mut crate::simulator::ProgramSimulator<M>,
        until: Duration,
    ) {
        while !self.is_done() && sim.is_running() {
            let timed = &self.input_macro.events[self.position];
            let next_elapsed = self.elapsed.saturating_add(timed.delay);
            if next_elapsed > until {
                break;
            }
            self.step(sim);
        }
    }

    /// Reset playback to the beginning.
    pub fn reset(&mut self) {
        self.position = 0;
        self.elapsed = Duration::ZERO;
    }
}

// ---------------------------------------------------------------------------
// MacroPlayback – deterministic scheduler for live playback
// ---------------------------------------------------------------------------

/// Deterministic playback scheduler with speed and looping controls.
///
/// Invariants:
/// - Event order is preserved.
/// - `elapsed` is monotonic for a given `advance` sequence.
/// - No events are emitted without their cumulative delay being satisfied.
///
/// Failure modes:
/// - If total duration is zero and looping is enabled, looping is ignored to
///   avoid infinite emission within a single `advance` call.
#[derive(Debug, Clone)]
pub struct MacroPlayback {
    input_macro: InputMacro,
    position: usize,
    elapsed: Duration,
    next_due: Duration,
    speed: f64,
    looping: bool,
    start_logged: bool,
    stop_logged: bool,
    error_logged: bool,
}

/// Safety cap to prevent pathological looping replays from monopolizing a
/// frame when elapsed time spikes (e.g. host clock jumps / extreme speed).
const MAX_DUE_EVENTS_PER_ADVANCE: usize = 4096;

impl MacroPlayback {
    /// Create a new playback scheduler for the given macro.
    pub fn new(input_macro: InputMacro) -> Self {
        let next_due = input_macro
            .events()
            .first()
            .map(|e| e.delay)
            .unwrap_or(Duration::ZERO);
        Self {
            input_macro,
            position: 0,
            elapsed: Duration::ZERO,
            next_due,
            speed: 1.0,
            looping: false,
            start_logged: false,
            stop_logged: false,
            error_logged: false,
        }
    }

    /// Set playback speed (must be finite and positive).
    pub fn set_speed(&mut self, speed: f64) {
        self.speed = normalize_speed(speed);
    }

    /// Fluent speed setter.
    #[must_use]
    pub fn with_speed(mut self, speed: f64) -> Self {
        self.set_speed(speed);
        self
    }

    /// Enable or disable looping.
    pub fn set_looping(&mut self, looping: bool) {
        self.looping = looping;
    }

    /// Fluent looping setter.
    #[must_use]
    pub fn with_looping(mut self, looping: bool) -> Self {
        self.set_looping(looping);
        self
    }

    /// Get the current playback speed.
    pub fn speed(&self) -> f64 {
        self.speed
    }

    /// Get current playback position (event index).
    pub fn position(&self) -> usize {
        self.position
    }

    /// Get elapsed virtual time.
    pub fn elapsed(&self) -> Duration {
        self.elapsed
    }

    /// Check if playback is complete (non-looping).
    pub fn is_done(&self) -> bool {
        if self.input_macro.is_empty() {
            return true;
        }
        if self.looping && self.input_macro.total_duration() > Duration::ZERO {
            return false;
        }
        self.position >= self.input_macro.len()
    }

    /// Reset playback to the beginning.
    pub fn reset(&mut self) {
        self.position = 0;
        self.elapsed = Duration::ZERO;
        self.next_due = self
            .input_macro
            .events()
            .first()
            .map(|e| e.delay)
            .unwrap_or(Duration::ZERO);
        self.start_logged = false;
        self.stop_logged = false;
        self.error_logged = false;
    }

    /// Advance playback time and return any events now due.
    pub fn advance(&mut self, delta: Duration) -> Vec<Event> {
        if self.input_macro.is_empty() {
            #[cfg(feature = "tracing")]
            if !self.error_logged {
                let meta = self.input_macro.metadata();
                tracing::warn!(
                    macro_event = "playback_error",
                    reason = "macro_empty",
                    name = %meta.name,
                    events = 0usize,
                    duration_ms = duration_millis_saturating(self.input_macro.total_duration()),
                );
                self.error_logged = true;
            }
            return Vec::new();
        }
        if self.is_done() {
            return Vec::new();
        }

        #[cfg(feature = "tracing")]
        if !self.start_logged {
            let meta = self.input_macro.metadata();
            tracing::info!(
                macro_event = "playback_start",
                name = %meta.name,
                events = self.input_macro.len(),
                duration_ms = duration_millis_saturating(self.input_macro.total_duration()),
                speed = self.speed,
                looping = self.looping,
            );
            self.start_logged = true;
        }

        let scaled = scale_duration(delta, self.speed);
        let total_duration = self.input_macro.total_duration();
        if self.looping && total_duration > Duration::ZERO && scaled == Duration::MAX {
            // Overflowed speed scaling can produce effectively infinite backlog.
            // Collapse to a single bounded loop window for this advance tick.
            self.elapsed =
                loop_elapsed_remainder(self.elapsed, total_duration).saturating_add(total_duration);
        } else {
            self.elapsed = self.elapsed.saturating_add(scaled);
        }
        let events = self.drain_due_events();

        #[cfg(feature = "tracing")]
        if self.is_done() && !self.stop_logged {
            let meta = self.input_macro.metadata();
            tracing::info!(
                macro_event = "playback_stop",
                reason = "completed",
                name = %meta.name,
                events = self.input_macro.len(),
                elapsed_ms = duration_millis_saturating(self.elapsed),
                looping = self.looping,
            );
            self.stop_logged = true;
        }

        events
    }

    fn drain_due_events(&mut self) -> Vec<Event> {
        let mut out = Vec::new();
        let total_duration = self.input_macro.total_duration();
        let can_loop = self.looping && total_duration > Duration::ZERO;
        if can_loop && self.position >= self.input_macro.len() {
            self.elapsed = loop_elapsed_remainder(self.elapsed, total_duration);
            self.position = 0;
            self.next_due = self
                .input_macro
                .events()
                .first()
                .map(|e| e.delay)
                .unwrap_or(Duration::ZERO);
        }

        while out.len() < MAX_DUE_EVENTS_PER_ADVANCE
            && self.position < self.input_macro.len()
            && self.elapsed >= self.next_due
        {
            let timed = &self.input_macro.events[self.position];
            #[cfg(feature = "tracing")]
            tracing::debug!(event = ?timed.event, delay = ?timed.delay, "macro playback event");
            out.push(timed.event.clone());
            self.position += 1;
            if self.position < self.input_macro.len() {
                self.next_due = self
                    .next_due
                    .saturating_add(self.input_macro.events[self.position].delay);
            } else if can_loop {
                // Carry any overflow elapsed time into the next loop.
                self.elapsed = self.elapsed.saturating_sub(total_duration);
                self.position = 0;
                self.next_due = self
                    .input_macro
                    .events()
                    .first()
                    .map(|e| e.delay)
                    .unwrap_or(Duration::ZERO);
            }
        }

        if can_loop && out.len() == MAX_DUE_EVENTS_PER_ADVANCE {
            // Collapse extreme backlog so a single advance cannot spin for
            // unbounded time under huge elapsed/speed spikes.
            self.elapsed = loop_elapsed_remainder(self.elapsed, total_duration);
            if self.position >= self.input_macro.len() {
                self.position = 0;
                self.next_due = self
                    .input_macro
                    .events()
                    .first()
                    .map(|e| e.delay)
                    .unwrap_or(Duration::ZERO);
            }
        }

        out
    }
}

fn normalize_speed(speed: f64) -> f64 {
    if !speed.is_finite() {
        return 1.0;
    }
    if speed <= 0.0 {
        return 0.0;
    }
    speed
}

fn scale_duration(delta: Duration, speed: f64) -> Duration {
    if delta == Duration::ZERO {
        return Duration::ZERO;
    }
    let speed = normalize_speed(speed);
    if speed == 0.0 {
        return Duration::ZERO;
    }
    if speed == 1.0 {
        return delta;
    }
    duration_from_secs_f64_saturating(delta.as_secs_f64() * speed)
}

fn duration_from_secs_f64_saturating(secs: f64) -> Duration {
    if secs.is_nan() || secs <= 0.0 {
        return Duration::ZERO;
    }
    Duration::try_from_secs_f64(secs).unwrap_or(Duration::MAX)
}

#[cfg(any(feature = "tracing", test))]
fn duration_millis_saturating(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

fn loop_elapsed_remainder(elapsed: Duration, total_duration: Duration) -> Duration {
    let total_secs = total_duration.as_secs_f64();
    if total_secs <= 0.0 {
        return Duration::ZERO;
    }
    let elapsed_secs = elapsed.as_secs_f64() % total_secs;
    duration_from_secs_f64_saturating(elapsed_secs)
}

// ---------------------------------------------------------------------------
// EventRecorder – live event stream recording with start/stop/pause
// ---------------------------------------------------------------------------

/// State of an [`EventRecorder`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordingState {
    /// Not yet started or has been stopped.
    Idle,
    /// Actively recording events.
    Recording,
    /// Temporarily paused (events are ignored).
    Paused,
}

/// Records events from a live event stream with start/stop/pause control.
///
/// This is a higher-level wrapper around [`MacroRecorder`] designed for
/// integration with the [`Program`](crate::program::Program) event loop.
///
/// # Usage
///
/// ```ignore
/// let mut recorder = EventRecorder::new("my_session");
/// recorder.start();
///
/// // In event loop:
/// for event in events {
///     recorder.record(&event);  // No-op if not recording
///     // ... process event normally ...
/// }
///
/// recorder.pause();
/// // ... events here are not recorded ...
/// recorder.resume();
///
/// let macro_recording = recorder.finish();
/// ```
pub struct EventRecorder {
    inner: MacroRecorder,
    state: RecordingState,
    pause_start: Option<Instant>,
    total_paused: Duration,
    event_count: usize,
}

impl EventRecorder {
    /// Create a new recorder with the given name.
    ///
    /// Starts in [`RecordingState::Idle`]. Call [`start`](Self::start)
    /// to begin recording.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            inner: MacroRecorder::new(name),
            state: RecordingState::Idle,
            pause_start: None,
            total_paused: Duration::ZERO,
            event_count: 0,
        }
    }

    /// Set the terminal size metadata.
    #[must_use]
    pub fn with_terminal_size(mut self, width: u16, height: u16) -> Self {
        self.inner = self.inner.with_terminal_size(width, height);
        self
    }

    /// Get the current recording state.
    pub fn state(&self) -> RecordingState {
        self.state
    }

    /// Check if actively recording (not idle or paused).
    pub fn is_recording(&self) -> bool {
        self.state == RecordingState::Recording
    }

    /// Start recording. No-op if already recording.
    pub fn start(&mut self) {
        match self.state {
            RecordingState::Idle => {
                self.state = RecordingState::Recording;
                #[cfg(feature = "tracing")]
                tracing::info!(
                    macro_event = "recorder_start",
                    name = %self.inner.name,
                    term_cols = self.inner.terminal_size.0,
                    term_rows = self.inner.terminal_size.1,
                );
            }
            RecordingState::Paused => {
                self.resume();
            }
            RecordingState::Recording => {} // Already recording
        }
    }

    /// Pause recording. Events received while paused are ignored.
    ///
    /// No-op if not recording.
    pub fn pause(&mut self) {
        if self.state == RecordingState::Recording {
            self.state = RecordingState::Paused;
            self.pause_start = Some(Instant::now());
        }
    }

    /// Resume recording after a pause.
    ///
    /// No-op if not paused.
    pub fn resume(&mut self) {
        if self.state == RecordingState::Paused {
            if let Some(pause_start) = self.pause_start.take() {
                self.total_paused = self.total_paused.saturating_add(pause_start.elapsed());
            }
            // Reset the inner recorder's timestamp so the next event's
            // delay is measured from the resume instant, not from the
            // last event before the pause.
            self.inner.last_event_time = Instant::now();
            self.state = RecordingState::Recording;
        }
    }

    /// Record an event. Only records if state is [`RecordingState::Recording`].
    ///
    /// Returns `true` if the event was recorded.
    pub fn record(&mut self, event: &Event) -> bool {
        if self.state != RecordingState::Recording {
            return false;
        }
        self.inner.record_event(event.clone());
        self.event_count += 1;
        true
    }

    /// Record an event with an explicit delay override.
    ///
    /// Returns `true` if the event was recorded.
    pub fn record_with_delay(&mut self, event: &Event, delay: Duration) -> bool {
        if self.state != RecordingState::Recording {
            return false;
        }
        self.inner.record_event_with_delay(event.clone(), delay);
        self.event_count += 1;
        true
    }

    /// Get the number of events recorded so far.
    pub fn event_count(&self) -> usize {
        self.event_count
    }

    /// Get the total time spent paused.
    pub fn total_paused(&self) -> Duration {
        let mut total = self.total_paused;
        if let Some(pause_start) = self.pause_start {
            total = total.saturating_add(pause_start.elapsed());
        }
        total
    }

    /// Stop recording and produce the final [`InputMacro`].
    ///
    /// Consumes the recorder.
    pub fn finish(self) -> InputMacro {
        self.finish_internal(true)
    }

    #[allow(unused_variables)]
    fn finish_internal(self, log: bool) -> InputMacro {
        let paused = self.total_paused();
        let macro_data = self.inner.finish();
        #[cfg(feature = "tracing")]
        if log {
            let meta = macro_data.metadata();
            tracing::info!(
                macro_event = "recorder_stop",
                name = %meta.name,
                events = macro_data.len(),
                duration_ms = duration_millis_saturating(macro_data.total_duration()),
                paused_ms = duration_millis_saturating(paused),
                term_cols = meta.terminal_size.0,
                term_rows = meta.terminal_size.1,
            );
        }
        macro_data
    }

    /// Stop recording and discard all events.
    ///
    /// Returns the number of events that were discarded.
    pub fn discard(self) -> usize {
        self.event_count
    }
}

/// Filter specification for recording.
///
/// Controls which events are recorded. Useful for excluding noise
/// events (like resize storms or mouse moves) from recordings.
#[derive(Debug, Clone)]
pub struct RecordingFilter {
    /// Record keyboard events.
    pub keys: bool,
    /// Record mouse events.
    pub mouse: bool,
    /// Record resize events.
    pub resize: bool,
    /// Record paste events.
    pub paste: bool,
    /// Record IME composition events.
    pub ime: bool,
    /// Record focus events.
    pub focus: bool,
}

impl Default for RecordingFilter {
    fn default() -> Self {
        Self {
            keys: true,
            mouse: true,
            resize: true,
            paste: true,
            ime: true,
            focus: true,
        }
    }
}

impl RecordingFilter {
    /// Record only keyboard events.
    pub fn keys_only() -> Self {
        Self {
            keys: true,
            mouse: false,
            resize: false,
            paste: false,
            ime: false,
            focus: false,
        }
    }

    /// Check if an event should be recorded.
    pub fn accepts(&self, event: &Event) -> bool {
        match event {
            Event::Key(_) => self.keys,
            Event::Mouse(_) => self.mouse,
            Event::Resize { .. } => self.resize,
            Event::Paste(_) => self.paste,
            Event::Ime(_) => self.ime,
            Event::Focus(_) => self.focus,
            Event::Clipboard(_) => true, // Always record clipboard responses
            Event::Tick => false,        // Internal timing, not recorded
        }
    }
}

/// A filtered event recorder that only records events matching a filter.
pub struct FilteredEventRecorder {
    recorder: EventRecorder,
    filter: RecordingFilter,
    filtered_count: usize,
}

impl FilteredEventRecorder {
    /// Create a filtered recorder.
    pub fn new(name: impl Into<String>, filter: RecordingFilter) -> Self {
        Self {
            recorder: EventRecorder::new(name),
            filter,
            filtered_count: 0,
        }
    }

    /// Set terminal size metadata.
    #[must_use]
    pub fn with_terminal_size(mut self, width: u16, height: u16) -> Self {
        self.recorder = self.recorder.with_terminal_size(width, height);
        self
    }

    /// Start recording.
    pub fn start(&mut self) {
        self.recorder.start();
    }

    /// Pause recording.
    pub fn pause(&mut self) {
        self.recorder.pause();
    }

    /// Resume recording.
    pub fn resume(&mut self) {
        self.recorder.resume();
    }

    /// Get current state.
    pub fn state(&self) -> RecordingState {
        self.recorder.state()
    }

    /// Check if actively recording.
    pub fn is_recording(&self) -> bool {
        self.recorder.is_recording()
    }

    /// Record an event if it passes the filter.
    ///
    /// Returns `true` if the event was recorded (passed filter and recorder is active).
    pub fn record(&mut self, event: &Event) -> bool {
        if !self.filter.accepts(event) {
            self.filtered_count += 1;
            return false;
        }
        self.recorder.record(event)
    }

    /// Get the number of events that were filtered out.
    pub fn filtered_count(&self) -> usize {
        self.filtered_count
    }

    /// Get the number of events actually recorded.
    pub fn event_count(&self) -> usize {
        self.recorder.event_count()
    }

    /// Stop recording and produce the final macro.
    #[allow(unused_variables)]
    pub fn finish(self) -> InputMacro {
        let filtered = self.filtered_count;
        let paused = self.recorder.total_paused();
        let macro_data = self.recorder.finish_internal(false);
        #[cfg(feature = "tracing")]
        {
            let meta = macro_data.metadata();
            tracing::info!(
                macro_event = "recorder_stop",
                name = %meta.name,
                events = macro_data.len(),
                filtered,
                duration_ms = duration_millis_saturating(macro_data.total_duration()),
                paused_ms = duration_millis_saturating(paused),
                term_cols = meta.terminal_size.0,
                term_rows = meta.terminal_size.1,
            );
        }
        macro_data
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::program::{Cmd, Model};
    use crate::simulator::ProgramSimulator;
    use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
    use ftui_render::frame::Frame;
    use proptest::prelude::*;

    // ---------- Test model ----------

    struct Counter {
        value: i32,
    }

    #[derive(Debug)]
    enum CounterMsg {
        Increment,
        Decrement,
        Quit,
    }

    impl From<Event> for CounterMsg {
        fn from(event: Event) -> Self {
            match event {
                Event::Key(k) if k.code == KeyCode::Char('+') => CounterMsg::Increment,
                Event::Key(k) if k.code == KeyCode::Char('-') => CounterMsg::Decrement,
                Event::Key(k) if k.code == KeyCode::Char('q') => CounterMsg::Quit,
                _ => CounterMsg::Increment,
            }
        }
    }

    impl Model for Counter {
        type Message = CounterMsg;

        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
            match msg {
                CounterMsg::Increment => {
                    self.value += 1;
                    Cmd::none()
                }
                CounterMsg::Decrement => {
                    self.value -= 1;
                    Cmd::none()
                }
                CounterMsg::Quit => Cmd::quit(),
            }
        }

        fn view(&self, _frame: &mut Frame) {}
    }

    fn key_event(c: char) -> Event {
        Event::Key(KeyEvent {
            code: KeyCode::Char(c),
            modifiers: Modifiers::empty(),
            kind: KeyEventKind::Press,
        })
    }

    // ---------- TimedEvent tests ----------

    #[test]
    fn timed_event_immediate_has_zero_delay() {
        let te = TimedEvent::immediate(key_event('a'));
        assert_eq!(te.delay, Duration::ZERO);
    }

    #[test]
    fn timed_event_new_preserves_delay() {
        let delay = Duration::from_millis(100);
        let te = TimedEvent::new(key_event('x'), delay);
        assert_eq!(te.delay, delay);
    }

    // ---------- InputMacro tests ----------

    #[test]
    fn macro_from_events_has_zero_delays() {
        let m = InputMacro::from_events("test", vec![key_event('+'), key_event('-')]);
        assert_eq!(m.len(), 2);
        assert!(!m.is_empty());
        assert_eq!(m.total_duration(), Duration::ZERO);
        for te in m.events() {
            assert_eq!(te.delay, Duration::ZERO);
        }
    }

    #[test]
    fn macro_metadata() {
        let m = InputMacro::from_events("my_macro", vec![key_event('a')]);
        assert_eq!(m.metadata().name, "my_macro");
        assert_eq!(m.metadata().terminal_size, (80, 24));
    }

    #[test]
    fn empty_macro() {
        let m = InputMacro::from_events("empty", vec![]);
        assert!(m.is_empty());
        assert_eq!(m.len(), 0);
    }

    #[test]
    fn bare_events_extracts_events() {
        let events = vec![key_event('+'), key_event('-'), key_event('q')];
        let m = InputMacro::from_events("test", events.clone());
        let bare = m.bare_events();
        assert_eq!(bare.len(), 3);
        assert_eq!(bare, events);
    }

    // ---------- MacroRecorder tests ----------

    #[test]
    fn recorder_captures_events() {
        let mut rec = MacroRecorder::new("rec_test");
        rec.record_event(key_event('+'));
        rec.record_event(key_event('+'));
        rec.record_event(key_event('-'));
        assert_eq!(rec.event_count(), 3);

        let m = rec.finish();
        assert_eq!(m.len(), 3);
        assert_eq!(m.metadata().name, "rec_test");
    }

    #[test]
    fn recorder_with_terminal_size() {
        let rec = MacroRecorder::new("sized").with_terminal_size(120, 40);
        let m = rec.finish();
        assert_eq!(m.metadata().terminal_size, (120, 40));
    }

    #[test]
    fn recorder_explicit_delays() {
        let mut rec = MacroRecorder::new("delayed");
        rec.record_event_with_delay(key_event('+'), Duration::from_millis(0));
        rec.record_event_with_delay(key_event('-'), Duration::from_millis(50));
        rec.record_event_with_delay(key_event('q'), Duration::from_millis(100));

        let m = rec.finish();
        assert_eq!(m.events()[0].delay, Duration::from_millis(0));
        assert_eq!(m.events()[1].delay, Duration::from_millis(50));
        assert_eq!(m.events()[2].delay, Duration::from_millis(100));
        assert_eq!(m.total_duration(), Duration::from_millis(150));
    }

    #[test]
    fn recorder_explicit_delay_overflow_saturates_total_duration() {
        let mut rec = MacroRecorder::new("huge-delay");
        rec.record_event_with_delay(key_event('+'), Duration::MAX);
        rec.record_event_with_delay(key_event('-'), Duration::from_millis(1));

        let m = rec.finish();
        assert_eq!(m.events()[0].delay, Duration::MAX);
        assert_eq!(m.events()[1].delay, Duration::from_millis(1));
        assert_eq!(m.total_duration(), Duration::MAX);
        assert_eq!(duration_millis_saturating(m.total_duration()), u64::MAX);
    }

    // ---------- MacroPlayer tests ----------

    #[test]
    fn player_replays_all_events() {
        let m = InputMacro::from_events(
            "replay",
            vec![key_event('+'), key_event('+'), key_event('+')],
        );

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        assert_eq!(player.remaining(), 3);
        assert!(!player.is_done());

        player.replay_all(&mut sim);

        assert!(player.is_done());
        assert_eq!(player.remaining(), 0);
        assert_eq!(sim.model().value, 3);
    }

    #[test]
    fn player_step_advances_position() {
        let m = InputMacro::from_events("step", vec![key_event('+'), key_event('+')]);

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        assert_eq!(player.position(), 0);

        assert!(player.step(&mut sim));
        assert_eq!(player.position(), 1);
        assert_eq!(sim.model().value, 1);

        assert!(player.step(&mut sim));
        assert_eq!(player.position(), 2);
        assert_eq!(sim.model().value, 2);

        assert!(!player.step(&mut sim));
    }

    #[test]
    fn player_stops_on_quit() {
        let m = InputMacro::from_events(
            "quit_test",
            vec![key_event('+'), key_event('q'), key_event('+')],
        );

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        player.replay_all(&mut sim);

        // Only increment and quit processed; third event skipped
        assert_eq!(sim.model().value, 1);
        assert!(!sim.is_running());
    }

    #[test]
    fn player_replay_until_respects_time() {
        let events = vec![
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
            TimedEvent::new(key_event('+'), Duration::from_millis(20)),
            TimedEvent::new(key_event('+'), Duration::from_millis(100)),
        ];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "timed".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(130),
            },
        );

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);

        // Play events up to 50ms: first two events (10ms + 20ms = 30ms)
        player.replay_until(&mut sim, Duration::from_millis(50));
        assert_eq!(sim.model().value, 2);
        assert_eq!(player.position(), 2);

        // Third event at 130ms, play until 200ms
        player.replay_until(&mut sim, Duration::from_millis(200));
        assert_eq!(sim.model().value, 3);
        assert!(player.is_done());
    }

    #[test]
    fn player_elapsed_tracks_virtual_time() {
        let events = vec![
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
            TimedEvent::new(key_event('+'), Duration::from_millis(20)),
        ];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "elapsed".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(30),
            },
        );

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        assert_eq!(player.elapsed(), Duration::ZERO);

        player.step(&mut sim);
        assert_eq!(player.elapsed(), Duration::from_millis(10));

        player.step(&mut sim);
        assert_eq!(player.elapsed(), Duration::from_millis(30));
    }

    #[test]
    fn player_reset_restarts_playback() {
        let m = InputMacro::from_events("reset", vec![key_event('+'), key_event('+')]);

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        player.replay_all(&mut sim);
        assert_eq!(sim.model().value, 2);
        assert!(player.is_done());

        // Reset player and replay into fresh simulator
        player.reset();
        assert_eq!(player.position(), 0);
        assert!(!player.is_done());

        let mut sim2 = ProgramSimulator::new(Counter { value: 10 });
        sim2.init();
        player.replay_all(&mut sim2);
        assert_eq!(sim2.model().value, 12);
    }

    #[test]
    fn player_replay_with_sleeper_respects_delays() {
        let events = vec![
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
            TimedEvent::new(key_event('+'), Duration::from_millis(0)),
            TimedEvent::new(key_event('+'), Duration::from_millis(25)),
        ];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "timed_sleep".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(35),
            },
        );

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        let mut sleeps = Vec::new();
        player.replay_with_sleeper(&mut sim, |d| sleeps.push(d));

        assert_eq!(
            sleeps,
            vec![Duration::from_millis(10), Duration::from_millis(25)]
        );
        assert_eq!(sim.model().value, 3);
    }

    // ---------- MacroPlayback tests ----------

    #[test]
    fn playback_emits_due_events_in_order() {
        let events = vec![
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
        ];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "playback".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(20),
            },
        );

        let mut playback = MacroPlayback::new(m.clone());
        assert!(playback.advance(Duration::from_millis(5)).is_empty());
        let first = playback.advance(Duration::from_millis(5));
        assert_eq!(first.len(), 1);
        let second = playback.advance(Duration::from_millis(10));
        assert_eq!(second.len(), 1);
        assert!(playback.advance(Duration::from_millis(10)).is_empty());
    }

    #[test]
    fn playback_speed_scales_time() {
        let events = vec![TimedEvent::new(key_event('+'), Duration::from_millis(10))];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "speed".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(10),
            },
        );

        let mut playback = MacroPlayback::new(m.clone()).with_speed(2.0);
        let events = playback.advance(Duration::from_millis(5));
        assert_eq!(events.len(), 1);
    }

    #[test]
    fn playback_speed_huge_value_does_not_panic() {
        let events = vec![TimedEvent::new(key_event('+'), Duration::from_millis(10))];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "huge-speed".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(10),
            },
        );

        let mut playback = MacroPlayback::new(m).with_speed(f64::MAX);
        let events = playback.advance(Duration::from_millis(1));
        assert_eq!(events.len(), 1);
    }

    #[test]
    fn playback_speed_huge_looping_multiple_advances_do_not_panic() {
        let events = vec![TimedEvent::new(key_event('+'), Duration::from_millis(10))];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "huge-speed-looping".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(10),
            },
        );

        let mut playback = MacroPlayback::new(m)
            .with_speed(f64::MAX)
            .with_looping(true);
        let first = playback.advance(Duration::from_millis(1));
        assert_eq!(first.len(), 1);
        let second = playback.advance(Duration::from_millis(1));
        assert_eq!(second.len(), 1);
    }

    #[test]
    fn playback_looping_handles_large_delta() {
        let events = vec![
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
        ];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "loop".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(20),
            },
        );

        let mut playback = MacroPlayback::new(m.clone()).with_looping(true);
        let events = playback.advance(Duration::from_millis(50));
        assert_eq!(events.len(), 5);
    }

    #[test]
    fn playback_zero_duration_does_not_loop_forever() {
        let m = InputMacro::from_events("zero", vec![key_event('+'), key_event('+')]);
        let mut playback = MacroPlayback::new(m.clone()).with_looping(true);

        let events = playback.advance(Duration::ZERO);
        assert_eq!(events.len(), 2);
        assert!(playback.advance(Duration::from_millis(10)).is_empty());
    }

    #[test]
    fn macro_replay_with_sleeper_wrapper() {
        let events = vec![
            TimedEvent::new(key_event('+'), Duration::from_millis(5)),
            TimedEvent::new(key_event('+'), Duration::from_millis(10)),
        ];
        let m = InputMacro::new(
            events,
            MacroMetadata {
                name: "wrapper".to_string(),
                terminal_size: (80, 24),
                total_duration: Duration::from_millis(15),
            },
        );

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut slept = Vec::new();
        m.replay_with_sleeper(&mut sim, |d| slept.push(d));

        assert_eq!(
            slept,
            vec![Duration::from_millis(5), Duration::from_millis(10)]
        );
        assert_eq!(sim.model().value, 2);
    }

    #[test]
    fn empty_macro_replay() {
        let m = InputMacro::from_events("empty", vec![]);

        let mut sim = ProgramSimulator::new(Counter { value: 5 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        assert!(player.is_done());
        player.replay_all(&mut sim);
        assert_eq!(sim.model().value, 5);
    }

    #[test]
    fn macro_with_mixed_events() {
        let events = vec![
            key_event('+'),
            Event::Resize {
                width: 100,
                height: 50,
            },
            key_event('-'),
            Event::Focus(true),
            key_event('+'),
        ];
        let m = InputMacro::from_events("mixed", events);

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();

        let mut player = MacroPlayer::new(&m);
        player.replay_all(&mut sim);

        // +1, resize->increment, -1, focus->increment, +1 = 3
        // (Counter converts all non-matching events to Increment)
        assert_eq!(sim.model().value, 3);
    }

    #[test]
    fn deterministic_replay() {
        let m = InputMacro::from_events(
            "determinism",
            vec![
                key_event('+'),
                key_event('+'),
                key_event('-'),
                key_event('+'),
                key_event('+'),
            ],
        );

        // Replay twice and verify identical results
        let result1 = {
            let mut sim = ProgramSimulator::new(Counter { value: 0 });
            sim.init();
            MacroPlayer::new(&m).replay_all(&mut sim);
            sim.model().value
        };

        let result2 = {
            let mut sim = ProgramSimulator::new(Counter { value: 0 });
            sim.init();
            MacroPlayer::new(&m).replay_all(&mut sim);
            sim.model().value
        };

        assert_eq!(result1, result2);
        assert_eq!(result1, 3);
    }

    // ---------- EventRecorder tests ----------

    #[test]
    fn event_recorder_starts_idle() {
        let rec = EventRecorder::new("test");
        assert_eq!(rec.state(), RecordingState::Idle);
        assert!(!rec.is_recording());
        assert_eq!(rec.event_count(), 0);
    }

    #[test]
    fn event_recorder_start_activates() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        assert_eq!(rec.state(), RecordingState::Recording);
        assert!(rec.is_recording());
    }

    #[test]
    fn event_recorder_ignores_events_when_idle() {
        let mut rec = EventRecorder::new("test");
        assert!(!rec.record(&key_event('a')));
        assert_eq!(rec.event_count(), 0);
    }

    #[test]
    fn event_recorder_records_when_active() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        assert!(rec.record(&key_event('a')));
        assert!(rec.record(&key_event('b')));
        assert_eq!(rec.event_count(), 2);

        let m = rec.finish();
        assert_eq!(m.len(), 2);
    }

    #[test]
    fn event_recorder_pause_ignores_events() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        rec.record(&key_event('a'));
        rec.pause();
        assert_eq!(rec.state(), RecordingState::Paused);
        assert!(!rec.is_recording());

        // Events during pause are ignored
        assert!(!rec.record(&key_event('b')));
        assert_eq!(rec.event_count(), 1);
    }

    #[test]
    fn event_recorder_resume_after_pause() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        rec.record(&key_event('a'));
        rec.pause();
        rec.record(&key_event('b')); // ignored
        rec.resume();
        assert!(rec.is_recording());
        rec.record(&key_event('c'));
        assert_eq!(rec.event_count(), 2);

        let m = rec.finish();
        assert_eq!(m.len(), 2);
        assert_eq!(m.bare_events()[0], key_event('a'));
        assert_eq!(m.bare_events()[1], key_event('c'));
    }

    #[test]
    fn event_recorder_resume_saturates_total_paused() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        rec.total_paused = Duration::MAX;
        rec.pause();
        std::thread::sleep(Duration::from_millis(1));
        rec.resume();

        assert_eq!(rec.total_paused(), Duration::MAX);
    }

    #[test]
    fn event_recorder_active_pause_saturates_total_paused_query() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        rec.total_paused = Duration::MAX;
        rec.pause();
        std::thread::sleep(Duration::from_millis(1));

        assert_eq!(rec.total_paused(), Duration::MAX);
    }

    #[test]
    fn event_recorder_start_resumes_when_paused() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        rec.pause();
        assert_eq!(rec.state(), RecordingState::Paused);

        rec.start(); // Should resume
        assert_eq!(rec.state(), RecordingState::Recording);
    }

    #[test]
    fn event_recorder_pause_noop_when_idle() {
        let mut rec = EventRecorder::new("test");
        rec.pause();
        assert_eq!(rec.state(), RecordingState::Idle);
    }

    #[test]
    fn event_recorder_resume_noop_when_idle() {
        let mut rec = EventRecorder::new("test");
        rec.resume();
        assert_eq!(rec.state(), RecordingState::Idle);
    }

    #[test]
    fn event_recorder_discard() {
        let mut rec = EventRecorder::new("test");
        rec.start();
        rec.record(&key_event('a'));
        rec.record(&key_event('b'));
        let count = rec.discard();
        assert_eq!(count, 2);
    }

    #[test]
    fn event_recorder_with_terminal_size() {
        let mut rec = EventRecorder::new("sized").with_terminal_size(120, 40);
        rec.start();
        rec.record(&key_event('x'));
        let m = rec.finish();
        assert_eq!(m.metadata().terminal_size, (120, 40));
    }

    #[test]
    fn event_recorder_finish_produces_valid_macro() {
        let mut rec = EventRecorder::new("full_test");
        rec.start();
        rec.record(&key_event('+'));
        rec.record(&key_event('+'));
        rec.record(&key_event('-'));

        let m = rec.finish();
        assert_eq!(m.len(), 3);
        assert_eq!(m.metadata().name, "full_test");

        // Replay and verify
        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();
        MacroPlayer::new(&m).replay_all(&mut sim);
        assert_eq!(sim.model().value, 1); // +1 +1 -1 = 1
    }

    #[test]
    fn event_recorder_record_with_delay() {
        let mut rec = EventRecorder::new("delayed");
        rec.start();
        assert!(rec.record_with_delay(&key_event('a'), Duration::from_millis(50)));
        assert!(rec.record_with_delay(&key_event('b'), Duration::from_millis(100)));
        assert_eq!(rec.event_count(), 2);

        let m = rec.finish();
        assert_eq!(m.events()[0].delay, Duration::from_millis(50));
        assert_eq!(m.events()[1].delay, Duration::from_millis(100));
    }

    #[test]
    fn event_recorder_record_with_delay_ignores_when_idle() {
        let mut rec = EventRecorder::new("test");
        assert!(!rec.record_with_delay(&key_event('a'), Duration::from_millis(50)));
        assert_eq!(rec.event_count(), 0);
    }

    // ---------- RecordingFilter tests ----------

    #[test]
    fn filter_default_accepts_all() {
        let filter = RecordingFilter::default();
        assert!(filter.accepts(&key_event('a')));
        assert!(filter.accepts(&Event::Resize {
            width: 80,
            height: 24
        }));
        assert!(filter.accepts(&Event::Focus(true)));
    }

    #[test]
    fn filter_keys_only() {
        let filter = RecordingFilter::keys_only();
        assert!(filter.accepts(&key_event('a')));
        assert!(!filter.accepts(&Event::Resize {
            width: 80,
            height: 24
        }));
        assert!(!filter.accepts(&Event::Focus(true)));
    }

    #[test]
    fn filter_custom() {
        let filter = RecordingFilter {
            keys: true,
            mouse: false,
            resize: false,
            paste: true,
            ime: false,
            focus: false,
        };
        assert!(filter.accepts(&key_event('a')));
        assert!(!filter.accepts(&Event::Resize {
            width: 80,
            height: 24
        }));
        assert!(!filter.accepts(&Event::Focus(false)));
    }

    // ---------- FilteredEventRecorder tests ----------

    #[test]
    fn filtered_recorder_records_matching_events() {
        let mut rec = FilteredEventRecorder::new("filtered", RecordingFilter::default());
        rec.start();
        assert!(rec.record(&key_event('a')));
        assert_eq!(rec.event_count(), 1);
        assert_eq!(rec.filtered_count(), 0);
    }

    #[test]
    fn filtered_recorder_skips_filtered_events() {
        let mut rec = FilteredEventRecorder::new("keys_only", RecordingFilter::keys_only());
        rec.start();
        assert!(rec.record(&key_event('a')));
        assert!(!rec.record(&Event::Focus(true)));
        assert!(!rec.record(&Event::Resize {
            width: 100,
            height: 50
        }));
        assert!(rec.record(&key_event('b')));

        assert_eq!(rec.event_count(), 2);
        assert_eq!(rec.filtered_count(), 2);
    }

    #[test]
    fn filtered_recorder_finish_produces_macro() {
        let mut rec = FilteredEventRecorder::new("test", RecordingFilter::keys_only());
        rec.start();
        rec.record(&key_event('+'));
        rec.record(&Event::Focus(true)); // filtered
        rec.record(&key_event('+'));

        let m = rec.finish();
        assert_eq!(m.len(), 2);

        let mut sim = ProgramSimulator::new(Counter { value: 0 });
        sim.init();
        MacroPlayer::new(&m).replay_all(&mut sim);
        assert_eq!(sim.model().value, 2);
    }

    #[test]
    fn filtered_recorder_pause_resume() {
        let mut rec = FilteredEventRecorder::new("test", RecordingFilter::default());
        rec.start();
        rec.record(&key_event('a'));
        rec.pause();
        assert!(!rec.record(&key_event('b'))); // paused
        rec.resume();
        rec.record(&key_event('c'));
        assert_eq!(rec.event_count(), 2);
    }

    #[test]
    fn filtered_recorder_with_terminal_size() {
        let mut rec = FilteredEventRecorder::new("sized", RecordingFilter::default())
            .with_terminal_size(200, 60);
        rec.start();
        rec.record(&key_event('x'));
        let m = rec.finish();
        assert_eq!(m.metadata().terminal_size, (200, 60));
    }

    // ---------- Property tests ----------

    #[derive(Default)]
    struct EventSink {
        events: Vec<Event>,
    }

    #[derive(Debug, Clone)]
    struct EventMsg(Event);

    impl From<Event> for EventMsg {
        fn from(event: Event) -> Self {
            Self(event)
        }
    }

    impl Model for EventSink {
        type Message = EventMsg;

        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
            self.events.push(msg.0);
            Cmd::none()
        }

        fn view(&self, _frame: &mut Frame) {}
    }

    proptest! {
        #[test]
        fn recorder_with_explicit_delays_roundtrips(pairs in proptest::collection::vec((0u8..=25, 0u16..=2000), 0..32)) {
            let mut recorder = MacroRecorder::new("prop").with_terminal_size(80, 24);
            let mut expected_total = Duration::ZERO;
            let mut expected_events = Vec::with_capacity(pairs.len());

            for (ch_idx, delay_ms) in &pairs {
                let ch = char::from(b'a' + *ch_idx);
                let delay = Duration::from_millis(*delay_ms as u64);
                expected_total += delay;
                let ev = key_event(ch);
                expected_events.push(ev.clone());
                recorder.record_event_with_delay(ev, delay);
            }

            let m = recorder.finish();
            prop_assert_eq!(m.len(), pairs.len());
            prop_assert_eq!(m.metadata().terminal_size, (80, 24));
            prop_assert_eq!(m.total_duration(), expected_total);
            prop_assert_eq!(m.bare_events(), expected_events);
        }

        #[test]
        fn player_replays_events_in_order(pairs in proptest::collection::vec((0u8..=25, 0u16..=2000), 0..32)) {
            let mut timed = Vec::with_capacity(pairs.len());
            let mut total = Duration::ZERO;
            let mut expected_events = Vec::with_capacity(pairs.len());

            for (ch_idx, delay_ms) in &pairs {
                let ch = char::from(b'a' + *ch_idx);
                let delay = Duration::from_millis(*delay_ms as u64);
                total += delay;
                let ev = key_event(ch);
                expected_events.push(ev.clone());
                timed.push(TimedEvent::new(ev, delay));
            }

            let m = InputMacro::new(timed, MacroMetadata {
                name: "prop".to_string(),
                terminal_size: (80, 24),
                total_duration: total,
            });

            let mut sim = ProgramSimulator::new(EventSink::default());
            sim.init();
            let mut player = MacroPlayer::new(&m);
            player.replay_all(&mut sim);

            prop_assert_eq!(sim.model().events.clone(), expected_events);
            prop_assert_eq!(player.elapsed(), total);
        }
    }
}