ftui-core 0.4.0

Terminal lifecycle, capabilities, and event parsing for FrankenTUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
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
#![forbid(unsafe_code)]

//! Terminal session lifecycle guard.
//!
//! This module provides RAII-based terminal lifecycle management that ensures
//! cleanup even on panic. It owns raw-mode entry/exit and tracks all terminal
//! state changes.
//!
//! # Lifecycle Guarantees
//!
//! 1. **All terminal state changes are tracked** - Each mode (raw, alt-screen,
//!    mouse, bracketed paste, focus events) has a corresponding flag.
//!
//! 2. **Drop restores previous state** - When the [`TerminalSession`] is
//!    dropped, all enabled modes are disabled in reverse order.
//!
//! 3. **Panic safety** - Because cleanup is in [`Drop`], it runs during panic
//!    unwinding (unless `panic = "abort"` is set).
//!
//! 4. **No leaked state on any exit path** - Whether by return, `?`, panic,
//!    or `process::exit()` (excluding abort), terminal state is restored.
//!
//! # Backend Decision (ADR-003)
//!
//! This module uses Crossterm as the terminal backend. Key requirements:
//! - Raw mode enter/exit must be reliable
//! - Cleanup must happen on normal exit AND panic
//! - Resize events must be delivered accurately
//!
//! See ADR-003 for the full backend decision rationale.
//!
//! # Escape Sequences Reference
//!
//! The following escape sequences are used (via Crossterm):
//!
//! | Feature | Enable | Disable |
//! |---------|--------|---------|
//! | Alternate screen | `CSI ? 1049 h` | `CSI ? 1049 l` |
//! | Mouse (SGR) | reset legacy encodings, then `CSI ? 1000;1002;1006 h` (+ split compatibility) | `CSI ? 1000;1002;1006 l` (+ split compatibility, plus legacy resets) |
//! | Bracketed paste | `CSI ? 2004 h` | `CSI ? 2004 l` |
//! | Focus events | `CSI ? 1004 h` | `CSI ? 1004 l` |
//! | Kitty keyboard | `CSI > 15 u` | `CSI < u` |
//! | Show cursor | `CSI ? 25 h` | `CSI ? 25 l` |
//! | Reset style | `CSI 0 m` | N/A |
//!
//! # Cleanup Order
//!
//! On drop, cleanup happens in reverse order of enabling:
//! 1. Reset scroll region and style (`CSI r`, `CSI 0 m`)
//! 2. Disable kitty keyboard (if enabled)
//! 3. Disable focus events (if enabled)
//! 4. Disable bracketed paste (if enabled)
//! 5. Disable mouse capture (if enabled)
//! 6. Show cursor (always)
//! 7. Leave alternate screen (if enabled)
//! 8. Exit raw mode (always)
//! 9. Flush stdout
//!
//! # Usage
//!
//! ```no_run
//! use ftui_core::terminal_session::{TerminalSession, SessionOptions};
//!
//! // Create a session with desired options
//! let session = TerminalSession::new(SessionOptions {
//!     alternate_screen: true,
//!     mouse_capture: true,
//!     ..Default::default()
//! })?;
//!
//! // Terminal is now in raw mode with alt screen and mouse
//! // ... do work ...
//!
//! // When `session` is dropped, terminal is restored
//! # Ok::<(), std::io::Error>(())
//! ```

use std::cell::Cell;
use std::env;
use std::io::{self, Write};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;

use crate::event::Event;
use crate::terminal_capabilities::TerminalCapabilities;

// Import tracing macros (no-op when tracing feature is disabled).
#[cfg(feature = "tracing")]
use crate::logging::{info_span, warn};
#[cfg(not(feature = "tracing"))]
use crate::{info_span, warn};

// ─── Metrics counters ────────────────────────────────────────────────────────

static IO_READ_DURATION_SUM_US: AtomicU64 = AtomicU64::new(0);
static IO_READ_COUNT: AtomicU64 = AtomicU64::new(0);
static IO_WRITE_DURATION_SUM_US: AtomicU64 = AtomicU64::new(0);
static IO_WRITE_COUNT: AtomicU64 = AtomicU64::new(0);
static IO_FLUSH_DURATION_SUM_US: AtomicU64 = AtomicU64::new(0);
static IO_FLUSH_COUNT: AtomicU64 = AtomicU64::new(0);
thread_local! {
    static PANIC_CLEANUP_SUPPRESS_DEPTH: Cell<u32> = const { Cell::new(0) };
}

const SIGNAL_SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
const SIGNAL_SHUTDOWN_POLL: Duration = Duration::from_millis(10);

/// Returns (sum_us, count) for read I/O operations.
pub fn terminal_io_read_stats() -> (u64, u64) {
    (
        IO_READ_DURATION_SUM_US.load(Ordering::Relaxed),
        IO_READ_COUNT.load(Ordering::Relaxed),
    )
}

/// Returns (sum_us, count) for write I/O operations.
pub fn terminal_io_write_stats() -> (u64, u64) {
    (
        IO_WRITE_DURATION_SUM_US.load(Ordering::Relaxed),
        IO_WRITE_COUNT.load(Ordering::Relaxed),
    )
}

/// Returns (sum_us, count) for flush I/O operations.
pub fn terminal_io_flush_stats() -> (u64, u64) {
    (
        IO_FLUSH_DURATION_SUM_US.load(Ordering::Relaxed),
        IO_FLUSH_COUNT.load(Ordering::Relaxed),
    )
}

fn wait_for_shutdown_ack() -> bool {
    let deadline = std::time::Instant::now()
        .checked_add(SIGNAL_SHUTDOWN_GRACE)
        .unwrap_or_else(std::time::Instant::now);

    loop {
        if crate::shutdown_signal::pending_termination_signal().is_none() {
            return true;
        }
        if std::time::Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(SIGNAL_SHUTDOWN_POLL);
    }
}

/// Run a closure while suppressing best-effort terminal cleanup in the panic hook.
///
/// Use this around intentional `catch_unwind` boundaries. Panic hooks still run,
/// but terminal cleanup is skipped for panics that are expected to be recovered.
///
/// In `panic = "abort"` builds, panics cannot be recovered by `catch_unwind`,
/// so suppression is disabled and this executes `f` directly.
pub fn with_panic_cleanup_suppressed<F, R>(f: F) -> R
where
    F: FnOnce() -> R,
{
    #[cfg(panic = "abort")]
    {
        return f();
    }

    #[cfg(not(panic = "abort"))]
    {
        struct SuppressGuard;
        impl Drop for SuppressGuard {
            fn drop(&mut self) {
                PANIC_CLEANUP_SUPPRESS_DEPTH.with(|depth| {
                    depth.set(depth.get().saturating_sub(1));
                });
            }
        }

        PANIC_CLEANUP_SUPPRESS_DEPTH.with(|depth| {
            depth.set(depth.get().saturating_add(1));
        });
        let _guard = SuppressGuard;
        f()
    }
}

fn panic_cleanup_suppressed() -> bool {
    PANIC_CLEANUP_SUPPRESS_DEPTH.with(|depth| depth.get() > 0)
}

/// Convert `web_time::Duration` to `std::time::Duration`, clamping to avoid
/// overflow on the `as_micros() -> u64` conversion.
fn to_std_duration(d: web_time::Duration) -> Duration {
    Duration::from_micros(d.as_micros().min(u64::MAX as u128) as u64)
}

const SIZE_RETRY_DELAY: Duration = Duration::from_millis(10);

#[inline]
fn size_retry_delay(cx: &crate::cx::Cx) -> Option<Duration> {
    if cx.is_done() {
        return None;
    }

    match cx.remaining() {
        Some(remaining) if to_std_duration(remaining) <= SIZE_RETRY_DELAY => None,
        _ => Some(SIZE_RETRY_DELAY),
    }
}

/// Compute remaining microseconds for Cx, or `u64::MAX` if no deadline.
#[cfg_attr(not(feature = "tracing"), allow(dead_code))]
fn cx_deadline_remaining_us(cx: &crate::cx::Cx) -> u64 {
    cx.remaining()
        .map(|r| r.as_micros().min(u64::MAX as u128) as u64)
        .unwrap_or(u64::MAX)
}

