ftui-extras 0.4.0

Feature-gated extras for FrankenTUI (markdown, charts, clipboard, themes).
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
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
//! ANSI escape sequence parser using the `vte` crate.
//!
//! This module provides a callback-based ANSI parser that dispatches parsed
//! sequences to an [`AnsiHandler`] implementation.
//!
//! # Invariants
//!
//! 1. **Complete UTF-8**: The parser correctly handles multi-byte UTF-8 sequences.
//! 2. **Sequence isolation**: Each escape sequence is fully parsed before dispatch.
//! 3. **State recovery**: Malformed sequences return to ground state gracefully.
//!
//! # Failure Modes
//!
//! | Failure | Cause | Behavior |
//! |---------|-------|----------|
//! | Invalid UTF-8 | Corrupted input | Replacement character dispatched |
//! | Unknown CSI | Unrecognized sequence | Silently ignored |
//! | Truncated sequence | Incomplete input | Buffered for next parse call |

use std::panic::{AssertUnwindSafe, catch_unwind};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use ftui_core::with_panic_cleanup_suppressed;
use vte::{Parser, Perform};

/// Opaque identifier returned when registering a parser hook.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HookId(u64);

impl HookId {
    /// Return the numeric id value.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Hook classes supported by [`AnsiParser`] registration APIs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookClass {
    /// CSI (`ESC [`) hook pipeline.
    Csi,
    /// OSC (`ESC ]`) hook pipeline.
    Osc,
    /// ESC (single-byte final) hook pipeline.
    Esc,
    /// DCS (`ESC P`) hook pipeline.
    Dcs,
}

/// Hook dispatch result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookDisposition {
    /// Continue dispatching remaining hooks, then fallback to the handler.
    Continue,
    /// Stop hook dispatch and suppress fallback handler dispatch.
    Consume,
    /// Reject the hook invocation and continue with fallback behavior.
    Reject,
}

/// Structured policy rejection codes emitted in hook traces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookRejectReason {
    /// Hook class disabled by capability profile.
    CapabilityDisabled,
    /// Parse-time quota exceeded.
    QuotaExceeded,
    /// Hook callback ran longer than the configured max runtime.
    TimeoutExceeded,
    /// Hook callback panicked and was isolated.
    HookPanicked,
    /// Hook explicitly rejected processing.
    HookRejected,
}

/// Hook trace stage for deterministic postmortem replay.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookTraceStage {
    /// A registered hook callback was invoked.
    HookInvoked,
    /// A hook consumed the event and stopped fallback dispatch.
    HookConsumed,
    /// No hook consumed the event, so fallback handler dispatch occurred.
    FallbackDispatched,
    /// Policy/capability/isolation rejected hook execution.
    PolicyRejected,
}

/// Replay-grade structured hook trace event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HookTraceEvent {
    /// Unix timestamp in milliseconds.
    pub ts_ms: u64,
    /// Monotonic correlation id for deterministic event ordering.
    pub correlation_id: u64,
    /// Hook class for this record.
    pub class: HookClass,
    /// Dispatch stage.
    pub stage: HookTraceStage,
    /// Hook id, when the record corresponds to a specific callback.
    pub hook_id: Option<HookId>,
    /// Rejection reason, if the stage is `PolicyRejected`.
    pub reject_reason: Option<HookRejectReason>,
    /// Callback elapsed microseconds when available.
    pub elapsed_us: Option<u64>,
}

/// Parse-time capability profile for parser hook classes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HookCapabilities {
    /// Allow CSI hooks.
    pub csi: bool,
    /// Allow OSC hooks.
    pub osc: bool,
    /// Allow ESC hooks.
    pub esc: bool,
    /// Allow DCS hooks.
    pub dcs: bool,
}

impl Default for HookCapabilities {
    fn default() -> Self {
        Self {
            csi: true,
            osc: true,
            esc: true,
            dcs: true,
        }
    }
}

/// Parse-time parser hook policy (quotas + callback runtime bounds).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HookPolicy {
    /// Max CSI hook dispatches per `parse()` call.
    pub max_csi_invocations_per_parse: u32,
    /// Max OSC hook dispatches per `parse()` call.
    pub max_osc_invocations_per_parse: u32,
    /// Max ESC hook dispatches per `parse()` call.
    pub max_esc_invocations_per_parse: u32,
    /// Max DCS hook dispatches per `parse()` call.
    pub max_dcs_invocations_per_parse: u32,
    /// Max DCS `put` bytes delivered to hooks per `parse()` call.
    pub max_dcs_bytes_per_parse: usize,
    /// Max callback runtime before timeout rejection.
    pub max_hook_runtime: Duration,
}

impl Default for HookPolicy {
    fn default() -> Self {
        Self {
            max_csi_invocations_per_parse: 2_048,
            max_osc_invocations_per_parse: 1_024,
            max_esc_invocations_per_parse: 2_048,
            max_dcs_invocations_per_parse: 8_192,
            max_dcs_bytes_per_parse: 256 * 1024,
            max_hook_runtime: Duration::from_millis(5),
        }
    }
}

/// CSI hook event payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CsiHookEvent {
    /// CSI numeric params.
    pub params: Vec<i64>,
    /// CSI intermediate bytes.
    pub intermediates: Vec<u8>,
    /// CSI final byte.
    pub final_byte: char,
}

/// OSC hook event payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OscHookEvent {
    /// OSC semicolon-separated params.
    pub params: Vec<Vec<u8>>,
}

/// ESC hook event payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EscHookEvent {
    /// ESC intermediates.
    pub intermediates: Vec<u8>,
    /// ESC final byte.
    pub final_byte: char,
}

/// DCS hook event payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DcsHookEvent {
    /// DCS sequence start (`hook`).
    Hook {
        /// DCS numeric params.
        params: Vec<i64>,
        /// DCS intermediate bytes.
        intermediates: Vec<u8>,
        /// DCS final byte.
        final_byte: char,
    },
    /// DCS payload byte (`put`).
    Put {
        /// DCS data byte.
        byte: u8,
    },
    /// DCS sequence end (`unhook`).
    Unhook,
}

type CsiHookCallback = Box<dyn FnMut(&CsiHookEvent) -> HookDisposition>;
type OscHookCallback = Box<dyn FnMut(&OscHookEvent) -> HookDisposition>;
type EscHookCallback = Box<dyn FnMut(&EscHookEvent) -> HookDisposition>;
type DcsHookCallback = Box<dyn FnMut(&DcsHookEvent) -> HookDisposition>;

struct HookEntry<T> {
    id: HookId,
    callback: T,
}

#[derive(Default)]
struct HookRegistry {
    next_id: u64,
    csi: Vec<HookEntry<CsiHookCallback>>,
    osc: Vec<HookEntry<OscHookCallback>>,
    esc: Vec<HookEntry<EscHookCallback>>,
    dcs: Vec<HookEntry<DcsHookCallback>>,
}

impl HookRegistry {
    fn register_csi<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&CsiHookEvent) -> HookDisposition + 'static,
    {
        let id = self.next_hook_id();
        self.csi.push(HookEntry {
            id,
            callback: Box::new(callback),
        });
        id
    }

    fn register_osc<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&OscHookEvent) -> HookDisposition + 'static,
    {
        let id = self.next_hook_id();
        self.osc.push(HookEntry {
            id,
            callback: Box::new(callback),
        });
        id
    }

    fn register_esc<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&EscHookEvent) -> HookDisposition + 'static,
    {
        let id = self.next_hook_id();
        self.esc.push(HookEntry {
            id,
            callback: Box::new(callback),
        });
        id
    }

    fn register_dcs<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&DcsHookEvent) -> HookDisposition + 'static,
    {
        let id = self.next_hook_id();
        self.dcs.push(HookEntry {
            id,
            callback: Box::new(callback),
        });
        id
    }

    fn deregister(&mut self, id: HookId) -> bool {
        fn remove_hook<T>(hooks: &mut Vec<HookEntry<T>>, id: HookId) -> bool {
            if let Some(idx) = hooks.iter().position(|entry| entry.id == id) {
                hooks.remove(idx);
                return true;
            }
            false
        }

        remove_hook(&mut self.csi, id)
            || remove_hook(&mut self.osc, id)
            || remove_hook(&mut self.esc, id)
            || remove_hook(&mut self.dcs, id)
    }

    fn clear(&mut self) {
        self.csi.clear();
        self.osc.clear();
        self.esc.clear();
        self.dcs.clear();
    }

    fn next_hook_id(&mut self) -> HookId {
        self.next_id = self.next_id.saturating_add(1);
        HookId(self.next_id)
    }
}

#[derive(Default)]
struct HookDispatchBudget {
    csi_invocations: u32,
    osc_invocations: u32,
    esc_invocations: u32,
    dcs_invocations: u32,
    dcs_bytes: usize,
}

fn system_time_ms() -> u64 {
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    u64::try_from(ts).unwrap_or(u64::MAX)
}

fn push_hook_trace(
    traces: &mut Vec<HookTraceEvent>,
    next_correlation_id: &mut u64,
    class: HookClass,
    stage: HookTraceStage,
    hook_id: Option<HookId>,
    reject_reason: Option<HookRejectReason>,
    elapsed: Option<Duration>,
) {
    let correlation_id = *next_correlation_id;
    *next_correlation_id = next_correlation_id.saturating_add(1);
    let elapsed_us = elapsed.map(|dur| u64::try_from(dur.as_micros()).unwrap_or(u64::MAX));
    traces.push(HookTraceEvent {
        ts_ms: system_time_ms(),
        correlation_id,
        class,
        stage,
        hook_id,
        reject_reason,
        elapsed_us,
    });
}