const KITTY_KEYBOARD_ENABLE: &[u8] = b"\x1b[>15u";
const KITTY_KEYBOARD_DISABLE: &[u8] = b"\x1b[<u";
const RESET_SCROLL_REGION: &[u8] = b"\x1b[r";
const RESET_STYLE: &[u8] = b"\x1b[0m";
const SYNC_END: &[u8] = b"\x1b[?2026l";
// Mouse mode hygiene:
// 1) Reset legacy and alternate encodings.
// 2) Enable canonical SGR mouse modes (1000 + 1002 + 1006).
// 3) Clear 1016 before enabling SGR to avoid terminals that treat 1016l
//    as a hard fallback to X10 when sent after 1006h.
// 4) Avoid DECSET 1003 (any-event mouse) because high-rate move streams can
//    destabilize mux pipelines.
// NOTE: Set SGR format (1006) before enabling mouse event modes for better
// compatibility with terminals that key off "last mode set" ordering.
const MOUSE_ENABLE_SEQ: &[u8] = b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006;1000;1002h\x1b[?1006h\x1b[?1000h\x1b[?1002h";
// Conservative mouse enable sequence for mux sessions and runtime toggles.
// Keep to split DECSET/DECRST forms (better passthrough behavior), but still
// reset alternate encodings so the inner terminal doesn't get "stuck" in a
// format our parser won't decode.
const MOUSE_ENABLE_MUX_SAFE_SEQ: &[u8] =
    b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006h\x1b[?1000h\x1b[?1002h";
const MOUSE_DISABLE_SEQ: &[u8] = b"\x1b[?1000;1002;1006l\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l";
// Conservative mouse disable sequence for mux/panic cleanup paths. Keeps
// parser surface minimal while still restoring canonical capture modes and
// clearing any leaked SGR-pixel mode.
const MOUSE_DISABLE_MUX_SAFE_SEQ: &[u8] =
    b"\x1b[?1016l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1001l\x1b[?1005l\x1b[?1015l";

static TERMINAL_SESSION_ACTIVE: AtomicBool = AtomicBool::new(false);

#[derive(Debug)]
struct SessionLock;

impl SessionLock {
    fn acquire() -> io::Result<Self> {
        if TERMINAL_SESSION_ACTIVE
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_err()
        {
            return Err(io::Error::other("TerminalSession already active"));
        }
        Ok(Self)
    }
}

impl Drop for SessionLock {
    fn drop(&mut self) {
        TERMINAL_SESSION_ACTIVE.store(false, Ordering::SeqCst);
    }
}

#[cfg(unix)]
use signal_hook::consts::signal::{SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGWINCH};
#[cfg(unix)]
use signal_hook::iterator::Signals;

/// Terminal session configuration options.
///
/// These options control which terminal modes are enabled when a session
/// starts. All options default to `false` for maximum portability.
///
/// # Example
///
/// ```
/// use ftui_core::terminal_session::SessionOptions;
///
/// // Full-featured TUI
/// let opts = SessionOptions {
///     alternate_screen: true,
///     mouse_capture: true,
///     bracketed_paste: true,
///     focus_events: true,
///     ..Default::default()
/// };
///
/// // Minimal inline mode
/// let inline_opts = SessionOptions::default();
/// ```
#[derive(Debug, Clone)]
pub struct SessionOptions {
    /// Enable alternate screen buffer (`CSI ? 1049 h`).
    ///
    /// When enabled, the terminal switches to a separate screen buffer,
    /// preserving the original scrollback. On exit, the original screen
    /// is restored.
    ///
    /// Use this for full-screen applications. For inline mode (preserving
    /// scrollback), leave this `false`.
    pub alternate_screen: bool,

    /// Enable mouse capture with SGR encoding, resetting legacy/alternate
    /// mouse encodings first and then applying `CSI ? 1000;1002;1006 h`
    /// (plus split-form compatibility).
    ///
    /// Enables:
    /// - Normal mouse tracking (1000)
    /// - Button event tracking (1002)
    /// - SGR extended coordinates (1006) - supports coordinates > 223
    pub mouse_capture: bool,

    /// Enable bracketed paste mode (`CSI ? 2004 h`).
    ///
    /// When enabled, pasted text is wrapped in escape sequences:
    /// - Start: `ESC [ 200 ~`
    /// - End: `ESC [ 201 ~`
    ///
    /// This allows distinguishing pasted text from typed text.
    pub bracketed_paste: bool,

    /// Enable focus change events (`CSI ? 1004 h`).
    ///
    /// When enabled, the terminal sends events when focus is gained or lost:
    /// - Focus in: `ESC [ I`
    /// - Focus out: `ESC [ O`
    pub focus_events: bool,

    /// Enable Kitty keyboard protocol (pushes flags with `CSI > 15 u`).
    ///
    /// Uses the kitty protocol to report repeat/release events and disambiguate
    /// keys. This is optional and only supported by select terminals.
    pub kitty_keyboard: bool,

    /// Install a signal handler to restore terminal state on SIGINT/SIGTERM/SIGHUP.
    ///
    /// Defaults to `true` to ensure the terminal is not left in a broken state
    /// when the application is terminated. Disable this if you are managing
    /// signals yourself or running in a context where signal handling is undesirable.
    pub intercept_signals: bool,
}

impl Default for SessionOptions {
    fn default() -> Self {
        Self {
            alternate_screen: false,
            mouse_capture: false,
            bracketed_paste: false,
            focus_events: false,
            kitty_keyboard: false,
            intercept_signals: true,
        }
    }
}

#[inline]
fn sanitize_session_options(
    mut requested: SessionOptions,
    capabilities: &TerminalCapabilities,
) -> SessionOptions {
    let focus_events_supported = capabilities.focus_events && !capabilities.in_any_mux();
    let kitty_keyboard_supported = capabilities.kitty_keyboard && !capabilities.in_any_mux();

    requested.mouse_capture = requested.mouse_capture && capabilities.mouse_sgr;
    requested.bracketed_paste = requested.bracketed_paste && capabilities.bracketed_paste;
    requested.focus_events = requested.focus_events && focus_events_supported;
    requested.kitty_keyboard = requested.kitty_keyboard && kitty_keyboard_supported;
    requested
}

/// A terminal session that manages raw mode and cleanup.
///
/// This struct owns the terminal configuration and ensures cleanup on drop.
/// It tracks all enabled modes and disables them in reverse order when dropped.
///
/// # Contract
///
/// - **Exclusive ownership**: Only one `TerminalSession` should exist at a time.
///   Creating multiple sessions will cause undefined terminal behavior.
///
/// - **Raw mode entry**: Creating a session automatically enters raw mode.
///   This disables line buffering and echo.
///
/// - **Cleanup guarantee**: When dropped (normally or via panic), all enabled
///   modes are disabled and the terminal is restored to its previous state.
///
/// # State Tracking
///
/// Each optional mode has a corresponding `_enabled` flag. These flags are
/// set when a mode is successfully enabled and cleared during cleanup.
/// This ensures we only disable modes that were actually enabled.
///
/// # Example
///
/// ```no_run
/// use ftui_core::terminal_session::{TerminalSession, SessionOptions};
///
/// fn run_app() -> std::io::Result<()> {
///     let session = TerminalSession::new(SessionOptions {
///         alternate_screen: true,
///         mouse_capture: true,
///         ..Default::default()
///     })?;
///
///     // Application loop
///     loop {
///         if session.poll_event(std::time::Duration::from_millis(100))? {
///             if let Some(event) = session.read_event()? {
///                 // Handle event...
///             }
///         }
///     }
///     // Session cleaned up when dropped
/// }
/// ```
#[derive(Debug)]
pub struct TerminalSession {
    /// Process-wide exclusivity guard for the one-session-at-a-time contract.
    ///
    /// Only sessions created via `TerminalSession::new` acquire this lock.
    /// `new_for_tests` intentionally skips it to allow parallel headless tests.
    session_lock: Option<SessionLock>,
    /// Whether this session must avoid mutating real terminal state.
    ///
    /// Test-helper sessions use this to skip global panic-hook installation and
    /// teardown writes on drop.
    headless: bool,
    options: SessionOptions,
    /// Track what was enabled so we can disable on drop.
    alternate_screen_enabled: bool,
    mouse_enabled: bool,
    bracketed_paste_enabled: bool,
    focus_events_enabled: bool,
    kitty_keyboard_enabled: bool,
    #[cfg(unix)]
    signal_guard: Option<SignalGuard>,
}

impl TerminalSession {
    #[inline]
    fn mouse_enable_sequence_for_caps(caps: &TerminalCapabilities) -> &'static [u8] {
        if caps.in_any_mux() {
            MOUSE_ENABLE_MUX_SAFE_SEQ
        } else {
            MOUSE_ENABLE_SEQ
        }
    }

    #[inline]
    fn mouse_disable_sequence_for_caps(caps: &TerminalCapabilities) -> &'static [u8] {
        if caps.in_any_mux() {
            MOUSE_DISABLE_MUX_SAFE_SEQ
        } else {
            MOUSE_DISABLE_SEQ
        }
    }

    /// Enter raw mode and optionally enable additional features.
    ///
    /// # Errors
    ///
    /// Returns an error if raw mode cannot be enabled.
    pub fn new(options: SessionOptions) -> io::Result<Self> {
        install_panic_hook();
        let capabilities = TerminalCapabilities::with_overrides();
        let options = sanitize_session_options(options, &capabilities);

        let session_lock = SessionLock::acquire()?;

        // Create signal guard before raw mode so that a failure here
        // does not leave the terminal in raw mode (the struct would never
        // be fully constructed, so Drop would not run).
        #[cfg(unix)]
        let signal_guard = if options.intercept_signals {
            Some(SignalGuard::new()?)
        } else {
            None
        };

        // Enter raw mode
        crossterm::terminal::enable_raw_mode()?;
        #[cfg(feature = "tracing")]
        tracing::info!("terminal raw mode enabled");

        let mut session = Self {
            session_lock: Some(session_lock),
            headless: false,
            options: options.clone(),
            alternate_screen_enabled: false,
            mouse_enabled: false,
            bracketed_paste_enabled: false,
            focus_events_enabled: false,
            kitty_keyboard_enabled: false,
            #[cfg(unix)]
            signal_guard,
        };

        // Enable optional features
        let mut stdout = io::stdout();

        if options.alternate_screen {
            // Mark enabled before writing in case of partial write failures;
            // drop cleanup must unwind any state that may already be active.
            session.alternate_screen_enabled = true;
            // Enter alternate screen and explicitly clear it.
            // Some terminals (including WezTerm) may show stale content in the
            // alt-screen buffer without an explicit clear. We also position the
            // cursor at the top-left to ensure a known initial state.
            crossterm::execute!(
                stdout,
                crossterm::terminal::EnterAlternateScreen,
                crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
                crossterm::cursor::MoveTo(0, 0)
            )?;
            #[cfg(feature = "tracing")]
            tracing::info!("alternate screen enabled (with clear)");
        }

        if options.mouse_capture {
            session.mouse_enabled = true;
            let enable_seq = Self::mouse_enable_sequence_for_caps(&capabilities);
            stdout.write_all(enable_seq)?;
            stdout.flush()?;
            #[cfg(feature = "tracing")]
            tracing::info!("mouse capture enabled");
        }

        if options.bracketed_paste {
            session.bracketed_paste_enabled = true;
            crossterm::execute!(stdout, crossterm::event::EnableBracketedPaste)?;
            #[cfg(feature = "tracing")]
            tracing::info!("bracketed paste enabled");
        }

        if options.focus_events {
            session.focus_events_enabled = true;
            crossterm::execute!(stdout, crossterm::event::EnableFocusChange)?;
            #[cfg(feature = "tracing")]
            tracing::info!("focus events enabled");
        }

        if options.kitty_keyboard {
            session.kitty_keyboard_enabled = true;
            Self::enable_kitty_keyboard(&mut stdout)?;
            #[cfg(feature = "tracing")]
            tracing::info!("kitty keyboard enabled");
        }

        Ok(session)
    }

    /// Create a session for tests without entering raw mode or installing
    /// global terminal cleanup hooks.
    ///
    /// This skips raw mode and feature toggles, allowing headless tests
    /// to construct `TerminalSession` safely.
    #[cfg(feature = "test-helpers")]
    pub fn new_for_tests(options: SessionOptions) -> io::Result<Self> {
        #[cfg(unix)]
        let signal_guard = None;

        Ok(Self {
            session_lock: None,
            headless: true,
            options,
            alternate_screen_enabled: false,
            mouse_enabled: false,
            bracketed_paste_enabled: false,
            focus_events_enabled: false,
            kitty_keyboard_enabled: false,
            #[cfg(unix)]
            signal_guard,
        })
    }

    /// Create a minimal session (raw mode only).
    pub fn minimal() -> io::Result<Self> {
        Self::new(SessionOptions::default())
    }

    /// Get the current terminal size (columns, rows).
    pub fn size(&self) -> io::Result<(u16, u16)> {
        let (w, h) = crossterm::terminal::size()?;
        if w > 1 && h > 1 {
            return Ok((w, h));
        }

        // Some terminals briefly report 1x1 on startup; fall back to env vars when available.
        if let Some((env_w, env_h)) = size_from_env() {
            return Ok((env_w, env_h));
        }

        // Re-probe once after a short delay to catch terminals that report size late.
        std::thread::sleep(SIZE_RETRY_DELAY);
        let (w2, h2) = crossterm::terminal::size()?;
        if w2 > 1 && h2 > 1 {
            return Ok((w2, h2));
        }

        // Ensure minimum viable size to prevent downstream panics in buffer allocation
        // and layout calculations. 2x2 is the absolute minimum for a functional TUI.
        let final_w = w2.max(2);
        let final_h = h2.max(2);
        Ok((final_w, final_h))
    }

    /// Poll for an event with a timeout.
    ///
    /// Returns `Ok(true)` if an event is available, `Ok(false)` if timeout.
    pub fn poll_event(&self, timeout: std::time::Duration) -> io::Result<bool> {
        crossterm::event::poll(timeout)
    }

    /// Poll for an event, respecting the [`Cx`] deadline and cancellation.
    ///
    /// The effective timeout is `min(timeout, cx.remaining())`. Returns
    /// `Ok(false)` immediately if the context is cancelled or expired.
    ///
    /// Emits a `terminal.io` tracing span with `op_type="poll"`.
    pub fn poll_event_cx(
        &self,
        timeout: std::time::Duration,
        cx: &crate::cx::Cx,
    ) -> io::Result<bool> {
        let _span = info_span!(
            "terminal.io",
            op_type = "poll",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            return Ok(false);
        }
        let effective = match cx.remaining() {
            Some(rem) => timeout.min(to_std_duration(rem)),
            None => timeout,
        };
        let start = web_time::Instant::now();
        let result = crossterm::event::poll(effective);
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_READ_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_READ_COUNT.fetch_add(1, Ordering::Relaxed);
        if cx.is_done() {
            warn!("terminal.io poll completed after Cx deadline/cancellation");
        }
        result
    }

    /// Read the next event (blocking until available).
    ///
    /// Returns `Ok(None)` if the event cannot be represented by the
    /// ftui canonical event types (e.g. unsupported key codes).
    pub fn read_event(&self) -> io::Result<Option<Event>> {
        let event = crossterm::event::read()?;
        Ok(Event::from_crossterm(event))
    }

    /// Read the next event, respecting the [`Cx`] deadline and cancellation.
    ///
    /// Polls with the context's remaining deadline, then reads if available.
    /// Returns `Ok(None)` if the context is cancelled, expired, or the poll
    /// times out before an event arrives.
    ///
    /// Emits a `terminal.io` tracing span with `op_type="read"`.
    pub fn read_event_cx(&self, cx: &crate::cx::Cx) -> io::Result<Option<Event>> {
        let _span = info_span!(
            "terminal.io",
            op_type = "read",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            return Ok(None);
        }
        let remaining = cx.remaining().unwrap_or(web_time::Duration::from_secs(60));
        let timeout = to_std_duration(remaining);
        let start = web_time::Instant::now();
        let result = if crossterm::event::poll(timeout)? {
            let event = crossterm::event::read()?;
            Ok(Event::from_crossterm(event))
        } else {
            Ok(None)
        };
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_READ_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_READ_COUNT.fetch_add(1, Ordering::Relaxed);
        if cx.is_done() {
            warn!("terminal.io read completed after Cx deadline/cancellation");
        }
        result
    }

    /// Show the cursor.
    pub fn show_cursor(&self) -> io::Result<()> {
        crossterm::execute!(io::stdout(), crossterm::cursor::Show)
    }

    /// Show the cursor, respecting the [`Cx`] deadline and cancellation.
    ///
    /// Returns `Ok(())` without writing if the context is already done.
    pub fn show_cursor_cx(&self, cx: &crate::cx::Cx) -> io::Result<()> {
        let _span = info_span!(
            "terminal.io",
            op_type = "write",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            return Ok(());
        }
        let start = web_time::Instant::now();
        let result = crossterm::execute!(io::stdout(), crossterm::cursor::Show);
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_WRITE_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_WRITE_COUNT.fetch_add(1, Ordering::Relaxed);
        if cx.is_done() {
            warn!("terminal.io show_cursor completed after Cx deadline/cancellation");
        }
        result
    }

    /// Hide the cursor.
    pub fn hide_cursor(&self) -> io::Result<()> {
        crossterm::execute!(io::stdout(), crossterm::cursor::Hide)
    }

    /// Hide the cursor, respecting the [`Cx`] deadline and cancellation.
    ///
    /// Returns `Ok(())` without writing if the context is already done.
    pub fn hide_cursor_cx(&self, cx: &crate::cx::Cx) -> io::Result<()> {
        let _span = info_span!(
            "terminal.io",
            op_type = "write",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            return Ok(());
        }
        let start = web_time::Instant::now();
        let result = crossterm::execute!(io::stdout(), crossterm::cursor::Hide);
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_WRITE_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_WRITE_COUNT.fetch_add(1, Ordering::Relaxed);
        if cx.is_done() {
            warn!("terminal.io hide_cursor completed after Cx deadline/cancellation");
        }
        result
    }

    /// Return whether mouse capture is currently enabled for this session.
    ///
    /// Mouse capture enables terminal mouse reporting (SGR mode) so the runtime
    /// can receive click/scroll/drag events.
    #[must_use]
    pub fn mouse_capture_enabled(&self) -> bool {
        self.mouse_enabled
    }

    /// Enable or disable terminal mouse capture (SGR mouse reporting).
    ///
    /// This is idempotent: enabling when already enabled (or disabling when
    /// already disabled) is a no-op.
    ///
    /// Note: In many terminals, enabling mouse capture steals the scroll wheel
    /// from the terminal's native scrollback. In inline mode, prefer leaving
    /// this off unless the user explicitly opts in.
    pub fn set_mouse_capture(&mut self, enabled: bool) -> io::Result<()> {
        let caps = TerminalCapabilities::with_overrides();
        let mouse_supported = caps.mouse_sgr;
        let enabled = enabled && mouse_supported;

        if enabled == self.mouse_enabled {
            self.options.mouse_capture = enabled;
            return Ok(());
        }

        let mut stdout = io::stdout();
        let write_result = if enabled {
            let enable_seq = Self::mouse_enable_sequence_for_caps(&caps);
            stdout.write_all(enable_seq).and_then(|_| stdout.flush())
        } else {
            let disable_seq = Self::mouse_disable_sequence_for_caps(&caps);
            stdout.write_all(disable_seq).and_then(|_| stdout.flush())
        };

        if let Err(err) = write_result {
            // A failed write may have partially toggled mouse reporting.
            // Keep a conservative enabled state so cleanup always emits disable.
            self.mouse_enabled = self.mouse_enabled || enabled;
            self.options.mouse_capture = self.mouse_enabled;
            return Err(err);
        }

        if enabled {
            self.mouse_enabled = true;
            self.options.mouse_capture = true;
            #[cfg(feature = "tracing")]
            tracing::info!("mouse capture enabled (runtime toggle)");
        } else {
            self.mouse_enabled = false;
            self.options.mouse_capture = false;
            #[cfg(feature = "tracing")]
            tracing::info!("mouse capture disabled (runtime toggle)");
        }

        Ok(())
    }

    /// Enable or disable terminal mouse capture, respecting the [`Cx`] deadline.
    ///
    /// Returns `Ok(())` without writing if the context is already done.
    pub fn set_mouse_capture_cx(&mut self, enabled: bool, cx: &crate::cx::Cx) -> io::Result<()> {
        let _span = info_span!(
            "terminal.io",
            op_type = "write",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            return Ok(());
        }
        let caps = TerminalCapabilities::with_overrides();
        let mouse_supported = caps.mouse_sgr;
        let enabled = enabled && mouse_supported;

        if enabled == self.mouse_enabled {
            self.options.mouse_capture = enabled;
            return Ok(());
        }
        let start = web_time::Instant::now();
        let mut stdout = io::stdout();
        let result = if enabled {
            let enable_seq = Self::mouse_enable_sequence_for_caps(&caps);
            let r = stdout.write_all(enable_seq).and_then(|_| stdout.flush());
            if r.is_ok() {
                self.mouse_enabled = true;
                self.options.mouse_capture = true;
            } else {
                // Conservative fallback: if the write partially succeeded, keep
                // mouse marked enabled so teardown still emits disable.
                self.mouse_enabled = self.mouse_enabled || enabled;
                self.options.mouse_capture = self.mouse_enabled;
            }
            r
        } else {
            let disable_seq = Self::mouse_disable_sequence_for_caps(&caps);
            let r = stdout.write_all(disable_seq).and_then(|_| stdout.flush());
            if r.is_ok() {
                self.mouse_enabled = false;
                self.options.mouse_capture = false;
            } else {
                // Conservative fallback for partial disable writes.
                self.mouse_enabled = true;
                self.options.mouse_capture = true;
            }
            r
        };
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_WRITE_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_WRITE_COUNT.fetch_add(1, Ordering::Relaxed);
        if cx.is_done() {
            warn!("terminal.io set_mouse_capture completed after Cx deadline/cancellation");
        }
        result
    }

    /// Query terminal size, respecting the [`Cx`] deadline and cancellation.
    ///
    /// Skips the retry-with-delay fallback if the context is done.
    pub fn size_cx(&self, cx: &crate::cx::Cx) -> io::Result<(u16, u16)> {
        let _span = info_span!(
            "terminal.io",
            op_type = "read",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            // Return env fallback or minimum viable size.
            if let Some(env_size) = size_from_env() {
                return Ok(env_size);
            }
            return Ok((2, 2));
        }
        let start = web_time::Instant::now();
        let (w, h) = crossterm::terminal::size()?;
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_READ_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_READ_COUNT.fetch_add(1, Ordering::Relaxed);
        if w > 1 && h > 1 {
            return Ok((w, h));
        }
        if let Some((env_w, env_h)) = size_from_env() {
            return Ok((env_w, env_h));
        }
        // Skip the startup retry when the context no longer has enough budget
        // to pay for the delay and follow-up probe.
        let Some(retry_delay) = size_retry_delay(cx) else {
            return Ok((w.max(2), h.max(2)));
        };
        std::thread::sleep(retry_delay);
        let (w2, h2) = crossterm::terminal::size()?;
        if w2 > 1 && h2 > 1 {
            return Ok((w2, h2));
        }
        Ok((w2.max(2), h2.max(2)))
    }

    /// Flush stdout, respecting the [`Cx`] deadline and cancellation.
    ///
    /// Returns `Ok(())` without flushing if the context is already done.
    pub fn flush_cx(&self, cx: &crate::cx::Cx) -> io::Result<()> {
        let _span = info_span!(
            "terminal.io",
            op_type = "flush",
            cx_deadline_remaining_us = cx_deadline_remaining_us(cx),
            cx_cancelled = cx.is_cancelled()
        );
        let _guard = _span.enter();
        if cx.is_done() {
            return Ok(());
        }
        let start = web_time::Instant::now();
        let result = io::stdout().flush();
        let elapsed_us = start.elapsed().as_micros().min(u64::MAX as u128) as u64;
        IO_FLUSH_DURATION_SUM_US.fetch_add(elapsed_us, Ordering::Relaxed);
        IO_FLUSH_COUNT.fetch_add(1, Ordering::Relaxed);
        if cx.is_done() {
            warn!("terminal.io flush completed after Cx deadline/cancellation");
        }
        result
    }

    /// Get the session options.
    pub fn options(&self) -> &SessionOptions {
        &self.options
    }

    /// Cleanup helper (shared between drop and explicit cleanup).
    fn cleanup(&mut self) {
        #[cfg(unix)]
        let _ = self.signal_guard.take();

        if self.headless {
            self.alternate_screen_enabled = false;
            self.mouse_enabled = false;
            self.bracketed_paste_enabled = false;
            self.focus_events_enabled = false;
            self.kitty_keyboard_enabled = false;
            let _ = self.session_lock.take();
            return;
        }

        let mut stdout = io::stdout();
        let caps = TerminalCapabilities::with_overrides();

        // Reset scroll region (critical for inline mode recovery)
        let _ = stdout.write_all(RESET_SCROLL_REGION);
        // Reset style so shell prompt does not inherit UI SGR state.
        let _ = stdout.write_all(RESET_STYLE);
        // Ensure synchronized output is disabled (prevent frozen terminal on panic)
        let _ = stdout.write_all(SYNC_END);

        // Disable features in reverse order of enabling
        if self.kitty_keyboard_enabled {
            let _ = Self::disable_kitty_keyboard(&mut stdout);
            self.kitty_keyboard_enabled = false;
            #[cfg(feature = "tracing")]
            tracing::info!("kitty keyboard disabled");
        }

        if self.focus_events_enabled {
            let _ = crossterm::execute!(stdout, crossterm::event::DisableFocusChange);
            self.focus_events_enabled = false;
            #[cfg(feature = "tracing")]
            tracing::info!("focus events disabled");
        }

        if self.bracketed_paste_enabled {
            let _ = crossterm::execute!(stdout, crossterm::event::DisableBracketedPaste);
            self.bracketed_paste_enabled = false;
            #[cfg(feature = "tracing")]
            tracing::info!("bracketed paste disabled");
        }

        if self.mouse_enabled {
            let _ = stdout.write_all(Self::mouse_disable_sequence_for_caps(&caps));
            self.mouse_enabled = false;
            #[cfg(feature = "tracing")]
            tracing::info!("mouse capture disabled");
        }

        // Always show cursor before leaving
        let _ = crossterm::execute!(stdout, crossterm::cursor::Show);

        if self.alternate_screen_enabled {
            let _ = crossterm::execute!(stdout, crossterm::terminal::LeaveAlternateScreen);
            self.alternate_screen_enabled = false;
            #[cfg(feature = "tracing")]
            tracing::info!("alternate screen disabled");
        }

        // Exit raw mode last
        let _ = crossterm::terminal::disable_raw_mode();
        #[cfg(feature = "tracing")]
        tracing::info!("terminal raw mode disabled");

        // Flush to ensure cleanup bytes are sent
        let _ = stdout.flush();

        // Release process-wide exclusivity only after terminal state is restored.
        let _ = self.session_lock.take();
    }

    fn enable_kitty_keyboard(writer: &mut impl Write) -> io::Result<()> {
        writer.write_all(KITTY_KEYBOARD_ENABLE)?;
        writer.flush()
    }

    fn disable_kitty_keyboard(writer: &mut impl Write) -> io::Result<()> {
        writer.write_all(KITTY_KEYBOARD_DISABLE)?;
        writer.flush()
    }
}

impl Drop for TerminalSession {
    fn drop(&mut self) {
        self.cleanup();
    }
}

fn size_from_env() -> Option<(u16, u16)> {
    let cols = env::var("COLUMNS").ok()?.parse::<u16>().ok()?;
    let rows = env::var("LINES").ok()?.parse::<u16>().ok()?;
    if cols > 1 && rows > 1 {
        Some((cols, rows))
    } else {
        None
    }
}

fn install_panic_hook() {
    static HOOK: OnceLock<()> = OnceLock::new();
    HOOK.get_or_init(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            if !panic_cleanup_suppressed() {
                best_effort_cleanup();
            }
            previous(info);
        }));
    });
}