fn dispatch_registered_hooks<E, F>(
    hooks: &mut [HookEntry<F>],
    event: &E,
    class: HookClass,
    max_runtime: Duration,
    traces: &mut Vec<HookTraceEvent>,
    next_correlation_id: &mut u64,
) -> bool
where
    F: FnMut(&E) -> HookDisposition,
{
    for entry in hooks {
        let started = Instant::now();
        let outcome = with_panic_cleanup_suppressed(|| {
            catch_unwind(AssertUnwindSafe(|| (entry.callback)(event)))
        });
        let elapsed = started.elapsed();

        push_hook_trace(
            traces,
            next_correlation_id,
            class,
            HookTraceStage::HookInvoked,
            Some(entry.id),
            None,
            Some(elapsed),
        );

        if elapsed > max_runtime {
            push_hook_trace(
                traces,
                next_correlation_id,
                class,
                HookTraceStage::PolicyRejected,
                Some(entry.id),
                Some(HookRejectReason::TimeoutExceeded),
                Some(elapsed),
            );
            continue;
        }

        match outcome {
            Ok(HookDisposition::Continue) => {}
            Ok(HookDisposition::Consume) => {
                push_hook_trace(
                    traces,
                    next_correlation_id,
                    class,
                    HookTraceStage::HookConsumed,
                    Some(entry.id),
                    None,
                    Some(elapsed),
                );
                return true;
            }
            Ok(HookDisposition::Reject) => {
                push_hook_trace(
                    traces,
                    next_correlation_id,
                    class,
                    HookTraceStage::PolicyRejected,
                    Some(entry.id),
                    Some(HookRejectReason::HookRejected),
                    Some(elapsed),
                );
            }
            Err(_) => {
                push_hook_trace(
                    traces,
                    next_correlation_id,
                    class,
                    HookTraceStage::PolicyRejected,
                    Some(entry.id),
                    Some(HookRejectReason::HookPanicked),
                    Some(elapsed),
                );
            }
        }
    }
    false
}

/// Handler trait for ANSI escape sequence events.
///
/// Implement this trait to receive parsed ANSI events from [`AnsiParser`].
///
/// # Example
///
/// ```ignore
/// use ftui_extras::terminal::AnsiHandler;
///
/// struct MyTerminal {
///     cursor_x: u16,
///     cursor_y: u16,
/// }
///
/// impl AnsiHandler for MyTerminal {
///     fn print(&mut self, c: char) {
///         // Handle printable character
///     }
///
///     fn csi_dispatch(&mut self, params: &[i64], intermediates: &[u8], c: char) {
///         match c {
///             'A' => self.cursor_y = self.cursor_y.saturating_sub(params.first().copied().unwrap_or(1) as u16),
///             'B' => self.cursor_y += params.first().copied().unwrap_or(1) as u16,
///             _ => {}
///         }
///     }
///     // ... other methods
/// }
/// ```
pub trait AnsiHandler {
    /// Handle a printable character.
    ///
    /// Called for each printable Unicode character in the input stream.
    fn print(&mut self, c: char);

    /// Handle a C0/C1 control code.
    ///
    /// Common codes:
    /// - `0x07` (BEL): Bell
    /// - `0x08` (BS): Backspace
    /// - `0x09` (HT): Horizontal tab
    /// - `0x0A` (LF): Line feed
    /// - `0x0D` (CR): Carriage return
    fn execute(&mut self, byte: u8);

    /// Handle a CSI (Control Sequence Introducer) sequence.
    ///
    /// CSI sequences start with `ESC [` and are the primary mechanism for
    /// cursor movement, text styling, and screen manipulation.
    ///
    /// # Arguments
    ///
    /// * `params` - Numeric parameters (semicolon-separated in the sequence)
    /// * `intermediates` - Intermediate bytes (e.g., `?` for DEC private modes)
    /// * `c` - The final byte that identifies the command
    ///
    /// # Common Commands
    ///
    /// | Final | Meaning |
    /// |-------|---------|
    /// | `A` | Cursor up |
    /// | `B` | Cursor down |
    /// | `C` | Cursor forward |
    /// | `D` | Cursor back |
    /// | `H` | Cursor position |
    /// | `J` | Erase display |
    /// | `K` | Erase line |
    /// | `m` | SGR (Select Graphic Rendition) |
    /// | `h` | Set mode (with `?` for DEC private) |
    /// | `l` | Reset mode (with `?` for DEC private) |
    fn csi_dispatch(&mut self, params: &[i64], intermediates: &[u8], c: char);

    /// Handle an OSC (Operating System Command) sequence.
    ///
    /// OSC sequences start with `ESC ]` and are used for things like
    /// setting the window title or clipboard operations.
    ///
    /// # Arguments
    ///
    /// * `params` - The parsed OSC parameters (semicolon-separated strings)
    ///
    /// # Common OSC Commands
    ///
    /// | Code | Meaning |
    /// |------|---------|
    /// | 0 | Set icon name and window title |
    /// | 2 | Set window title |
    /// | 52 | Clipboard operations |
    fn osc_dispatch(&mut self, params: &[&[u8]]);

    /// Handle an ESC sequence (non-CSI, non-OSC).
    ///
    /// # Arguments
    ///
    /// * `intermediates` - Intermediate bytes between ESC and final byte
    /// * `c` - The final byte
    ///
    /// # Common Sequences
    ///
    /// | Sequence | Meaning |
    /// |----------|---------|
    /// | `ESC 7` | Save cursor (DECSC) |
    /// | `ESC 8` | Restore cursor (DECRC) |
    /// | `ESC D` | Index (move down, scroll if needed) |
    /// | `ESC M` | Reverse index (move up, scroll if needed) |
    /// | `ESC c` | Full reset (RIS) |
    fn esc_dispatch(&mut self, intermediates: &[u8], c: char);

    /// Handle a DCS (Device Control String) hook.
    ///
    /// Called when entering a DCS sequence. Override if you need to handle
    /// sixel graphics or other DCS data.
    #[allow(unused_variables)]
    fn hook(&mut self, params: &[i64], intermediates: &[u8], c: char) {
        // Default: ignore
    }

    /// Handle DCS data bytes.
    #[allow(unused_variables)]
    fn put(&mut self, byte: u8) {
        // Default: ignore
    }

    /// Handle DCS sequence end.
    fn unhook(&mut self) {
        // Default: ignore
    }
}

/// Adapter that bridges vte's `Perform` trait to our `AnsiHandler` trait.
struct VteAdapter<'a, H: AnsiHandler> {
    handler: &'a mut H,
    hooks: &'a mut HookRegistry,
    policy: HookPolicy,
    capabilities: HookCapabilities,
    traces: &'a mut Vec<HookTraceEvent>,
    next_correlation_id: &'a mut u64,
    budget: HookDispatchBudget,
}

impl<H: AnsiHandler> VteAdapter<'_, H> {
    fn record_policy_rejection(&mut self, class: HookClass, reason: HookRejectReason) {
        push_hook_trace(
            self.traces,
            self.next_correlation_id,
            class,
            HookTraceStage::PolicyRejected,
            None,
            Some(reason),
            None,
        );
    }

    fn record_fallback(&mut self, class: HookClass) {
        push_hook_trace(
            self.traces,
            self.next_correlation_id,
            class,
            HookTraceStage::FallbackDispatched,
            None,
            None,
            None,
        );
    }

    fn dispatch_csi_hooks(&mut self, event: &CsiHookEvent) -> bool {
        if self.hooks.csi.is_empty() {
            return false;
        }

        if !self.capabilities.csi {
            self.record_policy_rejection(HookClass::Csi, HookRejectReason::CapabilityDisabled);
            return false;
        }

        if self.budget.csi_invocations >= self.policy.max_csi_invocations_per_parse {
            self.record_policy_rejection(HookClass::Csi, HookRejectReason::QuotaExceeded);
            return false;
        }
        self.budget.csi_invocations = self.budget.csi_invocations.saturating_add(1);

        dispatch_registered_hooks(
            &mut self.hooks.csi,
            event,
            HookClass::Csi,
            self.policy.max_hook_runtime,
            self.traces,
            self.next_correlation_id,
        )
    }

    fn dispatch_osc_hooks(&mut self, event: &OscHookEvent) -> bool {
        if self.hooks.osc.is_empty() {
            return false;
        }

        if !self.capabilities.osc {
            self.record_policy_rejection(HookClass::Osc, HookRejectReason::CapabilityDisabled);
            return false;
        }

        if self.budget.osc_invocations >= self.policy.max_osc_invocations_per_parse {
            self.record_policy_rejection(HookClass::Osc, HookRejectReason::QuotaExceeded);
            return false;
        }
        self.budget.osc_invocations = self.budget.osc_invocations.saturating_add(1);

        dispatch_registered_hooks(
            &mut self.hooks.osc,
            event,
            HookClass::Osc,
            self.policy.max_hook_runtime,
            self.traces,
            self.next_correlation_id,
        )
    }

    fn dispatch_esc_hooks(&mut self, event: &EscHookEvent) -> bool {
        if self.hooks.esc.is_empty() {
            return false;
        }

        if !self.capabilities.esc {
            self.record_policy_rejection(HookClass::Esc, HookRejectReason::CapabilityDisabled);
            return false;
        }

        if self.budget.esc_invocations >= self.policy.max_esc_invocations_per_parse {
            self.record_policy_rejection(HookClass::Esc, HookRejectReason::QuotaExceeded);
            return false;
        }
        self.budget.esc_invocations = self.budget.esc_invocations.saturating_add(1);

        dispatch_registered_hooks(
            &mut self.hooks.esc,
            event,
            HookClass::Esc,
            self.policy.max_hook_runtime,
            self.traces,
            self.next_correlation_id,
        )
    }

    fn dispatch_dcs_hooks(&mut self, event: &DcsHookEvent) -> bool {
        if self.hooks.dcs.is_empty() {
            return false;
        }

        if !self.capabilities.dcs {
            self.record_policy_rejection(HookClass::Dcs, HookRejectReason::CapabilityDisabled);
            return false;
        }

        if self.budget.dcs_invocations >= self.policy.max_dcs_invocations_per_parse {
            self.record_policy_rejection(HookClass::Dcs, HookRejectReason::QuotaExceeded);
            return false;
        }

        if matches!(event, DcsHookEvent::Put { .. })
            && self.budget.dcs_bytes >= self.policy.max_dcs_bytes_per_parse
        {
            self.record_policy_rejection(HookClass::Dcs, HookRejectReason::QuotaExceeded);
            return false;
        }

        self.budget.dcs_invocations = self.budget.dcs_invocations.saturating_add(1);
        if matches!(event, DcsHookEvent::Put { .. }) {
            self.budget.dcs_bytes = self.budget.dcs_bytes.saturating_add(1);
        }

        dispatch_registered_hooks(
            &mut self.hooks.dcs,
            event,
            HookClass::Dcs,
            self.policy.max_hook_runtime,
            self.traces,
            self.next_correlation_id,
        )
    }
}