/// Best-effort cleanup for termination paths that skip `Drop`.
///
/// Call this before `std::process::exit` to restore terminal state when
/// unwinding won't run destructors.
pub fn best_effort_cleanup_for_exit() {
    best_effort_cleanup();
}

fn best_effort_cleanup() {
    let mut stdout = io::stdout();
    let caps = TerminalCapabilities::with_overrides();

    let _ = stdout.write_all(RESET_SCROLL_REGION);
    let _ = stdout.write_all(RESET_STYLE);
    // Ensure synchronized output is disabled (prevent frozen terminal on panic)
    let _ = stdout.write_all(SYNC_END);

    // Keep panic/signal cleanup conservative: only emit mux-sensitive mode
    // disables when policy says they could have been enabled.
    if caps.kitty_keyboard && !caps.in_any_mux() {
        let _ = TerminalSession::disable_kitty_keyboard(&mut stdout);
    }
    if caps.focus_events && !caps.in_any_mux() {
        let _ = crossterm::execute!(stdout, crossterm::event::DisableFocusChange);
    }
    let _ = crossterm::execute!(stdout, crossterm::event::DisableBracketedPaste);
    let _ = stdout.write_all(TerminalSession::mouse_disable_sequence_for_caps(&caps));
    let _ = crossterm::execute!(stdout, crossterm::cursor::Show);
    let _ = crossterm::execute!(stdout, crossterm::terminal::LeaveAlternateScreen);
    let _ = crossterm::terminal::disable_raw_mode();
    let _ = stdout.flush();
}

#[cfg(unix)]
#[derive(Debug)]
struct SignalGuard {
    handle: signal_hook::iterator::Handle,
    thread: Option<std::thread::JoinHandle<()>>,
}

#[cfg(unix)]
impl SignalGuard {
    fn new() -> io::Result<Self> {
        let mut signals =
            Signals::new([SIGINT, SIGTERM, SIGHUP, SIGQUIT, SIGWINCH]).map_err(io::Error::other)?;
        let handle = signals.handle();
        let thread = std::thread::spawn(move || {
            for signal in signals.forever() {
                match signal {
                    SIGWINCH => {
                        #[cfg(feature = "tracing")]
                        tracing::debug!("SIGWINCH received");
                    }
                    SIGINT | SIGTERM | SIGHUP | SIGQUIT => {
                        #[cfg(feature = "tracing")]
                        tracing::warn!("termination signal received, cleaning up");
                        crate::shutdown_signal::record_pending_termination_signal(signal);
                        best_effort_cleanup();
                        if !wait_for_shutdown_ack() {
                            std::process::exit(128 + signal);
                        }
                    }
                    _ => {}
                }
            }
        });
        Ok(Self {
            handle,
            thread: Some(thread),
        })
    }
}

#[cfg(unix)]
impl Drop for SignalGuard {
    fn drop(&mut self) {
        self.handle.close();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// Spike validation notes (for ADR-003).
///
/// ## Crossterm Evaluation Results
///
/// ### Functionality (all verified)
/// - ✅ raw mode: `enable_raw_mode()` / `disable_raw_mode()`
/// - ✅ alternate screen: `EnterAlternateScreen` / `LeaveAlternateScreen`
/// - ✅ cursor show/hide: `Show` / `Hide`
/// - ✅ mouse mode (SGR): `EnableMouseCapture` / `DisableMouseCapture`
/// - ✅ bracketed paste: `EnableBracketedPaste` / `DisableBracketedPaste`
/// - ✅ focus events: `EnableFocusChange` / `DisableFocusChange`
/// - ✅ resize events: `Event::Resize(cols, rows)`
///
/// ### Robustness
/// - ✅ bounded-time reads via `poll()` with timeout
/// - ✅ handles partial sequences (internal buffer management)
/// - ⚠️ adversarial input: not fuzz-tested in this spike
///
/// ### Cleanup Discipline
/// - ✅ Drop impl guarantees cleanup on normal exit
/// - ✅ Drop impl guarantees cleanup on panic (via unwinding)
/// - ✅ cursor shown before exit
/// - ✅ raw mode disabled last
///
/// ### Platform Coverage
/// - ✅ Linux: fully supported
/// - ✅ macOS: fully supported
/// - ⚠️ Windows: supported with some feature limitations (see ADR-004)
///
/// ## Decision
/// **Crossterm is approved as the v1 terminal backend.**
///
/// Rationale: It provides all required functionality, handles cleanup via
/// standard Rust drop semantics, and has broad platform support.
///
/// Limitations documented in ADR-004 (Windows scope).
#[doc(hidden)]
pub const _SPIKE_NOTES: () = ();

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use portable_pty::{CommandBuilder, PtySize};
    #[cfg(unix)]
    use std::io::{self, Read, Write};
    #[cfg(unix)]
    use std::sync::mpsc;
    #[cfg(unix)]
    use std::thread;
    #[cfg(unix)]
    use std::time::{Duration, Instant};

    #[test]
    fn session_options_default_is_minimal() {
        let opts = SessionOptions::default();
        assert!(!opts.alternate_screen);
        assert!(!opts.mouse_capture);
        assert!(!opts.bracketed_paste);
        assert!(!opts.focus_events);
        assert!(!opts.kitty_keyboard);
    }

    #[test]
    fn session_options_clone() {
        let opts = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: false,
            focus_events: true,
            kitty_keyboard: false,
            intercept_signals: true,
        };
        let cloned = opts.clone();
        assert_eq!(cloned.alternate_screen, opts.alternate_screen);
        assert_eq!(cloned.mouse_capture, opts.mouse_capture);
        assert_eq!(cloned.bracketed_paste, opts.bracketed_paste);
        assert_eq!(cloned.focus_events, opts.focus_events);
        assert_eq!(cloned.kitty_keyboard, opts.kitty_keyboard);
    }