impl<H: AnsiHandler> Perform for VteAdapter<'_, H> {
    fn print(&mut self, c: char) {
        self.handler.print(c);
    }

    fn execute(&mut self, byte: u8) {
        self.handler.execute(byte);
    }

    fn csi_dispatch(&mut self, params: &vte::Params, intermediates: &[u8], _ignore: bool, c: char) {
        // Convert vte::Params to Vec<i64>
        let params: Vec<i64> = params
            .iter()
            .flat_map(|subparams| subparams.iter().map(|&v| i64::from(v)))
            .collect();
        let intermediates = intermediates.to_vec();
        let event = CsiHookEvent {
            params: params.clone(),
            intermediates: intermediates.clone(),
            final_byte: c,
        };

        if self.dispatch_csi_hooks(&event) {
            return;
        }

        self.record_fallback(HookClass::Csi);
        self.handler.csi_dispatch(&params, &intermediates, c);
    }

    fn osc_dispatch(&mut self, params: &[&[u8]], _bell_terminated: bool) {
        let params: Vec<Vec<u8>> = params.iter().map(|param| param.to_vec()).collect();
        let event = OscHookEvent {
            params: params.clone(),
        };
        if self.dispatch_osc_hooks(&event) {
            return;
        }

        self.record_fallback(HookClass::Osc);
        let refs: Vec<&[u8]> = params.iter().map(Vec::as_slice).collect();
        self.handler.osc_dispatch(&refs);
    }

    fn esc_dispatch(&mut self, intermediates: &[u8], _ignore: bool, byte: u8) {
        let final_byte = char::from(byte);
        let intermediates = intermediates.to_vec();
        let event = EscHookEvent {
            intermediates: intermediates.clone(),
            final_byte,
        };
        if self.dispatch_esc_hooks(&event) {
            return;
        }

        self.record_fallback(HookClass::Esc);
        self.handler.esc_dispatch(&intermediates, final_byte);
    }

    fn hook(&mut self, params: &vte::Params, intermediates: &[u8], _ignore: bool, c: char) {
        let params: Vec<i64> = params
            .iter()
            .flat_map(|subparams| subparams.iter().map(|&v| i64::from(v)))
            .collect();
        let intermediates = intermediates.to_vec();
        let event = DcsHookEvent::Hook {
            params: params.clone(),
            intermediates: intermediates.clone(),
            final_byte: c,
        };
        if self.dispatch_dcs_hooks(&event) {
            return;
        }

        self.record_fallback(HookClass::Dcs);
        self.handler.hook(&params, &intermediates, c);
    }

    fn put(&mut self, byte: u8) {
        let event = DcsHookEvent::Put { byte };
        if self.dispatch_dcs_hooks(&event) {
            return;
        }

        self.record_fallback(HookClass::Dcs);
        self.handler.put(byte);
    }

    fn unhook(&mut self) {
        let event = DcsHookEvent::Unhook;
        if self.dispatch_dcs_hooks(&event) {
            return;
        }

        self.record_fallback(HookClass::Dcs);
        self.handler.unhook();
    }
}

/// ANSI escape sequence parser.
///
/// Wraps the `vte` crate's parser and dispatches events to an [`AnsiHandler`].
///
/// # Example
///
/// ```ignore
/// use ftui_extras::terminal::{AnsiParser, AnsiHandler};
///
/// struct MyHandler;
/// impl AnsiHandler for MyHandler {
///     fn print(&mut self, c: char) { print!("{}", c); }
///     fn execute(&mut self, byte: u8) {}
///     fn csi_dispatch(&mut self, params: &[i64], intermediates: &[u8], c: char) {}
///     fn osc_dispatch(&mut self, params: &[&[u8]]) {}
///     fn esc_dispatch(&mut self, intermediates: &[u8], c: char) {}
/// }
///
/// let mut parser = AnsiParser::new();
/// let mut handler = MyHandler;
/// parser.parse(b"\x1b[31mHello\x1b[0m", &mut handler);
/// ```
pub struct AnsiParser {
    inner: Parser,
    hooks: HookRegistry,
    hook_policy: HookPolicy,
    hook_capabilities: HookCapabilities,
    hook_trace: Vec<HookTraceEvent>,
    next_correlation_id: u64,
}

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

impl AnsiParser {
    /// Create a new ANSI parser.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: Parser::new(),
            hooks: HookRegistry::default(),
            hook_policy: HookPolicy::default(),
            hook_capabilities: HookCapabilities::default(),
            hook_trace: Vec::new(),
            next_correlation_id: 1,
        }
    }

    /// Parse bytes and dispatch events to the handler.
    ///
    /// This method can be called repeatedly with chunks of data. The parser
    /// maintains state between calls to handle sequences that span chunks.
    pub fn parse<H: AnsiHandler>(&mut self, data: &[u8], handler: &mut H) {
        let mut adapter = VteAdapter {
            handler,
            hooks: &mut self.hooks,
            policy: self.hook_policy,
            capabilities: self.hook_capabilities,
            traces: &mut self.hook_trace,
            next_correlation_id: &mut self.next_correlation_id,
            budget: HookDispatchBudget::default(),
        };
        self.inner.advance(&mut adapter, data);
    }

    /// Register a deterministic CSI hook callback.
    ///
    /// Hooks are invoked in registration order.
    pub fn register_csi_hook<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&CsiHookEvent) -> HookDisposition + 'static,
    {
        self.hooks.register_csi(callback)
    }

    /// Register a deterministic OSC hook callback.
    ///
    /// Hooks are invoked in registration order.
    pub fn register_osc_hook<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&OscHookEvent) -> HookDisposition + 'static,
    {
        self.hooks.register_osc(callback)
    }

    /// Register a deterministic ESC hook callback.
    ///
    /// Hooks are invoked in registration order.
    pub fn register_esc_hook<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&EscHookEvent) -> HookDisposition + 'static,
    {
        self.hooks.register_esc(callback)
    }

    /// Register a deterministic DCS hook callback.
    ///
    /// Hooks are invoked in registration order.
    pub fn register_dcs_hook<F>(&mut self, callback: F) -> HookId
    where
        F: FnMut(&DcsHookEvent) -> HookDisposition + 'static,
    {
        self.hooks.register_dcs(callback)
    }

    /// Deregister a previously registered hook.
    ///
    /// Returns `true` when a hook was removed.
    pub fn deregister_hook(&mut self, id: HookId) -> bool {
        self.hooks.deregister(id)
    }

    /// Remove all registered parser hooks.
    pub fn clear_hooks(&mut self) {
        self.hooks.clear();
    }

    /// Set parse-time hook policy controls.
    pub fn set_hook_policy(&mut self, policy: HookPolicy) {
        self.hook_policy = policy;
    }

    /// Read the active parse-time hook policy.
    #[must_use]
    pub const fn hook_policy(&self) -> HookPolicy {
        self.hook_policy
    }

    /// Set hook capability gates.
    pub fn set_hook_capabilities(&mut self, capabilities: HookCapabilities) {
        self.hook_capabilities = capabilities;
    }

    /// Read active hook capability gates.
    #[must_use]
    pub const fn hook_capabilities(&self) -> HookCapabilities {
        self.hook_capabilities
    }

    /// Borrow the accumulated structured hook trace log.
    #[must_use]
    pub fn hook_trace(&self) -> &[HookTraceEvent] {
        &self.hook_trace
    }

    /// Drain and return structured hook trace records.
    pub fn drain_hook_trace(&mut self) -> Vec<HookTraceEvent> {
        std::mem::take(&mut self.hook_trace)
    }

    /// Reset the parser to initial state.
    ///
    /// Call this after a protocol error or when starting a new parsing session.
    pub fn reset(&mut self) {
        self.inner = Parser::new();
    }
}

impl std::fmt::Debug for AnsiParser {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AnsiParser").finish_non_exhaustive()
    }
}

/// SGR (Select Graphic Rendition) parameter values.
///
/// These constants map to the numeric parameters used in `ESC [ ... m` sequences.
pub mod sgr {
    /// Reset all attributes
    pub const RESET: i64 = 0;
    /// Bold/bright
    pub const BOLD: i64 = 1;
    /// Dim/faint
    pub const DIM: i64 = 2;
    /// Italic
    pub const ITALIC: i64 = 3;
    /// Underline
    pub const UNDERLINE: i64 = 4;
    /// Slow blink
    pub const BLINK: i64 = 5;
    /// Reverse video
    pub const REVERSE: i64 = 7;
    /// Hidden/invisible
    pub const HIDDEN: i64 = 8;
    /// Strikethrough
    pub const STRIKETHROUGH: i64 = 9;