    #[test]
    fn session_options_debug() {
        let opts = SessionOptions::default();
        let debug = format!("{:?}", opts);
        assert!(debug.contains("SessionOptions"));
        assert!(debug.contains("alternate_screen"));
    }

    #[test]
    fn kitty_keyboard_escape_sequences() {
        // Verify the escape sequences are correct
        assert_eq!(KITTY_KEYBOARD_ENABLE, b"\x1b[>15u");
        assert_eq!(KITTY_KEYBOARD_DISABLE, b"\x1b[<u");
    }

    #[test]
    fn mouse_enable_excludes_any_event_mode() {
        assert!(
            !MOUSE_ENABLE_SEQ
                .windows(b"\x1b[?1003h".len())
                .any(|w| w == b"\x1b[?1003h"),
            "mouse enable must not include 1003 any-event mode"
        );
        assert!(
            MOUSE_ENABLE_SEQ
                .windows(b"\x1b[?1000h".len())
                .any(|w| w == b"\x1b[?1000h"),
            "mouse enable should include 1000 normal tracking"
        );
        assert!(
            MOUSE_ENABLE_SEQ
                .windows(b"\x1b[?1002h".len())
                .any(|w| w == b"\x1b[?1002h"),
            "mouse enable should include 1002 button-event tracking"
        );
        assert!(
            MOUSE_ENABLE_SEQ
                .windows(b"\x1b[?1006h".len())
                .any(|w| w == b"\x1b[?1006h"),
            "mouse enable should include 1006 SGR tracking"
        );
        let pos_1016l = MOUSE_ENABLE_SEQ
            .windows(b"\x1b[?1016l".len())
            .position(|w| w == b"\x1b[?1016l")
            .expect("mouse enable should clear 1016 before enabling SGR");
        let pos_1006h = MOUSE_ENABLE_SEQ
            .windows(b"\x1b[?1006h".len())
            .position(|w| w == b"\x1b[?1006h")
            .expect("mouse enable should include 1006 SGR mode");
        assert!(
            pos_1016l < pos_1006h,
            "1016l must be emitted before 1006h to preserve SGR mode on Ghostty-like terminals"
        );
    }

    #[test]
    fn mouse_enable_mux_safe_sequence_is_minimal() {
        let mux_caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .in_tmux(true)
            .build();
        assert_eq!(
            TerminalSession::mouse_enable_sequence_for_caps(&mux_caps),
            MOUSE_ENABLE_MUX_SAFE_SEQ
        );
        assert!(
            MOUSE_ENABLE_MUX_SAFE_SEQ
                .windows(b"\x1b[?1005l".len())
                .any(|w| w == b"\x1b[?1005l"),
            "mux-safe mouse enable must clear UTF-8 mouse encoding (1005)"
        );
        assert!(
            MOUSE_ENABLE_MUX_SAFE_SEQ
                .windows(b"\x1b[?1015l".len())
                .any(|w| w == b"\x1b[?1015l"),
            "mux-safe mouse enable must clear urxvt mouse encoding (1015)"
        );
        assert!(
            MOUSE_ENABLE_MUX_SAFE_SEQ
                .windows(b"\x1b[?1006h".len())
                .any(|w| w == b"\x1b[?1006h"),
            "mux-safe mouse enable must keep SGR mode"
        );
        assert!(
            !MOUSE_ENABLE_MUX_SAFE_SEQ
                .windows(b"\x1b[?1003h".len())
                .any(|w| w == b"\x1b[?1003h"),
            "mux-safe mouse enable must not include 1003 any-event mode"
        );
        let pos_1016l = MOUSE_ENABLE_MUX_SAFE_SEQ
            .windows(b"\x1b[?1016l".len())
            .position(|w| w == b"\x1b[?1016l")
            .expect("mux-safe mouse enable should clear 1016 before enabling SGR");
        let pos_1006h = MOUSE_ENABLE_MUX_SAFE_SEQ
            .windows(b"\x1b[?1006h".len())
            .position(|w| w == b"\x1b[?1006h")
            .expect("mux-safe mouse enable should include 1006 SGR mode");
        assert!(
            pos_1016l < pos_1006h,
            "mux-safe mouse enable must emit 1016l before 1006h to preserve SGR mode"
        );
    }

    #[test]
    fn mouse_disable_mux_safe_sequence_clears_1016() {
        let mux_caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .in_tmux(true)
            .build();
        assert_eq!(
            TerminalSession::mouse_disable_sequence_for_caps(&mux_caps),
            MOUSE_DISABLE_MUX_SAFE_SEQ
        );
        let pos_1016l = MOUSE_DISABLE_MUX_SAFE_SEQ
            .windows(b"\x1b[?1016l".len())
            .position(|w| w == b"\x1b[?1016l")
            .expect("mux-safe mouse disable should clear 1016");
        let pos_1006l = MOUSE_DISABLE_MUX_SAFE_SEQ
            .windows(b"\x1b[?1006l".len())
            .position(|w| w == b"\x1b[?1006l")
            .expect("mux-safe mouse disable should disable 1006");
        assert!(
            pos_1016l < pos_1006l,
            "mux-safe mouse disable should clear 1016 before dropping SGR mode"
        );
    }

    #[test]
    fn session_options_partial_config() {
        let opts = SessionOptions {
            alternate_screen: true,
            mouse_capture: false,
            bracketed_paste: true,
            ..Default::default()
        };
        assert!(opts.alternate_screen);
        assert!(!opts.mouse_capture);
        assert!(opts.bracketed_paste);
        assert!(!opts.focus_events);
        assert!(!opts.kitty_keyboard);
    }

    #[test]
    fn sanitize_session_options_disables_unsupported_capabilities() {
        let requested = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        let caps = TerminalCapabilities::basic();
        let sanitized = sanitize_session_options(requested, &caps);

        assert!(sanitized.alternate_screen);
        assert!(!sanitized.mouse_capture);
        assert!(!sanitized.bracketed_paste);
        assert!(!sanitized.focus_events);
        assert!(!sanitized.kitty_keyboard);
    }

    #[test]
    fn sanitize_session_options_is_conservative_in_wezterm_mux() {
        let requested = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        let caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .bracketed_paste(true)
            .focus_events(true)
            .kitty_keyboard(true)
            .in_wezterm_mux(true)
            .build();
        let sanitized = sanitize_session_options(requested, &caps);

        assert!(sanitized.alternate_screen);
        assert!(sanitized.mouse_capture);
        assert!(sanitized.bracketed_paste);
        assert!(!sanitized.focus_events);
        assert!(!sanitized.kitty_keyboard);
    }

    #[test]
    fn sanitize_session_options_is_conservative_in_tmux() {
        let requested = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        let caps = TerminalCapabilities::builder()
            .mouse_sgr(true)
            .bracketed_paste(true)
            .focus_events(true)
            .kitty_keyboard(true)
            .in_tmux(true)
            .build();
        let sanitized = sanitize_session_options(requested, &caps);

        assert!(sanitized.alternate_screen);
        assert!(sanitized.mouse_capture);
        assert!(sanitized.bracketed_paste);
        assert!(!sanitized.focus_events);
        assert!(!sanitized.kitty_keyboard);
    }

    #[cfg(unix)]
    enum ReaderMsg {
        Data(Vec<u8>),
        Eof,
        Err(std::io::Error),
    }