    /// Reset bold/dim
    pub const NORMAL_INTENSITY: i64 = 22;
    /// Reset italic
    pub const NO_ITALIC: i64 = 23;
    /// Reset underline
    pub const NO_UNDERLINE: i64 = 24;
    /// Reset blink
    pub const NO_BLINK: i64 = 25;
    /// Reset reverse
    pub const NO_REVERSE: i64 = 27;
    /// Reset hidden
    pub const NO_HIDDEN: i64 = 28;
    /// Reset strikethrough
    pub const NO_STRIKETHROUGH: i64 = 29;

    /// Black foreground
    pub const FG_BLACK: i64 = 30;
    /// Red foreground
    pub const FG_RED: i64 = 31;
    /// Green foreground
    pub const FG_GREEN: i64 = 32;
    /// Yellow foreground
    pub const FG_YELLOW: i64 = 33;
    /// Blue foreground
    pub const FG_BLUE: i64 = 34;
    /// Magenta foreground
    pub const FG_MAGENTA: i64 = 35;
    /// Cyan foreground
    pub const FG_CYAN: i64 = 36;
    /// White foreground
    pub const FG_WHITE: i64 = 37;
    /// Extended foreground color (256 or RGB)
    pub const FG_EXTENDED: i64 = 38;
    /// Default foreground
    pub const FG_DEFAULT: i64 = 39;

    /// Black background
    pub const BG_BLACK: i64 = 40;
    /// Red background
    pub const BG_RED: i64 = 41;
    /// Green background
    pub const BG_GREEN: i64 = 42;
    /// Yellow background
    pub const BG_YELLOW: i64 = 43;
    /// Blue background
    pub const BG_BLUE: i64 = 44;
    /// Magenta background
    pub const BG_MAGENTA: i64 = 45;
    /// Cyan background
    pub const BG_CYAN: i64 = 46;
    /// White background
    pub const BG_WHITE: i64 = 47;
    /// Extended background color (256 or RGB)
    pub const BG_EXTENDED: i64 = 48;
    /// Default background
    pub const BG_DEFAULT: i64 = 49;

    /// Bright black foreground
    pub const FG_BRIGHT_BLACK: i64 = 90;
    /// Bright red foreground
    pub const FG_BRIGHT_RED: i64 = 91;
    /// Bright green foreground
    pub const FG_BRIGHT_GREEN: i64 = 92;
    /// Bright yellow foreground
    pub const FG_BRIGHT_YELLOW: i64 = 93;
    /// Bright blue foreground
    pub const FG_BRIGHT_BLUE: i64 = 94;
    /// Bright magenta foreground
    pub const FG_BRIGHT_MAGENTA: i64 = 95;
    /// Bright cyan foreground
    pub const FG_BRIGHT_CYAN: i64 = 96;
    /// Bright white foreground
    pub const FG_BRIGHT_WHITE: i64 = 97;

    /// Bright black background
    pub const BG_BRIGHT_BLACK: i64 = 100;
    /// Bright red background
    pub const BG_BRIGHT_RED: i64 = 101;
    /// Bright green background
    pub const BG_BRIGHT_GREEN: i64 = 102;
    /// Bright yellow background
    pub const BG_BRIGHT_YELLOW: i64 = 103;
    /// Bright blue background
    pub const BG_BRIGHT_BLUE: i64 = 104;
    /// Bright magenta background
    pub const BG_BRIGHT_MAGENTA: i64 = 105;
    /// Bright cyan background
    pub const BG_BRIGHT_CYAN: i64 = 106;
    /// Bright white background
    pub const BG_BRIGHT_WHITE: i64 = 107;

    /// 256-color mode indicator (used after FG_EXTENDED or BG_EXTENDED)
    pub const COLOR_256: i64 = 5;
    /// RGB color mode indicator (used after FG_EXTENDED or BG_EXTENDED)
    pub const COLOR_RGB: i64 = 2;
}

/// DEC private mode numbers (used with CSI ? h/l sequences).
pub mod dec_mode {
    /// Cursor visible
    pub const CURSOR_VISIBLE: i64 = 25;
    /// Alternate screen buffer
    pub const ALT_SCREEN: i64 = 1049;
    /// Alternate screen (no save/restore)
    pub const ALT_SCREEN_NO_CLEAR: i64 = 1047;
    /// Save cursor before alt screen
    pub const SAVE_CURSOR: i64 = 1048;
    /// Mouse tracking: normal
    pub const MOUSE_TRACKING: i64 = 1000;
    /// Mouse tracking: button events
    pub const MOUSE_BUTTON: i64 = 1002;
    /// Mouse tracking: any event
    pub const MOUSE_ANY: i64 = 1003;
    /// Mouse tracking: SGR extended mode
    pub const MOUSE_SGR: i64 = 1006;
    /// Focus events
    pub const FOCUS: i64 = 1004;
    /// Bracketed paste mode
    pub const BRACKETED_PASTE: i64 = 2004;
}

/// Parse SGR parameters into attribute changes.
///
/// This is a helper for implementing `csi_dispatch` when `c == 'm'`.
///
/// # Returns
///
/// An iterator over `SgrChange` values describing the attribute changes.
pub fn parse_sgr(params: &[i64]) -> impl Iterator<Item = SgrChange> + '_ {
    SgrIterator::new(params)
}

/// A single SGR attribute change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SgrChange {
    /// Reset all attributes
    Reset,
    /// Set bold
    Bold(bool),
    /// Set dim
    Dim(bool),
    /// Set italic
    Italic(bool),
    /// Set underline
    Underline(bool),
    /// Set blink
    Blink(bool),
    /// Set reverse video
    Reverse(bool),
    /// Set hidden
    Hidden(bool),
    /// Set strikethrough
    Strikethrough(bool),
    /// Set foreground to ANSI color (0-7)
    FgAnsi(u8),
    /// Set foreground to bright ANSI color (0-7 maps to 8-15)
    FgBrightAnsi(u8),
    /// Set foreground to 256-color palette
    Fg256(u8),
    /// Set foreground to RGB
    FgRgb(u8, u8, u8),
    /// Reset foreground to default
    FgDefault,
    /// Set background to ANSI color (0-7)
    BgAnsi(u8),
    /// Set background to bright ANSI color (0-7 maps to 8-15)
    BgBrightAnsi(u8),
    /// Set background to 256-color palette
    Bg256(u8),
    /// Set background to RGB
    BgRgb(u8, u8, u8),
    /// Reset background to default
    BgDefault,
}

/// Iterator over SGR changes.
struct SgrIterator<'a> {
    params: &'a [i64],
    index: usize,
}

impl<'a> SgrIterator<'a> {
    fn new(params: &'a [i64]) -> Self {
        Self { params, index: 0 }
    }

    fn next_param(&mut self) -> Option<i64> {
        if self.index < self.params.len() {
            let val = self.params[self.index];
            self.index += 1;
            Some(val)
        } else {
            None
        }
    }

    fn parse_extended_color(&mut self) -> Option<SgrChange> {
        let mode = self.next_param()?;
        match mode {
            5 => {
                // 256-color mode: 38;5;N or 48;5;N
                let color = self.next_param()?;
                Some(SgrChange::Fg256(color.clamp(0, 255) as u8))
            }
            2 => {
                // RGB mode: 38;2;R;G;B or 48;2;R;G;B
                let r = self.next_param()?;
                let g = self.next_param()?;
                let b = self.next_param()?;
                Some(SgrChange::FgRgb(
                    r.clamp(0, 255) as u8,
                    g.clamp(0, 255) as u8,
                    b.clamp(0, 255) as u8,
                ))
            }
            _ => None,
        }
    }

    fn parse_extended_bg_color(&mut self) -> Option<SgrChange> {
        let mode = self.next_param()?;
        match mode {
            5 => {
                let color = self.next_param()?;
                Some(SgrChange::Bg256(color.clamp(0, 255) as u8))
            }
            2 => {
                let r = self.next_param()?;
                let g = self.next_param()?;
                let b = self.next_param()?;
                Some(SgrChange::BgRgb(
                    r.clamp(0, 255) as u8,
                    g.clamp(0, 255) as u8,
                    b.clamp(0, 255) as u8,
                ))
            }
            _ => None,
        }
    }
}

impl Iterator for SgrIterator<'_> {
    type Item = SgrChange;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let param = self.next_param()?;

            let change = match param {
                0 => SgrChange::Reset,
                1 => SgrChange::Bold(true),
                2 => SgrChange::Dim(true),
                3 => SgrChange::Italic(true),
                4 => SgrChange::Underline(true),
                5 => SgrChange::Blink(true),
                7 => SgrChange::Reverse(true),
                8 => SgrChange::Hidden(true),
                9 => SgrChange::Strikethrough(true),
                22 => {
                    // Reset both bold and dim
                    return Some(SgrChange::Bold(false));
                }
                23 => SgrChange::Italic(false),
                24 => SgrChange::Underline(false),
                25 => SgrChange::Blink(false),
                27 => SgrChange::Reverse(false),
                28 => SgrChange::Hidden(false),
                29 => SgrChange::Strikethrough(false),
                30..=37 => SgrChange::FgAnsi((param - 30) as u8),
                38 => {
                    if let Some(change) = self.parse_extended_color() {
                        return Some(change);
                    }
                    continue;
                }
                39 => SgrChange::FgDefault,
                40..=47 => SgrChange::BgAnsi((param - 40) as u8),
                48 => {
                    if let Some(change) = self.parse_extended_bg_color() {
                        return Some(change);
                    }
                    continue;
                }
                49 => SgrChange::BgDefault,
                90..=97 => SgrChange::FgBrightAnsi((param - 90) as u8),
                100..=107 => SgrChange::BgBrightAnsi((param - 100) as u8),
                _ => continue, // Unknown SGR parameter
            };

            return Some(change);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;
    use std::thread;

    /// Test handler that records all events.
    #[derive(Default)]
    #[allow(clippy::type_complexity)]
    struct TestHandler {
        printed: RefCell<Vec<char>>,
        executed: RefCell<Vec<u8>>,
        csi_calls: RefCell<Vec<(Vec<i64>, Vec<u8>, char)>>,
        osc_calls: RefCell<Vec<Vec<Vec<u8>>>>,
        esc_calls: RefCell<Vec<(Vec<u8>, char)>>,
    }

    impl AnsiHandler for TestHandler {
        fn print(&mut self, c: char) {
            self.printed.borrow_mut().push(c);
        }

        fn execute(&mut self, byte: u8) {
            self.executed.borrow_mut().push(byte);
        }

        fn csi_dispatch(&mut self, params: &[i64], intermediates: &[u8], c: char) {
            self.csi_calls
                .borrow_mut()
                .push((params.to_vec(), intermediates.to_vec(), c));
        }

        fn osc_dispatch(&mut self, params: &[&[u8]]) {
            self.osc_calls
                .borrow_mut()
                .push(params.iter().map(|p| p.to_vec()).collect());
        }

        fn esc_dispatch(&mut self, intermediates: &[u8], c: char) {
            self.esc_calls
                .borrow_mut()
                .push((intermediates.to_vec(), c));
        }
    }

    #[test]
    fn parse_plain_text() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"Hello", &mut handler);

        let printed: Vec<char> = handler.printed.borrow().clone();
        assert_eq!(printed, vec!['H', 'e', 'l', 'l', 'o']);
    }

    #[test]
    fn parse_control_codes() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"A\nB\rC\tD", &mut handler);

        let printed: Vec<char> = handler.printed.borrow().clone();
        assert_eq!(printed, vec!['A', 'B', 'C', 'D']);

        let executed: Vec<u8> = handler.executed.borrow().clone();
        assert_eq!(executed, vec![b'\n', b'\r', b'\t']);
    }

    #[test]
    fn parse_csi_cursor_up() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ 5 A - cursor up 5
        parser.parse(b"\x1b[5A", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![5]);
        assert_eq!(csi_calls[0].2, 'A');
    }

    #[test]
    fn parse_csi_cursor_position() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ 10 ; 20 H - cursor to row 10, col 20
        parser.parse(b"\x1b[10;20H", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![10, 20]);
        assert_eq!(csi_calls[0].2, 'H');
    }

    #[test]
    fn parse_csi_sgr_colors() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ 1 ; 31 m - bold red
        parser.parse(b"\x1b[1;31m", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![1, 31]);
        assert_eq!(csi_calls[0].2, 'm');
    }

    #[test]
    fn parse_csi_dec_private_mode() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ ? 25 h - show cursor
        parser.parse(b"\x1b[?25h", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].1, vec![b'?']);
        assert_eq!(csi_calls[0].2, 'h');
    }

    #[test]
    fn parse_osc_title() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // OSC 0 ; title BEL
        parser.parse(b"\x1b]0;My Title\x07", &mut handler);

        let osc_calls = handler.osc_calls.borrow();
        assert_eq!(osc_calls.len(), 1);
        assert_eq!(osc_calls[0].len(), 2);
        assert_eq!(osc_calls[0][0], b"0");
        assert_eq!(osc_calls[0][1], b"My Title");
    }

    #[test]
    fn parse_esc_save_cursor() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC 7 - save cursor
        parser.parse(b"\x1b7", &mut handler);

        let esc_calls = handler.esc_calls.borrow();
        assert_eq!(esc_calls.len(), 1);
        assert_eq!(esc_calls[0].1, '7');
    }

    #[test]
    fn parse_mixed_content() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\x1b[31mHello\x1b[0m World", &mut handler);

        let printed: Vec<char> = handler.printed.borrow().clone();
        assert_eq!(
            printed,
            vec!['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
        );

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 2); // [31m and [0m
    }

    #[test]
    fn parse_utf8() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse("Hello, 世界! 🎉".as_bytes(), &mut handler);

        let printed: Vec<char> = handler.printed.borrow().clone();
        assert!(printed.contains(&''));
        assert!(printed.contains(&''));
        assert!(printed.contains(&'🎉'));
    }

    #[test]
    fn parse_incomplete_sequence_buffered() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Send partial sequence
        parser.parse(b"\x1b[1", &mut handler);
        assert!(handler.csi_calls.borrow().is_empty());

        // Complete the sequence
        parser.parse(b";31m", &mut handler);
        assert_eq!(handler.csi_calls.borrow().len(), 1);
    }

    #[test]
    fn reset_clears_state() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Start a sequence
        parser.parse(b"\x1b[1", &mut handler);

        // Reset
        parser.reset();

        // New sequence should work
        parser.parse(b"\x1b[5A", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![5]);
    }

    #[test]
    fn csi_hook_registration_is_ordered_and_deregisterable() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();
        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));

        let order_first = Rc::clone(&order);
        parser.register_csi_hook(move |_event| {
            order_first.borrow_mut().push("first");
            HookDisposition::Continue
        });

        let order_second = Rc::clone(&order);
        let consumer_id = parser.register_csi_hook(move |_event| {
            order_second.borrow_mut().push("second");
            HookDisposition::Consume
        });

        parser.parse(b"\x1b[5A", &mut handler);

        assert_eq!(*order.borrow(), vec!["first", "second"]);
        assert!(handler.csi_calls.borrow().is_empty());
        assert!(
            parser
                .hook_trace()
                .iter()
                .any(|event| event.class == HookClass::Csi
                    && event.stage == HookTraceStage::HookConsumed)
        );

        assert!(parser.deregister_hook(consumer_id));
        parser.drain_hook_trace();
        parser.parse(b"\x1b[6A", &mut handler);
        assert_eq!(handler.csi_calls.borrow().len(), 1);
    }

    #[test]
    fn capability_gating_skips_hooks_and_records_rejection() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();
        let calls = Rc::new(RefCell::new(0_u32));
        let calls_for_hook = Rc::clone(&calls);

        parser.register_csi_hook(move |_event| {
            *calls_for_hook.borrow_mut() += 1;
            HookDisposition::Continue
        });

        parser.set_hook_capabilities(HookCapabilities {
            csi: false,
            ..HookCapabilities::default()
        });

        parser.parse(b"\x1b[1A", &mut handler);

        assert_eq!(*calls.borrow(), 0);
        assert_eq!(handler.csi_calls.borrow().len(), 1);

        let trace = parser.drain_hook_trace();
        assert!(trace.iter().any(|event| {
            event.class == HookClass::Csi
                && event.stage == HookTraceStage::PolicyRejected
                && event.reject_reason == Some(HookRejectReason::CapabilityDisabled)
        }));
        assert!(trace.iter().any(|event| {
            event.class == HookClass::Csi && event.stage == HookTraceStage::FallbackDispatched
        }));
    }

    #[test]
    fn csi_hook_quota_is_enforced_per_parse_call() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();
        let calls = Rc::new(RefCell::new(0_u32));
        let calls_for_hook = Rc::clone(&calls);

        parser.set_hook_policy(HookPolicy {
            max_csi_invocations_per_parse: 1,
            ..HookPolicy::default()
        });

        parser.register_csi_hook(move |_event| {
            *calls_for_hook.borrow_mut() += 1;
            HookDisposition::Continue
        });

        parser.parse(b"\x1b[1A\x1b[2B", &mut handler);

        assert_eq!(*calls.borrow(), 1);
        assert_eq!(handler.csi_calls.borrow().len(), 2);

        let trace = parser.drain_hook_trace();
        assert!(trace.iter().any(|event| {
            event.class == HookClass::Csi
                && event.stage == HookTraceStage::PolicyRejected
                && event.reject_reason == Some(HookRejectReason::QuotaExceeded)
        }));
    }

    #[test]
    fn hook_panic_is_isolated_and_falls_back_to_handler() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.register_csi_hook(|_event| -> HookDisposition {
            panic!("panic from hook should be isolated");
        });

        parser.parse(b"\x1b[3A", &mut handler);

        assert_eq!(handler.csi_calls.borrow().len(), 1);
        let trace = parser.drain_hook_trace();
        assert!(trace.iter().any(|event| {
            event.class == HookClass::Csi
                && event.stage == HookTraceStage::PolicyRejected
                && event.reject_reason == Some(HookRejectReason::HookPanicked)
        }));
    }

    #[test]
    fn hook_timeout_isolated_and_falls_back_to_handler() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.set_hook_policy(HookPolicy {
            max_hook_runtime: Duration::from_millis(1),
            ..HookPolicy::default()
        });
        parser.register_csi_hook(|_event| {
            thread::sleep(Duration::from_millis(3));
            HookDisposition::Consume
        });

        parser.parse(b"\x1b[4A", &mut handler);

        assert_eq!(handler.csi_calls.borrow().len(), 1);
        let trace = parser.drain_hook_trace();
        assert!(trace.iter().any(|event| {
            event.class == HookClass::Csi
                && event.stage == HookTraceStage::PolicyRejected
                && event.reject_reason == Some(HookRejectReason::TimeoutExceeded)
        }));
    }

    // ── SGR parsing tests ─────────────────────────────────────────────

    #[test]
    fn sgr_reset() {
        let changes: Vec<_> = parse_sgr(&[0]).collect();
        assert_eq!(changes, vec![SgrChange::Reset]);
    }

    #[test]
    fn sgr_bold_italic() {
        let changes: Vec<_> = parse_sgr(&[1, 3]).collect();
        assert_eq!(
            changes,
            vec![SgrChange::Bold(true), SgrChange::Italic(true)]
        );
    }

    #[test]
    fn sgr_fg_color() {
        let changes: Vec<_> = parse_sgr(&[31]).collect();
        assert_eq!(changes, vec![SgrChange::FgAnsi(1)]);
    }

    #[test]
    fn sgr_256_color() {
        let changes: Vec<_> = parse_sgr(&[38, 5, 196]).collect();
        assert_eq!(changes, vec![SgrChange::Fg256(196)]);
    }

    #[test]
    fn sgr_rgb_color() {
        let changes: Vec<_> = parse_sgr(&[38, 2, 100, 150, 200]).collect();
        assert_eq!(changes, vec![SgrChange::FgRgb(100, 150, 200)]);
    }

    #[test]
    fn sgr_bg_256_color() {
        let changes: Vec<_> = parse_sgr(&[48, 5, 21]).collect();
        assert_eq!(changes, vec![SgrChange::Bg256(21)]);
    }

    #[test]
    fn sgr_bg_rgb_color() {
        let changes: Vec<_> = parse_sgr(&[48, 2, 50, 100, 150]).collect();
        assert_eq!(changes, vec![SgrChange::BgRgb(50, 100, 150)]);
    }

    #[test]
    fn sgr_bright_colors() {
        let changes: Vec<_> = parse_sgr(&[91, 101]).collect();
        assert_eq!(
            changes,
            vec![SgrChange::FgBrightAnsi(1), SgrChange::BgBrightAnsi(1)]
        );
    }

    #[test]
    fn sgr_complex_sequence() {
        // Bold, red fg, blue bg, reset
        let changes: Vec<_> = parse_sgr(&[1, 31, 44, 0]).collect();
        assert_eq!(
            changes,
            vec![
                SgrChange::Bold(true),
                SgrChange::FgAnsi(1),
                SgrChange::BgAnsi(4),
                SgrChange::Reset,
            ]
        );
    }

    #[test]
    fn sgr_empty_treated_as_reset() {
        // Empty params should produce no changes (vte handles this at a higher level)
        let changes: Vec<_> = parse_sgr(&[]).collect();
        assert!(changes.is_empty());
    }

    #[test]
    fn sgr_defaults() {
        let changes: Vec<_> = parse_sgr(&[39, 49]).collect();
        assert_eq!(changes, vec![SgrChange::FgDefault, SgrChange::BgDefault]);
    }

    // ── DCS (Device Control String) tests ───────────────────────────────

    /// Extended handler that also records DCS events.
    #[derive(Default)]
    #[allow(clippy::type_complexity)]
    struct DcsTestHandler {
        printed: Vec<char>,
        hook_calls: Vec<(Vec<i64>, Vec<u8>, char)>,
        put_bytes: Vec<u8>,
        unhook_count: usize,
    }

    impl AnsiHandler for DcsTestHandler {
        fn print(&mut self, c: char) {
            self.printed.push(c);
        }
        fn execute(&mut self, _byte: u8) {}
        fn csi_dispatch(&mut self, _params: &[i64], _intermediates: &[u8], _c: char) {}
        fn osc_dispatch(&mut self, _params: &[&[u8]]) {}
        fn esc_dispatch(&mut self, _intermediates: &[u8], _c: char) {}
        fn hook(&mut self, params: &[i64], intermediates: &[u8], c: char) {
            self.hook_calls
                .push((params.to_vec(), intermediates.to_vec(), c));
        }
        fn put(&mut self, byte: u8) {
            self.put_bytes.push(byte);
        }
        fn unhook(&mut self) {
            self.unhook_count += 1;
        }
    }

    #[test]
    fn dcs_hook_put_unhook_roundtrip() {
        let mut parser = AnsiParser::new();
        let mut handler = DcsTestHandler::default();

        // DCS q (sixel): ESC P q <data> ESC backslash
        parser.parse(b"\x1bPq", &mut handler);
        assert_eq!(handler.hook_calls.len(), 1);
        assert_eq!(handler.hook_calls[0].2, 'q');

        // Send data bytes
        parser.parse(b"#0;2;0;0;0", &mut handler);
        assert!(!handler.put_bytes.is_empty());

        // End DCS with ST (ESC \)
        parser.parse(b"\x1b\\", &mut handler);
        assert_eq!(handler.unhook_count, 1);
    }

    #[test]
    fn dcs_with_params() {
        let mut parser = AnsiParser::new();
        let mut handler = DcsTestHandler::default();

        // DCS with params: ESC P 1;2 q
        parser.parse(b"\x1bP1;2q", &mut handler);
        assert_eq!(handler.hook_calls.len(), 1);
        assert_eq!(handler.hook_calls[0].0, vec![1, 2]);
        assert_eq!(handler.hook_calls[0].2, 'q');
    }

    #[test]
    fn dcs_hook_byte_quota_enforced_with_replay_trace() {
        let mut parser = AnsiParser::new();
        let mut handler = DcsTestHandler::default();
        let dcs_put_hook_calls = Rc::new(RefCell::new(0_usize));
        let dcs_put_hook_calls_for_hook = Rc::clone(&dcs_put_hook_calls);

        parser.set_hook_policy(HookPolicy {
            max_dcs_bytes_per_parse: 2,
            ..HookPolicy::default()
        });
        parser.register_dcs_hook(move |event| {
            if matches!(event, DcsHookEvent::Put { .. }) {
                *dcs_put_hook_calls_for_hook.borrow_mut() += 1;
            }
            HookDisposition::Continue
        });

        parser.parse(b"\x1bPqABCDE\x1b\\", &mut handler);

        assert_eq!(*dcs_put_hook_calls.borrow(), 2);
        assert_eq!(handler.put_bytes, b"ABCDE".to_vec());

        let trace = parser.drain_hook_trace();
        assert!(trace.iter().any(|event| {
            event.class == HookClass::Dcs
                && event.stage == HookTraceStage::PolicyRejected
                && event.reject_reason == Some(HookRejectReason::QuotaExceeded)
        }));
    }

    // ── ESC sequence variant tests ──────────────────────────────────────

    #[test]
    fn esc_restore_cursor() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC 8 - restore cursor
        parser.parse(b"\x1b8", &mut handler);

        let esc_calls = handler.esc_calls.borrow();
        assert_eq!(esc_calls.len(), 1);
        assert_eq!(esc_calls[0].1, '8');
    }

    #[test]
    fn esc_index_down() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC D - index (move down, scroll if needed)
        parser.parse(b"\x1bD", &mut handler);

        let esc_calls = handler.esc_calls.borrow();
        assert_eq!(esc_calls.len(), 1);
        assert_eq!(esc_calls[0].1, 'D');
        assert!(esc_calls[0].0.is_empty());
    }

    #[test]
    fn esc_reverse_index() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC M - reverse index (move up, scroll if needed)
        parser.parse(b"\x1bM", &mut handler);

        let esc_calls = handler.esc_calls.borrow();
        assert_eq!(esc_calls.len(), 1);
        assert_eq!(esc_calls[0].1, 'M');
    }

    #[test]
    fn esc_full_reset() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC c - full reset (RIS)
        parser.parse(b"\x1bc", &mut handler);

        let esc_calls = handler.esc_calls.borrow();
        assert_eq!(esc_calls.len(), 1);
        assert_eq!(esc_calls[0].1, 'c');
    }

    #[test]
    fn multiple_esc_sequences() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Save cursor, then restore cursor
        parser.parse(b"\x1b7\x1b8", &mut handler);

        let esc_calls = handler.esc_calls.borrow();
        assert_eq!(esc_calls.len(), 2);
        assert_eq!(esc_calls[0].1, '7');
        assert_eq!(esc_calls[1].1, '8');
    }

    // ── CSI sequence variant tests ──────────────────────────────────────

    #[test]
    fn csi_cursor_down() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\x1b[3B", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![3]);
        assert_eq!(csi_calls[0].2, 'B');
    }

    #[test]
    fn csi_cursor_forward() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\x1b[7C", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![7]);
        assert_eq!(csi_calls[0].2, 'C');
    }

    #[test]
    fn csi_cursor_back() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\x1b[2D", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![2]);
        assert_eq!(csi_calls[0].2, 'D');
    }

    #[test]
    fn csi_erase_display() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ 2 J - erase entire display
        parser.parse(b"\x1b[2J", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![2]);
        assert_eq!(csi_calls[0].2, 'J');
    }

    #[test]
    fn csi_erase_line() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ K - erase from cursor to end of line (default 0)
        parser.parse(b"\x1b[K", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].2, 'K');
    }

    #[test]
    fn csi_no_params_defaults() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ H - cursor home (no params = 1;1)
        parser.parse(b"\x1b[H", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].2, 'H');
        // vte delivers an empty or default param set
    }

    #[test]
    fn csi_alt_screen_enable() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ ? 1049 h - enable alt screen
        parser.parse(b"\x1b[?1049h", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![1049]);
        assert_eq!(csi_calls[0].1, vec![b'?']);
        assert_eq!(csi_calls[0].2, 'h');
    }

    #[test]
    fn csi_alt_screen_disable() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ ? 1049 l - disable alt screen
        parser.parse(b"\x1b[?1049l", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![1049]);
        assert_eq!(csi_calls[0].1, vec![b'?']);
        assert_eq!(csi_calls[0].2, 'l');
    }

    #[test]
    fn csi_bracketed_paste_mode() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ ? 2004 h - enable bracketed paste
        parser.parse(b"\x1b[?2004h", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);
        assert_eq!(csi_calls[0].0, vec![2004]);
        assert_eq!(csi_calls[0].1, vec![b'?']);
        assert_eq!(csi_calls[0].2, 'h');
    }

    #[test]
    fn multiple_csi_in_one_parse() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Cursor up, then cursor down, then erase line
        parser.parse(b"\x1b[5A\x1b[3B\x1b[K", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 3);
        assert_eq!(csi_calls[0].2, 'A');
        assert_eq!(csi_calls[1].2, 'B');
        assert_eq!(csi_calls[2].2, 'K');
    }

    // ── SGR individual attribute tests ──────────────────────────────────

    #[test]
    fn sgr_dim() {
        let changes: Vec<_> = parse_sgr(&[2]).collect();
        assert_eq!(changes, vec![SgrChange::Dim(true)]);
    }

    #[test]
    fn sgr_underline() {
        let changes: Vec<_> = parse_sgr(&[4]).collect();
        assert_eq!(changes, vec![SgrChange::Underline(true)]);
    }

    #[test]
    fn sgr_blink() {
        let changes: Vec<_> = parse_sgr(&[5]).collect();
        assert_eq!(changes, vec![SgrChange::Blink(true)]);
    }

    #[test]
    fn sgr_reverse() {
        let changes: Vec<_> = parse_sgr(&[7]).collect();
        assert_eq!(changes, vec![SgrChange::Reverse(true)]);
    }

    #[test]
    fn sgr_hidden() {
        let changes: Vec<_> = parse_sgr(&[8]).collect();
        assert_eq!(changes, vec![SgrChange::Hidden(true)]);
    }

    #[test]
    fn sgr_strikethrough() {
        let changes: Vec<_> = parse_sgr(&[9]).collect();
        assert_eq!(changes, vec![SgrChange::Strikethrough(true)]);
    }

    #[test]
    fn sgr_normal_intensity_resets_bold() {
        // SGR 22 resets both bold and dim, but implementation returns Bold(false)
        let changes: Vec<_> = parse_sgr(&[22]).collect();
        assert_eq!(changes, vec![SgrChange::Bold(false)]);
    }

    #[test]
    fn sgr_no_italic() {
        let changes: Vec<_> = parse_sgr(&[23]).collect();
        assert_eq!(changes, vec![SgrChange::Italic(false)]);
    }

    #[test]
    fn sgr_no_underline() {
        let changes: Vec<_> = parse_sgr(&[24]).collect();
        assert_eq!(changes, vec![SgrChange::Underline(false)]);
    }

    #[test]
    fn sgr_no_blink() {
        let changes: Vec<_> = parse_sgr(&[25]).collect();
        assert_eq!(changes, vec![SgrChange::Blink(false)]);
    }

    #[test]
    fn sgr_no_reverse() {
        let changes: Vec<_> = parse_sgr(&[27]).collect();
        assert_eq!(changes, vec![SgrChange::Reverse(false)]);
    }

    #[test]
    fn sgr_no_hidden() {
        let changes: Vec<_> = parse_sgr(&[28]).collect();
        assert_eq!(changes, vec![SgrChange::Hidden(false)]);
    }

    #[test]
    fn sgr_no_strikethrough() {
        let changes: Vec<_> = parse_sgr(&[29]).collect();
        assert_eq!(changes, vec![SgrChange::Strikethrough(false)]);
    }

    // ── SGR all standard colors ─────────────────────────────────────────

    #[test]
    fn sgr_all_standard_fg_colors() {
        for code in 30..=37 {
            let changes: Vec<_> = parse_sgr(&[code]).collect();
            assert_eq!(
                changes,
                vec![SgrChange::FgAnsi((code - 30) as u8)],
                "failed for SGR {code}"
            );
        }
    }

    #[test]
    fn sgr_all_standard_bg_colors() {
        for code in 40..=47 {
            let changes: Vec<_> = parse_sgr(&[code]).collect();
            assert_eq!(
                changes,
                vec![SgrChange::BgAnsi((code - 40) as u8)],
                "failed for SGR {code}"
            );
        }
    }

    #[test]
    fn sgr_all_bright_fg_colors() {
        for code in 90..=97 {
            let changes: Vec<_> = parse_sgr(&[code]).collect();
            assert_eq!(
                changes,
                vec![SgrChange::FgBrightAnsi((code - 90) as u8)],
                "failed for SGR {code}"
            );
        }
    }

    #[test]
    fn sgr_all_bright_bg_colors() {
        for code in 100..=107 {
            let changes: Vec<_> = parse_sgr(&[code]).collect();
            assert_eq!(
                changes,
                vec![SgrChange::BgBrightAnsi((code - 100) as u8)],
                "failed for SGR {code}"
            );
        }
    }

    // ── SGR extended color edge cases ───────────────────────────────────

    #[test]
    fn sgr_extended_fg_unknown_mode_skipped() {
        // 38;9 is not a valid color mode (only 2 and 5 are)
        let changes: Vec<_> = parse_sgr(&[38, 9]).collect();
        assert!(
            changes.is_empty(),
            "unknown extended mode should be skipped"
        );
    }

    #[test]
    fn sgr_extended_bg_unknown_mode_skipped() {
        // 48;9 is not a valid bg color mode
        let changes: Vec<_> = parse_sgr(&[48, 9]).collect();
        assert!(
            changes.is_empty(),
            "unknown extended bg mode should be skipped"
        );
    }

    #[test]
    fn sgr_extended_fg_truncated_256() {
        // 38;5 without the color index - next_param returns None
        let changes: Vec<_> = parse_sgr(&[38, 5]).collect();
        assert!(
            changes.is_empty(),
            "truncated 256-color should yield nothing"
        );
    }

    #[test]
    fn sgr_extended_fg_truncated_rgb_partial() {
        // 38;2;100;150 missing the B component
        let changes: Vec<_> = parse_sgr(&[38, 2, 100, 150]).collect();
        assert!(changes.is_empty(), "truncated RGB should yield nothing");
    }

    #[test]
    fn sgr_extended_fg_truncated_mode_only() {
        // 38 with no mode byte at all
        let changes: Vec<_> = parse_sgr(&[38]).collect();
        assert!(changes.is_empty(), "38 alone should yield nothing");
    }

    #[test]
    fn sgr_extended_bg_truncated_256() {
        // 48;5 without color index
        let changes: Vec<_> = parse_sgr(&[48, 5]).collect();
        assert!(
            changes.is_empty(),
            "truncated bg 256-color should yield nothing"
        );
    }

    #[test]
    fn sgr_extended_bg_truncated_rgb_partial() {
        // 48;2;50;100 missing B component
        let changes: Vec<_> = parse_sgr(&[48, 2, 50, 100]).collect();
        assert!(changes.is_empty(), "truncated bg RGB should yield nothing");
    }

    #[test]
    fn sgr_extended_bg_truncated_mode_only() {
        // 48 with no mode byte
        let changes: Vec<_> = parse_sgr(&[48]).collect();
        assert!(changes.is_empty(), "48 alone should yield nothing");
    }

    #[test]
    fn sgr_unknown_params_skipped() {
        // 6, 10, 50, 99 are not recognized SGR codes
        let changes: Vec<_> = parse_sgr(&[6, 10, 50, 99]).collect();
        assert!(changes.is_empty(), "unknown SGR params should be skipped");
    }

    #[test]
    fn sgr_unknown_interspersed_with_valid() {
        // Unknown (6), bold (1), unknown (99), italic (3)
        let changes: Vec<_> = parse_sgr(&[6, 1, 99, 3]).collect();
        assert_eq!(
            changes,
            vec![SgrChange::Bold(true), SgrChange::Italic(true)]
        );
    }

    #[test]
    fn sgr_extended_fg_followed_by_valid() {
        // 38;5;196 then bold
        let changes: Vec<_> = parse_sgr(&[38, 5, 196, 1]).collect();
        assert_eq!(changes, vec![SgrChange::Fg256(196), SgrChange::Bold(true)]);
    }

    #[test]
    fn sgr_extended_bg_followed_by_valid() {
        // bg RGB then fg default
        let changes: Vec<_> = parse_sgr(&[48, 2, 10, 20, 30, 39]).collect();
        assert_eq!(
            changes,
            vec![SgrChange::BgRgb(10, 20, 30), SgrChange::FgDefault]
        );
    }

    // ── Parser edge cases ───────────────────────────────────────────────

    #[test]
    fn parse_empty_input() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"", &mut handler);

        assert!(handler.printed.borrow().is_empty());
        assert!(handler.executed.borrow().is_empty());
        assert!(handler.csi_calls.borrow().is_empty());
        assert!(handler.osc_calls.borrow().is_empty());
        assert!(handler.esc_calls.borrow().is_empty());
    }

    #[test]
    fn parse_only_control_codes() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\n\r\t\x07\x08", &mut handler);

        assert!(handler.printed.borrow().is_empty());
        let executed: Vec<u8> = handler.executed.borrow().clone();
        assert_eq!(executed, vec![b'\n', b'\r', b'\t', 0x07, 0x08]);
    }

    #[test]
    fn parse_bell_control_code() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\x07", &mut handler);

        let executed: Vec<u8> = handler.executed.borrow().clone();
        assert_eq!(executed, vec![0x07]);
    }

    #[test]
    fn parse_backspace_control_code() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.parse(b"\x08", &mut handler);

        let executed: Vec<u8> = handler.executed.borrow().clone();
        assert_eq!(executed, vec![0x08]);
    }

    #[test]
    fn parse_osc_with_st_terminator() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // OSC 2 ; title ST (ESC \)
        parser.parse(b"\x1b]2;Window Title\x1b\\", &mut handler);

        let osc_calls = handler.osc_calls.borrow();
        assert_eq!(osc_calls.len(), 1);
        assert_eq!(osc_calls[0][0], b"2");
        assert_eq!(osc_calls[0][1], b"Window Title");
    }

    #[test]
    fn parse_multiple_parse_calls_state_persists() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // First call: text
        parser.parse(b"AB", &mut handler);
        // Second call: more text
        parser.parse(b"CD", &mut handler);

        let printed: Vec<char> = handler.printed.borrow().clone();
        assert_eq!(printed, vec!['A', 'B', 'C', 'D']);
    }

    #[test]
    fn parse_sequence_split_across_calls() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Split ESC [ 31 m across two calls
        parser.parse(b"\x1b[3", &mut handler);
        assert!(handler.csi_calls.borrow().is_empty());

        parser.parse(b"1m", &mut handler);
        assert_eq!(handler.csi_calls.borrow().len(), 1);
        assert_eq!(handler.csi_calls.borrow()[0].0, vec![31]);
        assert_eq!(handler.csi_calls.borrow()[0].2, 'm');
    }

    #[test]
    fn parser_default_impl() {
        let parser = AnsiParser::default();
        // Just verify it constructs without error
        let debug = format!("{parser:?}");
        assert!(debug.contains("AnsiParser"));
    }

    #[test]
    fn parser_debug_impl() {
        let parser = AnsiParser::new();
        let debug = format!("{parser:?}");
        assert!(debug.contains("AnsiParser"));
    }

    #[test]
    fn hook_trace_correlation_ids_are_monotonic() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        parser.register_esc_hook(|_event| HookDisposition::Continue);
        parser.parse(b"\x1b7\x1b8", &mut handler);

        let trace = parser.drain_hook_trace();
        assert!(!trace.is_empty());
        assert!(
            trace
                .windows(2)
                .all(|window| { window[0].correlation_id < window[1].correlation_id })
        );
        assert!(trace.iter().all(|event| event.ts_ms > 0));
    }

    #[test]
    fn reset_discards_partial_sequence() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Start incomplete CSI
        parser.parse(b"\x1b[", &mut handler);

        // Reset discards it
        parser.reset();

        // Plain text should work normally
        parser.parse(b"Hello", &mut handler);
        let printed: Vec<char> = handler.printed.borrow().clone();
        assert_eq!(printed, vec!['H', 'e', 'l', 'l', 'o']);
        assert!(handler.csi_calls.borrow().is_empty());
    }

    // ── SGR constant value tests ────────────────────────────────────────

    #[test]
    fn sgr_constants_are_correct() {
        assert_eq!(sgr::RESET, 0);
        assert_eq!(sgr::BOLD, 1);
        assert_eq!(sgr::DIM, 2);
        assert_eq!(sgr::ITALIC, 3);
        assert_eq!(sgr::UNDERLINE, 4);
        assert_eq!(sgr::BLINK, 5);
        assert_eq!(sgr::REVERSE, 7);
        assert_eq!(sgr::HIDDEN, 8);
        assert_eq!(sgr::STRIKETHROUGH, 9);

        assert_eq!(sgr::NORMAL_INTENSITY, 22);
        assert_eq!(sgr::NO_ITALIC, 23);
        assert_eq!(sgr::NO_UNDERLINE, 24);
        assert_eq!(sgr::NO_BLINK, 25);
        assert_eq!(sgr::NO_REVERSE, 27);
        assert_eq!(sgr::NO_HIDDEN, 28);
        assert_eq!(sgr::NO_STRIKETHROUGH, 29);
    }

    #[test]
    fn sgr_fg_color_constants() {
        assert_eq!(sgr::FG_BLACK, 30);
        assert_eq!(sgr::FG_RED, 31);
        assert_eq!(sgr::FG_GREEN, 32);
        assert_eq!(sgr::FG_YELLOW, 33);
        assert_eq!(sgr::FG_BLUE, 34);
        assert_eq!(sgr::FG_MAGENTA, 35);
        assert_eq!(sgr::FG_CYAN, 36);
        assert_eq!(sgr::FG_WHITE, 37);
        assert_eq!(sgr::FG_EXTENDED, 38);
        assert_eq!(sgr::FG_DEFAULT, 39);
    }

    #[test]
    fn sgr_bg_color_constants() {
        assert_eq!(sgr::BG_BLACK, 40);
        assert_eq!(sgr::BG_RED, 41);
        assert_eq!(sgr::BG_GREEN, 42);
        assert_eq!(sgr::BG_YELLOW, 43);
        assert_eq!(sgr::BG_BLUE, 44);
        assert_eq!(sgr::BG_MAGENTA, 45);
        assert_eq!(sgr::BG_CYAN, 46);
        assert_eq!(sgr::BG_WHITE, 47);
        assert_eq!(sgr::BG_EXTENDED, 48);
        assert_eq!(sgr::BG_DEFAULT, 49);
    }

    #[test]
    fn sgr_bright_color_constants() {
        assert_eq!(sgr::FG_BRIGHT_BLACK, 90);
        assert_eq!(sgr::FG_BRIGHT_RED, 91);
        assert_eq!(sgr::FG_BRIGHT_GREEN, 92);
        assert_eq!(sgr::FG_BRIGHT_YELLOW, 93);
        assert_eq!(sgr::FG_BRIGHT_BLUE, 94);
        assert_eq!(sgr::FG_BRIGHT_MAGENTA, 95);
        assert_eq!(sgr::FG_BRIGHT_CYAN, 96);
        assert_eq!(sgr::FG_BRIGHT_WHITE, 97);

        assert_eq!(sgr::BG_BRIGHT_BLACK, 100);
        assert_eq!(sgr::BG_BRIGHT_RED, 101);
        assert_eq!(sgr::BG_BRIGHT_GREEN, 102);
        assert_eq!(sgr::BG_BRIGHT_YELLOW, 103);
        assert_eq!(sgr::BG_BRIGHT_BLUE, 104);
        assert_eq!(sgr::BG_BRIGHT_MAGENTA, 105);
        assert_eq!(sgr::BG_BRIGHT_CYAN, 106);
        assert_eq!(sgr::BG_BRIGHT_WHITE, 107);
    }

    #[test]
    fn sgr_color_mode_constants() {
        assert_eq!(sgr::COLOR_256, 5);
        assert_eq!(sgr::COLOR_RGB, 2);
    }

    // ── DEC mode constant tests ─────────────────────────────────────────

    #[test]
    fn dec_mode_constants_are_correct() {
        assert_eq!(dec_mode::CURSOR_VISIBLE, 25);
        assert_eq!(dec_mode::ALT_SCREEN, 1049);
        assert_eq!(dec_mode::ALT_SCREEN_NO_CLEAR, 1047);
        assert_eq!(dec_mode::SAVE_CURSOR, 1048);
        assert_eq!(dec_mode::MOUSE_TRACKING, 1000);
        assert_eq!(dec_mode::MOUSE_BUTTON, 1002);
        assert_eq!(dec_mode::MOUSE_ANY, 1003);
        assert_eq!(dec_mode::MOUSE_SGR, 1006);
        assert_eq!(dec_mode::FOCUS, 1004);
        assert_eq!(dec_mode::BRACKETED_PASTE, 2004);
    }

    // ── SgrChange trait coverage ────────────────────────────────────────

    #[test]
    fn sgr_change_debug_format() {
        let change = SgrChange::Bold(true);
        let debug = format!("{change:?}");
        assert!(debug.contains("Bold"));
    }

    #[test]
    fn sgr_change_clone_eq() {
        let a = SgrChange::FgRgb(100, 150, 200);
        let b = a;
        assert_eq!(a, b);
    }

    #[test]
    fn sgr_change_ne() {
        assert_ne!(SgrChange::Bold(true), SgrChange::Bold(false));
        assert_ne!(SgrChange::FgAnsi(1), SgrChange::FgAnsi(2));
        assert_ne!(SgrChange::FgDefault, SgrChange::BgDefault);
    }

    // ── Full roundtrip: parse ANSI then interpret SGR ───────────────────

    #[test]
    fn roundtrip_parse_then_sgr() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // Bold red text with reset
        parser.parse(b"\x1b[1;31mRed\x1b[0m", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 2);

        // Interpret the first SGR
        let sgr_changes: Vec<_> = parse_sgr(&csi_calls[0].0).collect();
        assert_eq!(
            sgr_changes,
            vec![SgrChange::Bold(true), SgrChange::FgAnsi(1)]
        );

        // Interpret the reset
        let reset_changes: Vec<_> = parse_sgr(&csi_calls[1].0).collect();
        assert_eq!(reset_changes, vec![SgrChange::Reset]);
    }

    #[test]
    fn roundtrip_256_color() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ 38;5;208 m - 256-color orange foreground
        parser.parse(b"\x1b[38;5;208m", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);

        let sgr_changes: Vec<_> = parse_sgr(&csi_calls[0].0).collect();
        assert_eq!(sgr_changes, vec![SgrChange::Fg256(208)]);
    }

    #[test]
    fn roundtrip_rgb_color() {
        let mut parser = AnsiParser::new();
        let mut handler = TestHandler::default();

        // ESC [ 48;2;255;128;0 m - RGB orange background
        parser.parse(b"\x1b[48;2;255;128;0m", &mut handler);

        let csi_calls = handler.csi_calls.borrow();
        assert_eq!(csi_calls.len(), 1);

        let sgr_changes: Vec<_> = parse_sgr(&csi_calls[0].0).collect();
        assert_eq!(sgr_changes, vec![SgrChange::BgRgb(255, 128, 0)]);
    }

    #[test]
    fn sgr_all_attribute_set_then_reset() {
        // Set every attribute, then reset each one
        let changes: Vec<_> =
            parse_sgr(&[1, 2, 3, 4, 5, 7, 8, 9, 22, 23, 24, 25, 27, 28, 29]).collect();
        assert_eq!(
            changes,
            vec![
                SgrChange::Bold(true),
                SgrChange::Dim(true),
                SgrChange::Italic(true),
                SgrChange::Underline(true),
                SgrChange::Blink(true),
                SgrChange::Reverse(true),
                SgrChange::Hidden(true),
                SgrChange::Strikethrough(true),
                SgrChange::Bold(false), // 22 resets bold
                SgrChange::Italic(false),
                SgrChange::Underline(false),
                SgrChange::Blink(false),
                SgrChange::Reverse(false),
                SgrChange::Hidden(false),
                SgrChange::Strikethrough(false),
            ]
        );
    }
}