    #[cfg(unix)]
    fn read_until_pattern(
        rx: &mpsc::Receiver<ReaderMsg>,
        captured: &mut Vec<u8>,
        pattern: &[u8],
        timeout: Duration,
    ) -> std::io::Result<()> {
        let deadline = Instant::now() + timeout;
        while Instant::now() < deadline {
            let remaining = deadline.saturating_duration_since(Instant::now());
            let wait = remaining.min(Duration::from_millis(50));
            match rx.recv_timeout(wait) {
                Ok(ReaderMsg::Data(chunk)) => {
                    captured.extend_from_slice(&chunk);
                    if captured.windows(pattern.len()).any(|w| w == pattern) {
                        return Ok(());
                    }
                }
                Ok(ReaderMsg::Eof) => break,
                Ok(ReaderMsg::Err(err)) => return Err(err),
                Err(mpsc::RecvTimeoutError::Timeout) => continue,
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
        Err(std::io::Error::other(
            "timeout waiting for PTY output marker",
        ))
    }

    #[cfg(unix)]
    fn assert_contains_any(output: &[u8], options: &[&[u8]], label: &str) {
        let found = options
            .iter()
            .any(|needle| output.windows(needle.len()).any(|w| w == *needle));
        assert!(found, "expected cleanup sequence for {label}");
    }

    // -----------------------------------------------------------------------
    // Kitty keyboard escape helpers
    // -----------------------------------------------------------------------

    #[test]
    fn kitty_keyboard_enable_writes_correct_sequence() {
        let mut buf = Vec::new();
        TerminalSession::enable_kitty_keyboard(&mut buf).unwrap();
        assert_eq!(buf, b"\x1b[>15u");
    }

    #[test]
    fn kitty_keyboard_disable_writes_correct_sequence() {
        let mut buf = Vec::new();
        TerminalSession::disable_kitty_keyboard(&mut buf).unwrap();
        assert_eq!(buf, b"\x1b[<u");
    }

    #[test]
    fn kitty_keyboard_roundtrip_writes_both_sequences() {
        let mut buf = Vec::new();
        TerminalSession::enable_kitty_keyboard(&mut buf).unwrap();
        TerminalSession::disable_kitty_keyboard(&mut buf).unwrap();
        assert_eq!(buf, b"\x1b[>15u\x1b[<u");
    }

    // -----------------------------------------------------------------------
    // SessionOptions exhaustive
    // -----------------------------------------------------------------------

    #[test]
    fn session_options_all_enabled() {
        let opts = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        assert!(opts.alternate_screen);
        assert!(opts.mouse_capture);
        assert!(opts.bracketed_paste);
        assert!(opts.focus_events);
        assert!(opts.kitty_keyboard);
    }

    #[test]
    fn session_options_debug_contains_all_fields() {
        let opts = SessionOptions {
            alternate_screen: true,
            mouse_capture: false,
            bracketed_paste: true,
            focus_events: false,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        let debug = format!("{opts:?}");
        assert!(debug.contains("alternate_screen: true"), "{debug}");
        assert!(debug.contains("mouse_capture: false"), "{debug}");
        assert!(debug.contains("bracketed_paste: true"), "{debug}");
        assert!(debug.contains("focus_events: false"), "{debug}");
        assert!(debug.contains("kitty_keyboard: true"), "{debug}");
        assert!(debug.contains("intercept_signals: true"), "{debug}");
    }

    #[test]
    fn session_options_clone_independence() {
        let opts = SessionOptions {
            alternate_screen: true,
            ..Default::default()
        };
        let mut cloned = opts.clone();
        cloned.alternate_screen = false;
        // Original unchanged
        assert!(opts.alternate_screen);
        assert!(!cloned.alternate_screen);
    }

    // -----------------------------------------------------------------------
    // new_for_tests construction (requires test-helpers feature)
    // -----------------------------------------------------------------------

    #[cfg(feature = "test-helpers")]
    #[test]
    fn new_for_tests_default_options() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        assert!(!session.mouse_capture_enabled());
        assert!(!session.alternate_screen_enabled);
        assert!(!session.mouse_enabled);
        assert!(!session.bracketed_paste_enabled);
        assert!(!session.focus_events_enabled);
        assert!(!session.kitty_keyboard_enabled);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn new_for_tests_preserves_options() {
        let opts = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        let session = TerminalSession::new_for_tests(opts).unwrap();
        let stored = session.options();
        assert!(stored.alternate_screen);
        assert!(stored.mouse_capture);
        assert!(stored.bracketed_paste);
        assert!(stored.focus_events);
        assert!(stored.kitty_keyboard);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn new_for_tests_flags_all_false_regardless_of_options() {
        // Even if options request features, new_for_tests skips enabling them
        let opts = SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        };
        let session = TerminalSession::new_for_tests(opts).unwrap();
        // Flags track *actual* enabled state, not *requested* state
        assert!(!session.alternate_screen_enabled);
        assert!(!session.mouse_enabled);
        assert!(!session.bracketed_paste_enabled);
        assert!(!session.focus_events_enabled);
        assert!(!session.kitty_keyboard_enabled);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn new_for_tests_allows_multiple_sessions() {
        let _a = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let _b = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn new_for_tests_marks_session_headless() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        assert!(session.headless);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn mouse_capture_enabled_getter() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        assert!(!session.mouse_capture_enabled());
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn options_getter_returns_session_options() {
        let opts = SessionOptions {
            mouse_capture: true,
            focus_events: true,
            ..Default::default()
        };
        let session = TerminalSession::new_for_tests(opts).unwrap();
        assert!(session.options().mouse_capture);
        assert!(session.options().focus_events);
        assert!(!session.options().alternate_screen);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn set_mouse_capture_idempotent_disable() {
        let mut session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        // Already disabled - should be no-op
        assert!(!session.mouse_capture_enabled());
        session.set_mouse_capture(false).unwrap();
        assert!(!session.mouse_capture_enabled());
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn set_mouse_capture_enable_then_idempotent_enable() {
        let _g = crate::capability_override::push_override(
            crate::capability_override::CapabilityOverride::modern(),
        );
        let mut session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        // Enable mouse
        session.set_mouse_capture(true).unwrap();
        assert!(session.mouse_capture_enabled());
        assert!(session.options().mouse_capture);
        // Enable again - idempotent
        session.set_mouse_capture(true).unwrap();
        assert!(session.mouse_capture_enabled());
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn set_mouse_capture_toggle_roundtrip() {
        let _g = crate::capability_override::push_override(
            crate::capability_override::CapabilityOverride::modern(),
        );
        let mut session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        assert!(!session.mouse_capture_enabled());

        session.set_mouse_capture(true).unwrap();
        assert!(session.mouse_capture_enabled());
        assert!(session.options().mouse_capture);

        session.set_mouse_capture(false).unwrap();
        assert!(!session.mouse_capture_enabled());
        assert!(!session.options().mouse_capture);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn set_mouse_capture_multiple_toggles() {
        let _g = crate::capability_override::push_override(
            crate::capability_override::CapabilityOverride::modern(),
        );
        let mut session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        for _ in 0..5 {
            session.set_mouse_capture(true).unwrap();
            assert!(session.mouse_capture_enabled());
            session.set_mouse_capture(false).unwrap();
            assert!(!session.mouse_capture_enabled());
        }
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn cleanup_clears_all_flags() {
        let mut session = TerminalSession::new_for_tests(SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        })
        .unwrap();
        // Manually set flags to simulate features being enabled
        session.alternate_screen_enabled = true;
        session.mouse_enabled = true;
        session.bracketed_paste_enabled = true;
        session.focus_events_enabled = true;
        session.kitty_keyboard_enabled = true;

        session.cleanup();

        assert!(!session.alternate_screen_enabled);
        assert!(!session.mouse_enabled);
        assert!(!session.bracketed_paste_enabled);
        assert!(!session.focus_events_enabled);
        assert!(!session.kitty_keyboard_enabled);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn cleanup_is_idempotent() {
        let mut session = TerminalSession::new_for_tests(SessionOptions {
            mouse_capture: true,
            ..Default::default()
        })
        .unwrap();
        session.mouse_enabled = true;

        session.cleanup();
        assert!(!session.mouse_enabled);
        // Second cleanup should be safe (no-op since flags already cleared)
        session.cleanup();
        assert!(!session.mouse_enabled);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn cleanup_only_disables_enabled_features() {
        let mut session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        // Only enable mouse, leave others off
        session.mouse_enabled = true;
        // Cleanup should handle partial state gracefully
        session.cleanup();
        assert!(!session.mouse_enabled);
        assert!(!session.alternate_screen_enabled);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn cleanup_headless_session_clears_feature_flags() {
        let mut session = TerminalSession::new_for_tests(SessionOptions {
            alternate_screen: true,
            mouse_capture: true,
            bracketed_paste: true,
            focus_events: true,
            kitty_keyboard: true,
            intercept_signals: true,
        })
        .unwrap();
        session.alternate_screen_enabled = true;
        session.mouse_enabled = true;
        session.bracketed_paste_enabled = true;
        session.focus_events_enabled = true;
        session.kitty_keyboard_enabled = true;

        session.cleanup();

        assert!(!session.alternate_screen_enabled);
        assert!(!session.mouse_enabled);
        assert!(!session.bracketed_paste_enabled);
        assert!(!session.focus_events_enabled);
        assert!(!session.kitty_keyboard_enabled);
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn session_debug_format() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let debug = format!("{session:?}");
        assert!(debug.contains("TerminalSession"), "{debug}");
        assert!(debug.contains("mouse_enabled"), "{debug}");
        assert!(debug.contains("alternate_screen_enabled"), "{debug}");
    }

    #[test]
    fn panic_cleanup_suppression_scope_restores_state() {
        assert!(
            !panic_cleanup_suppressed(),
            "suppression should start disabled"
        );
        with_panic_cleanup_suppressed(|| {
            if cfg!(panic = "abort") {
                assert!(
                    !panic_cleanup_suppressed(),
                    "abort profile must not suppress panic cleanup"
                );
                return;
            }
            assert!(panic_cleanup_suppressed(), "suppression should be enabled");
            with_panic_cleanup_suppressed(|| {
                assert!(
                    panic_cleanup_suppressed(),
                    "nested suppression should remain enabled"
                );
            });
            assert!(
                panic_cleanup_suppressed(),
                "outer suppression should still be enabled after nested scope"
            );
        });
        assert!(
            !panic_cleanup_suppressed(),
            "suppression should be disabled after scope exits"
        );
    }

    // -----------------------------------------------------------------------
    // PTY integration tests
    // -----------------------------------------------------------------------

    #[cfg(unix)]
    #[test]
    fn terminal_session_panic_cleanup_idempotent() {
        const MARKER: &[u8] = b"PANIC_CAUGHT";
        const TEST_NAME: &str =
            "terminal_session::tests::terminal_session_panic_cleanup_idempotent";
        const ALT_SCREEN_EXIT_SEQS: &[&[u8]] = &[b"\x1b[?1049l", b"\x1b[?1047l"];
        const MOUSE_DISABLE_SEQS: &[&[u8]] = &[
            b"\x1b[?1000l\x1b[?1002l\x1b[?1006l",
            b"\x1b[?1000;1002;1006l",
            b"\x1b[?1000;1002l",
            b"\x1b[?1000l",
        ];
        const BRACKETED_PASTE_DISABLE_SEQS: &[&[u8]] = &[b"\x1b[?2004l"];
        const FOCUS_DISABLE_SEQS: &[&[u8]] = &[b"\x1b[?1004l"];
        const KITTY_DISABLE_SEQS: &[&[u8]] = &[b"\x1b[<u"];
        const CURSOR_SHOW_SEQS: &[&[u8]] = &[b"\x1b[?25h"];
        const SCROLL_REGION_RESET_SEQS: &[&[u8]] = &[b"\x1b[r"];
        const STYLE_RESET_SEQS: &[&[u8]] = &[b"\x1b[0m"];

        if std::env::var("FTUI_CORE_PANIC_CHILD").is_ok() {
            let _ = std::panic::catch_unwind(|| {
                let _session = TerminalSession::new(SessionOptions {
                    alternate_screen: true,
                    mouse_capture: true,
                    bracketed_paste: true,
                    focus_events: true,
                    kitty_keyboard: true,
                    intercept_signals: true,
                })
                .expect("TerminalSession::new should succeed in PTY");
                panic!("intentional panic to exercise cleanup");
            });

            // The panic hook + Drop will have already attempted cleanup; call again to
            // verify idempotence when cleanup paths run multiple times.
            best_effort_cleanup_for_exit();

            let _ = io::stdout().write_all(MARKER);
            let _ = io::stdout().flush();
            return;
        }

        let exe = std::env::current_exe().expect("current_exe");
        let mut cmd = CommandBuilder::new(exe);
        cmd.args(["--exact", TEST_NAME, "--nocapture"]);
        cmd.env("FTUI_CORE_PANIC_CHILD", "1");
        cmd.env("RUST_BACKTRACE", "0");
        cmd.env("TERM", "xterm-256color");
        cmd.env("FTUI_TEST_PROFILE", "modern");
        cmd.env("TERM_PROGRAM", "WezTerm");
        cmd.env_remove("TMUX");
        cmd.env_remove("STY");
        cmd.env_remove("ZELLIJ");
        cmd.env_remove("WEZTERM_PANE");

        let pty_system = portable_pty::native_pty_system();
        let pair = pty_system
            .openpty(PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })
            .expect("openpty");

        let mut child = pair.slave.spawn_command(cmd).expect("spawn PTY child");
        drop(pair.slave);

        let mut reader = pair.master.try_clone_reader().expect("clone PTY reader");
        let _writer = pair.master.take_writer().expect("take PTY writer");

        let (tx, rx) = mpsc::channel::<ReaderMsg>();
        let reader_thread = thread::spawn(move || {
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf) {
                    Ok(0) => {
                        let _ = tx.send(ReaderMsg::Eof);
                        break;
                    }
                    Ok(n) => {
                        let _ = tx.send(ReaderMsg::Data(buf[..n].to_vec()));
                    }
                    Err(err) => {
                        let _ = tx.send(ReaderMsg::Err(err));
                        break;
                    }
                }
            }
        });

        let mut captured = Vec::new();
        read_until_pattern(&rx, &mut captured, MARKER, Duration::from_secs(5))
            .expect("expected marker from child");

        let status = child.wait().expect("child wait");
        let _ = reader_thread.join();

        assert!(status.success(), "child should exit successfully");
        assert!(
            captured.windows(MARKER.len()).any(|w| w == MARKER),
            "expected panic marker in PTY output"
        );
        assert_contains_any(&captured, ALT_SCREEN_EXIT_SEQS, "alt-screen exit");
        assert_contains_any(&captured, MOUSE_DISABLE_SEQS, "mouse disable");
        assert_contains_any(
            &captured,
            BRACKETED_PASTE_DISABLE_SEQS,
            "bracketed paste disable",
        );
        assert_contains_any(&captured, FOCUS_DISABLE_SEQS, "focus disable");
        assert_contains_any(&captured, KITTY_DISABLE_SEQS, "kitty disable");
        assert_contains_any(&captured, CURSOR_SHOW_SEQS, "cursor show");
        assert_contains_any(&captured, SCROLL_REGION_RESET_SEQS, "scroll-region reset");
        assert_contains_any(&captured, STYLE_RESET_SEQS, "style reset");
    }

    #[cfg(unix)]
    #[test]
    fn terminal_session_enforces_single_active_session() {
        const MARKER: &[u8] = b"EXCLUSIVITY_OK";
        const TEST_NAME: &str =
            "terminal_session::tests::terminal_session_enforces_single_active_session";

        if std::env::var("FTUI_CORE_EXCLUSIVITY_CHILD").is_ok() {
            let session = TerminalSession::new(SessionOptions::default())
                .expect("TerminalSession::new should succeed in PTY");
            let err = TerminalSession::new(SessionOptions::default())
                .expect_err("second TerminalSession::new should be rejected");
            let msg = err.to_string();
            assert!(
                msg.contains("already active"),
                "unexpected error message: {msg}"
            );
            drop(session);

            let _session2 = TerminalSession::new(SessionOptions::default())
                .expect("TerminalSession::new should succeed after previous session dropped");

            let _ = io::stdout().write_all(MARKER);
            let _ = io::stdout().flush();
            return;
        }

        let exe = std::env::current_exe().expect("current_exe");
        let mut cmd = CommandBuilder::new(exe);
        cmd.args(["--exact", TEST_NAME, "--nocapture"]);
        cmd.env("FTUI_CORE_EXCLUSIVITY_CHILD", "1");
        cmd.env("RUST_BACKTRACE", "0");
        cmd.env("TERM", "xterm-256color");
        cmd.env("TERM_PROGRAM", "WezTerm");
        cmd.env_remove("TMUX");
        cmd.env_remove("STY");
        cmd.env_remove("ZELLIJ");
        cmd.env_remove("WEZTERM_PANE");

        let pty_system = portable_pty::native_pty_system();
        let pair = pty_system
            .openpty(PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })
            .expect("openpty");

        let mut child = pair.slave.spawn_command(cmd).expect("spawn PTY child");
        drop(pair.slave);

        let mut reader = pair.master.try_clone_reader().expect("clone PTY reader");
        let _writer = pair.master.take_writer().expect("take PTY writer");

        let (tx, rx) = mpsc::channel::<ReaderMsg>();
        let reader_thread = thread::spawn(move || {
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf) {
                    Ok(0) => {
                        let _ = tx.send(ReaderMsg::Eof);
                        break;
                    }
                    Ok(n) => {
                        let _ = tx.send(ReaderMsg::Data(buf[..n].to_vec()));
                    }
                    Err(err) => {
                        let _ = tx.send(ReaderMsg::Err(err));
                        break;
                    }
                }
            }
        });

        let mut captured = Vec::new();
        read_until_pattern(&rx, &mut captured, MARKER, Duration::from_secs(5))
            .expect("expected marker from child");

        let status = child.wait().expect("child wait");
        let _ = reader_thread.join();

        assert!(status.success(), "child should exit successfully");
        assert!(
            captured.windows(MARKER.len()).any(|w| w == MARKER),
            "expected marker in PTY output"
        );
    }

    // -----------------------------------------------------------------------
    // Cx helper function tests
    // -----------------------------------------------------------------------

    #[test]
    fn to_std_duration_converts_correctly() {
        let d = web_time::Duration::from_millis(1234);
        let std_d = super::to_std_duration(d);
        assert_eq!(std_d, Duration::from_millis(1234));
    }

    #[test]
    fn to_std_duration_zero() {
        let d = web_time::Duration::from_secs(0);
        let std_d = super::to_std_duration(d);
        assert_eq!(std_d, Duration::ZERO);
    }

    #[test]
    fn to_std_duration_large_value() {
        let d = web_time::Duration::from_secs(86400);
        let std_d = super::to_std_duration(d);
        assert_eq!(std_d, Duration::from_secs(86400));
    }

    #[test]
    fn cx_deadline_remaining_us_no_deadline() {
        let (cx, _ctrl) = crate::cx::Cx::background();
        let remaining = super::cx_deadline_remaining_us(&cx);
        assert_eq!(remaining, u64::MAX);
    }

    #[test]
    fn cx_deadline_remaining_us_with_deadline() {
        let (cx, _ctrl) = crate::cx::Cx::with_deadline(web_time::Duration::from_millis(500));
        let remaining = super::cx_deadline_remaining_us(&cx);
        // Should be approximately 500_000 us (allow some elapsed time)
        assert!(remaining <= 500_000, "remaining={remaining}");
        assert!(remaining > 400_000, "remaining={remaining}");
    }

    #[test]
    fn cx_deadline_remaining_us_cancelled() {
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        // No deadline means u64::MAX even when cancelled (deadline is separate from cancellation)
        assert_eq!(super::cx_deadline_remaining_us(&cx), u64::MAX);
    }

    #[test]
    fn cx_deadline_remaining_us_expired() {
        let (cx, _ctrl) = crate::cx::Cx::with_deadline(web_time::Duration::from_nanos(1));
        std::thread::sleep(Duration::from_millis(2));
        let remaining = super::cx_deadline_remaining_us(&cx);
        assert_eq!(remaining, 0);
    }

    // -----------------------------------------------------------------------
    // Metrics function tests
    // -----------------------------------------------------------------------

    #[test]
    fn terminal_io_stats_functions_return_tuples() {
        // Verify the metric accessor functions return without panicking.
        let (_sum, _count) = terminal_io_read_stats();
        let (_sum_w, _count_w) = terminal_io_write_stats();
        let (_sum_f, _count_f) = terminal_io_flush_stats();
    }

    #[test]
    fn terminal_io_metrics_counters_are_monotonic() {
        // Read initial state
        let (_, count_before) = terminal_io_read_stats();
        // Counters are global and shared across tests — just verify they don't decrease
        let (_, count_after) = terminal_io_read_stats();
        assert!(count_after >= count_before);
    }

    // -----------------------------------------------------------------------
    // Cx-aware method tests (using test-helpers feature)
    // -----------------------------------------------------------------------

    #[cfg(feature = "test-helpers")]
    #[test]
    fn poll_event_cx_returns_false_when_cancelled() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        let result = session.poll_event_cx(Duration::from_secs(10), &cx);
        assert!(result.is_ok());
        assert!(
            !result.unwrap(),
            "cancelled cx should return false immediately"
        );
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn poll_event_cx_returns_false_when_expired() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, _ctrl) = crate::cx::Cx::with_deadline(web_time::Duration::from_nanos(1));
        std::thread::sleep(Duration::from_millis(2));
        let result = session.poll_event_cx(Duration::from_secs(10), &cx);
        assert!(result.is_ok());
        assert!(
            !result.unwrap(),
            "expired cx should return false immediately"
        );
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn read_event_cx_returns_none_when_cancelled() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        let result = session.read_event_cx(&cx);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none(), "cancelled cx should return None");
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn read_event_cx_returns_none_when_expired() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, _ctrl) = crate::cx::Cx::with_deadline(web_time::Duration::from_nanos(1));
        std::thread::sleep(Duration::from_millis(2));
        let result = session.read_event_cx(&cx);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none(), "expired cx should return None");
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn show_cursor_cx_noop_when_cancelled() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        assert!(session.show_cursor_cx(&cx).is_ok());
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn hide_cursor_cx_noop_when_cancelled() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        assert!(session.hide_cursor_cx(&cx).is_ok());
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn flush_cx_noop_when_cancelled() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        assert!(session.flush_cx(&cx).is_ok());
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn size_cx_returns_minimum_when_cancelled() {
        let session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        let (w, h) = session.size_cx(&cx).unwrap();
        assert!(w >= 2, "width={w}");
        assert!(h >= 2, "height={h}");
    }

    #[cfg(feature = "test-helpers")]
    #[test]
    fn set_mouse_capture_cx_noop_when_cancelled() {
        let mut session = TerminalSession::new_for_tests(SessionOptions::default()).unwrap();
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        assert!(session.set_mouse_capture_cx(true, &cx).is_ok());
        // Mouse should NOT be enabled since cx was cancelled
        assert!(!session.mouse_capture_enabled());
    }

    // -----------------------------------------------------------------------
    // Cx-aware methods with Lab clock (deterministic timing)
    // -----------------------------------------------------------------------

    #[test]
    fn cx_lab_deadline_remaining_us_deterministic() {
        let clock = crate::cx::LabClock::new();
        let (cx, _ctrl) =
            crate::cx::Cx::lab_with_deadline(&clock, web_time::Duration::from_millis(100));
        // Lab clock hasn't advanced, so remaining should be ~100ms
        let remaining = super::cx_deadline_remaining_us(&cx);
        assert!(remaining <= 100_000, "remaining={remaining}");
        assert!(remaining > 90_000, "remaining={remaining}");

        // Advance clock by 50ms
        clock.advance(web_time::Duration::from_millis(50));
        let remaining = super::cx_deadline_remaining_us(&cx);
        assert!(remaining <= 50_000, "remaining={remaining}");
        assert!(remaining > 40_000, "remaining={remaining}");
    }

    #[test]
    fn size_retry_delay_uses_default_window_without_deadline() {
        let (cx, _ctrl) = crate::cx::Cx::background();
        assert_eq!(super::size_retry_delay(&cx), Some(SIZE_RETRY_DELAY));
    }

    #[test]
    fn size_retry_delay_skips_when_cancelled() {
        let (cx, ctrl) = crate::cx::Cx::background();
        ctrl.cancel();
        assert_eq!(super::size_retry_delay(&cx), None);
    }

    #[test]
    fn size_retry_delay_skips_when_deadline_cannot_cover_retry() {
        let clock = crate::cx::LabClock::new();
        let (cx, _ctrl) =
            crate::cx::Cx::lab_with_deadline(&clock, web_time::Duration::from_millis(10));
        assert_eq!(super::size_retry_delay(&cx), None);
    }

    #[test]
    fn size_retry_delay_allows_retry_when_budget_exceeds_delay() {
        let clock = crate::cx::LabClock::new();
        let (cx, _ctrl) =
            crate::cx::Cx::lab_with_deadline(&clock, web_time::Duration::from_millis(25));
        assert_eq!(super::size_retry_delay(&cx), Some(SIZE_RETRY_DELAY));
    }

    #[test]
    fn pending_termination_signal_round_trip() {
        crate::shutdown_signal::with_test_signal_serialization(|| {
            crate::shutdown_signal::clear_pending_termination_signal();
            assert_eq!(crate::shutdown_signal::pending_termination_signal(), None);

            crate::shutdown_signal::record_pending_termination_signal(2);
            assert_eq!(
                crate::shutdown_signal::pending_termination_signal(),
                Some(2)
            );

            // First signal wins until explicitly cleared.
            crate::shutdown_signal::record_pending_termination_signal(15);
            assert_eq!(
                crate::shutdown_signal::pending_termination_signal(),
                Some(2)
            );

            crate::shutdown_signal::clear_pending_termination_signal();
            assert_eq!(crate::shutdown_signal::pending_termination_signal(), None);
        });
    }
}