aprender-present-terminal 0.31.2

Terminal backend for Presentar UI framework with zero-allocation rendering
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
//! Application state and data collectors for ptop.
//!
//! Mirrors ttop's app.rs - maintains system state and history.

use crossterm::event::{KeyCode, KeyModifiers};
use std::time::Duration;

use sysinfo::{
    CpuRefreshKind, Disks, MemoryRefreshKind, Networks, ProcessRefreshKind, ProcessesToUpdate,
    System, Users,
};

use super::config::{DetailLevel, FilesViewMode, PanelType, PtopConfig, SignalType};
use super::ui::{read_gpu_info, GpuInfo};

/// Parse a single meminfo line to extract value in bytes.
/// Format: "Label:          1234567 kB"
#[cfg(target_os = "linux")]
fn parse_meminfo_line(line: &str) -> Option<u64> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    parts
        .get(1)
        .and_then(|s| s.parse::<u64>().ok())
        .map(|kb| kb * 1024)
}

/// Check if line is the Cached memory line (not SwapCached).
#[cfg(target_os = "linux")]
fn is_cached_line(line: &str) -> bool {
    line.starts_with("Cached:") && !line.starts_with("CachedSwap")
}

/// Read cached memory from /proc/meminfo (Linux only).
/// Returns bytes, or 0 if unavailable.
#[cfg(target_os = "linux")]
fn read_cached_memory() -> u64 {
    std::fs::read_to_string("/proc/meminfo")
        .ok()
        .and_then(|contents| {
            contents
                .lines()
                .find(|line| is_cached_line(line))
                .and_then(parse_meminfo_line)
        })
        .unwrap_or(0)
}

#[cfg(not(target_os = "linux"))]
fn read_cached_memory() -> u64 {
    // On non-Linux systems, return 0 (cached memory not available via /proc)
    0
}

/// Map CCD temperatures to core array (AMD processors).
///
/// AMD Threadripper/EPYC: cores are distributed across CCDs.
/// Each CCD gets an equal share of cores.
#[cfg(target_os = "linux")]
fn map_ccd_temps_to_cores(ccd_temps: &std::collections::HashMap<String, f32>, temps: &mut [f32]) {
    let core_count = temps.len();
    let cores_per_ccd = core_count / 4;

    // Assign CCD temperatures to corresponding cores.
    for (ccd_idx, label) in ["Tccd1", "Tccd2", "Tccd3", "Tccd4"].iter().enumerate() {
        if let Some(&temp) = ccd_temps.get(*label) {
            let start = cores_per_ccd * ccd_idx;
            let end = if ccd_idx == 3 {
                core_count
            } else {
                (cores_per_ccd * (ccd_idx + 1)).min(core_count)
            };
            for i in start..end {
                temps[i] = temp;
            }
        }
    }

    // Fallback to Tctl if no CCD temps found
    if temps.iter().all(|&t| t == 0.0) {
        if let Some(&tctl) = ccd_temps.get("Tctl") {
            temps.fill(tctl);
        }
    }
}

/// Read AMD k10temp/zenpower temperatures from hwmon path.
#[cfg(target_os = "linux")]
fn read_amd_temps(path: &std::path::Path, temps: &mut [f32]) -> bool {
    use std::collections::HashMap;
    use std::fs;

    let mut ccd_temps: HashMap<String, f32> = HashMap::new();

    // Read temperature sensor labels and values.
    for i in 1..=10 {
        let label_path = path.join(format!("temp{i}_label"));
        let input_path = path.join(format!("temp{i}_input"));

        if let (Ok(label), Ok(input)) = (
            fs::read_to_string(&label_path),
            fs::read_to_string(&input_path),
        ) {
            let label = label.trim().to_string();
            if let Ok(millidegrees) = input.trim().parse::<i64>() {
                ccd_temps.insert(label, millidegrees as f32 / 1000.0);
            }
        }
    }

    if ccd_temps.is_empty() {
        return false;
    }

    map_ccd_temps_to_cores(&ccd_temps, temps);
    true
}

/// Read Intel coretemp temperatures from hwmon path.
#[cfg(target_os = "linux")]
fn read_intel_temps(path: &std::path::Path, temps: &mut [f32]) -> bool {
    use std::fs;

    // Intel: temp2_input = Core 0, temp3_input = Core 1, etc.
    for (i, temp) in temps.iter_mut().enumerate() {
        let temp_file = path.join(format!("temp{}_input", i + 2));
        if let Ok(temp_str) = fs::read_to_string(&temp_file) {
            if let Ok(millidegrees) = temp_str.trim().parse::<i64>() {
                *temp = millidegrees as f32 / 1000.0;
            }
        }
    }

    // Use package temperature when per-core temps unavailable.
    if temps.iter().all(|&t| t == 0.0) {
        let temp_file = path.join("temp1_input");
        if let Ok(temp_str) = fs::read_to_string(&temp_file) {
            if let Ok(millidegrees) = temp_str.trim().parse::<i64>() {
                temps.fill(millidegrees as f32 / 1000.0);
                return true;
            }
        }
        return false;
    }
    true
}

/// Try to read CPU temperatures from a single hwmon device.
#[cfg(target_os = "linux")]
fn try_read_hwmon_temps(path: &std::path::Path, temps: &mut [f32]) -> bool {
    use std::fs;

    let Ok(name) = fs::read_to_string(path.join("name")) else {
        return false;
    };

    match name.trim() {
        "k10temp" | "zenpower" => read_amd_temps(path, temps),
        "coretemp" => read_intel_temps(path, temps),
        _ => false,
    }
}

/// Read per-core CPU temperatures from /sys/class/hwmon (Linux only).
/// Returns temperatures in °C, or zeros if unavailable.
#[cfg(target_os = "linux")]
fn read_core_temperatures(core_count: usize) -> Vec<f32> {
    use std::fs;
    use std::path::Path;

    let mut temps = vec![0.0f32; core_count];
    let hwmon_dir = Path::new("/sys/class/hwmon");

    let Ok(entries) = fs::read_dir(hwmon_dir) else {
        return temps;
    };

    for entry in entries.flatten() {
        if try_read_hwmon_temps(&entry.path(), &mut temps) {
            return temps;
        }
    }

    temps
}

#[cfg(not(target_os = "linux"))]
fn read_core_temperatures(core_count: usize) -> Vec<f32> {
    // On non-Linux systems, return zeros
    vec![0.0f32; core_count]
}

use super::analyzers::{
    AnalyzerRegistry, ConnectionsData, DiskEntropyData, DiskIoData, FileAnalyzerData, PsiData,
    SensorHealthData, TreemapData,
};
use crate::{AsyncCollector, Snapshot};

/// Metrics snapshot sent from background collector to main thread.
/// Contains only the data needed for rendering - no heavy objects.
#[derive(Clone)]
pub struct MetricsSnapshot {
    // CPU metrics
    pub cpu_avg: f64,
    pub per_core_percent: Vec<f64>,
    pub per_core_freq: Vec<u64>, // MHz - SPEC-024 async update requirement
    pub per_core_temp: Vec<f32>, // °C - SPEC-024 async update requirement
    pub load_avg: sysinfo::LoadAvg,

    // Memory metrics
    pub mem_total: u64,
    pub mem_used: u64,
    pub mem_available: u64,
    pub mem_cached: u64,
    pub swap_total: u64,
    pub swap_used: u64,

    // Network metrics (bytes since boot)
    pub net_rx: u64,
    pub net_tx: u64,

    // GPU metrics
    pub gpu_info: Option<GpuInfo>,

    // Process list (extracted from sysinfo::System)
    pub processes: Vec<ProcessInfo>,

    // Disk info (extracted from sysinfo::Disks)
    pub disk_info: Vec<DiskInfo>,

    // Network interfaces (extracted from sysinfo::Networks)
    pub network_info: Vec<NetworkInfo>,

    // Analyzer results
    pub psi_data: Option<PsiData>,
    pub connections_data: Option<ConnectionsData>,
    pub treemap_data: Option<TreemapData>,
    pub sensor_health_data: Option<SensorHealthData>,
    pub disk_io_data: Option<DiskIoData>,
    pub disk_entropy_data: Option<DiskEntropyData>,
    pub file_analyzer_data: Option<FileAnalyzerData>,
}

/// Lightweight process info for rendering
#[derive(Clone)]
pub struct ProcessInfo {
    pub pid: u32,
    pub name: String,
    pub cpu_usage: f32,
    pub memory: u64,
    pub user: String,
    pub cmd: String,
}

/// Lightweight disk info for rendering
#[derive(Clone)]
pub struct DiskInfo {
    pub name: String,
    pub mount_point: String,
    pub total_space: u64,
    pub available_space: u64,
    pub file_system: String,
}

/// Lightweight network interface info for rendering
#[derive(Clone)]
pub struct NetworkInfo {
    pub name: String,
    pub received: u64,
    pub transmitted: u64,
}

impl Snapshot for MetricsSnapshot {
    fn empty() -> Self {
        Self {
            cpu_avg: 0.0,
            per_core_percent: Vec::new(),
            per_core_freq: Vec::new(),
            per_core_temp: Vec::new(),
            load_avg: sysinfo::LoadAvg {
                one: 0.0,
                five: 0.0,
                fifteen: 0.0,
            },
            mem_total: 0,
            mem_used: 0,
            mem_available: 0,
            mem_cached: 0,
            swap_total: 0,
            swap_used: 0,
            net_rx: 0,
            net_tx: 0,
            gpu_info: None,
            processes: Vec::new(),
            disk_info: Vec::new(),
            network_info: Vec::new(),
            psi_data: None,
            connections_data: None,
            treemap_data: None,
            sensor_health_data: None,
            disk_io_data: None,
            disk_entropy_data: None,
            file_analyzer_data: None,
        }
    }
}

/// Background metrics collector that owns all heavy I/O objects.
/// Runs in a background thread and produces MetricsSnapshots.
pub struct MetricsCollector {
    system: System,
    disks: Disks,
    networks: Networks,
    analyzers: AnalyzerRegistry,
    deterministic: bool,
    frame_id: u64,
}

impl MetricsCollector {
    /// Create a new collector with initialized system objects.
    pub fn new(deterministic: bool) -> Self {
        let mut system = System::new();

        // Initial CPU sample (need 2 for delta calculation)
        system.refresh_cpu_specifics(CpuRefreshKind::everything());

        let disks = Disks::new_with_refreshed_list();
        let networks = Networks::new_with_refreshed_list();
        let analyzers = AnalyzerRegistry::new();

        Self {
            system,
            disks,
            networks,
            analyzers,
            deterministic,
            frame_id: 0,
        }
    }

    /// Check if PSI is available
    pub fn has_psi(&self) -> bool {
        self.analyzers.psi.is_some()
    }

    /// Check if GPU monitoring is available
    pub fn has_gpu(&self) -> bool {
        self.analyzers.gpu_procs.is_some()
    }

    /// Check if sensor monitoring is available
    pub fn has_sensors(&self) -> bool {
        self.analyzers.sensor_health.is_some()
    }

    /// Check if connection monitoring is available
    pub fn has_connections(&self) -> bool {
        self.analyzers.connections.is_some()
    }

    /// Check if treemap is available
    pub fn has_treemap(&self) -> bool {
        self.analyzers.treemap.is_some()
    }
}

impl AsyncCollector for MetricsCollector {
    type Snapshot = MetricsSnapshot;

    fn collect(&mut self) -> MetricsSnapshot {
        self.frame_id += 1;

        if self.deterministic {
            return MetricsSnapshot::empty();
        }

        // CPU refresh
        self.system
            .refresh_cpu_specifics(CpuRefreshKind::everything());

        let cpu_total: f32 = self
            .system
            .cpus()
            .iter()
            .map(sysinfo::Cpu::cpu_usage)
            .sum::<f32>()
            / self.system.cpus().len().max(1) as f32;

        let per_core_percent: Vec<f64> = self
            .system
            .cpus()
            .iter()
            .map(|c| c.cpu_usage() as f64)
            .collect();

        // SPEC-024: Extract per-core frequency for async updates
        let per_core_freq: Vec<u64> = self
            .system
            .cpus()
            .iter()
            .map(sysinfo::Cpu::frequency)
            .collect();

        // SPEC-024: Extract per-core temperature (from hwmon if available)
        let per_core_temp: Vec<f32> = read_core_temperatures(self.system.cpus().len());

        let load_avg = System::load_average();

        // Memory refresh
        self.system
            .refresh_memory_specifics(MemoryRefreshKind::everything());

        let mem_total = self.system.total_memory();
        let mem_used = self.system.used_memory();
        let mem_available = self.system.available_memory();
        let mem_cached = read_cached_memory();
        let swap_total = self.system.total_swap();
        let swap_used = self.system.used_swap();

        // Process refresh - incremental for performance
        let process_count = self.system.processes().len();
        let needs_initial = process_count == 0;
        let needs_periodic = self.frame_id > 0 && self.frame_id % 60 == 0;

        if needs_initial || needs_periodic {
            self.system.refresh_processes_specifics(
                ProcessesToUpdate::All,
                true,
                ProcessRefreshKind::nothing()
                    .with_cpu()
                    .with_memory()
                    .with_user(sysinfo::UpdateKind::OnlyIfNotSet),
            );
        } else if self.frame_id > 0 {
            let top_pids: Vec<_> = self
                .system
                .processes()
                .iter()
                .filter(|(_, p)| p.cpu_usage() > 0.1)
                .take(50)
                .map(|(pid, _)| *pid)
                .collect();

            if !top_pids.is_empty() {
                self.system.refresh_processes_specifics(
                    ProcessesToUpdate::Some(&top_pids),
                    true,
                    ProcessRefreshKind::nothing()
                        .with_cpu()
                        .with_memory()
                        .with_user(sysinfo::UpdateKind::OnlyIfNotSet),
                );
            }
        }

        // Extract process info
        let processes: Vec<ProcessInfo> = self
            .system
            .processes()
            .iter()
            .map(|(pid, proc)| ProcessInfo {
                pid: pid.as_u32(),
                name: proc.name().to_string_lossy().to_string(),
                cpu_usage: proc.cpu_usage(),
                memory: proc.memory(),
                user: proc.user_id().map(|u| u.to_string()).unwrap_or_default(),
                cmd: proc
                    .cmd()
                    .iter()
                    .map(|s| s.to_string_lossy())
                    .collect::<Vec<_>>()
                    .join(" "),
            })
            .collect();

        // Disk refresh
        self.disks.refresh(true);
        let disk_info: Vec<DiskInfo> = self
            .disks
            .iter()
            .map(|d| DiskInfo {
                name: d.name().to_string_lossy().to_string(),
                mount_point: d.mount_point().to_string_lossy().to_string(),
                total_space: d.total_space(),
                available_space: d.available_space(),
                file_system: d.file_system().to_string_lossy().to_string(),
            })
            .collect();

        // Network refresh
        self.networks.refresh(true);
        let (net_rx, net_tx) = self
            .networks
            .iter()
            .fold((0u64, 0u64), |acc, (_name, data)| {
                (acc.0 + data.received(), acc.1 + data.transmitted())
            });

        let network_info: Vec<NetworkInfo> = self
            .networks
            .iter()
            .map(|(name, data)| NetworkInfo {
                name: name.clone(),
                received: data.received(),
                transmitted: data.transmitted(),
            })
            .collect();

        // GPU info (may call nvidia-smi)
        let gpu_info = read_gpu_info();

        // Analyzer data
        self.analyzers.collect_all();
        let psi_data = self.analyzers.psi.as_ref().map(|p| p.data().clone());
        let connections_data = self
            .analyzers
            .connections
            .as_ref()
            .map(|c| c.data().clone());
        let treemap_data = self.analyzers.treemap.as_ref().map(|t| t.data().clone());
        let sensor_health_data = self
            .analyzers
            .sensor_health
            .as_ref()
            .map(|s| s.data().clone());
        let disk_io_data = self.analyzers.disk_io.as_ref().map(|d| d.data().clone());
        let disk_entropy_data = self
            .analyzers
            .disk_entropy
            .as_ref()
            .map(|d| d.data().clone());
        let file_analyzer_data = self
            .analyzers
            .file_analyzer
            .as_ref()
            .map(|f| f.data().clone());

        MetricsSnapshot {
            cpu_avg: cpu_total as f64 / 100.0,
            per_core_percent,
            per_core_freq,
            per_core_temp,
            load_avg,
            mem_total,
            mem_used,
            mem_available,
            mem_cached,
            swap_total,
            swap_used,
            net_rx,
            net_tx,
            gpu_info,
            processes,
            disk_info,
            network_info,
            psi_data,
            connections_data,
            treemap_data,
            sensor_health_data,
            disk_io_data,
            disk_entropy_data,
            file_analyzer_data,
        }
    }
}

/// Ring buffer for history (matches ttop's `ring_buffer.rs`)
pub struct RingBuffer<T> {
    data: Vec<T>,
    capacity: usize,
}

impl<T: Clone> RingBuffer<T> {
    pub fn new(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            capacity,
        }
    }

    pub fn push(&mut self, value: T) {
        if self.data.len() >= self.capacity {
            self.data.remove(0);
        }
        self.data.push(value);
    }

    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    pub fn last(&self) -> Option<&T> {
        self.data.last()
    }
}

/// Process sort column (matches ttop's state.rs)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessSortColumn {
    Pid,
    User,
    Cpu,
    Mem,
    Command,
}

impl ProcessSortColumn {
    /// Number of columns for navigation bounds
    pub const COUNT: usize = 5;

    pub fn next(self) -> Self {
        match self {
            Self::Pid => Self::User,
            Self::User => Self::Cpu,
            Self::Cpu => Self::Mem,
            Self::Mem => Self::Command,
            Self::Command => Self::Pid,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            Self::Pid => Self::Command,
            Self::User => Self::Pid,
            Self::Cpu => Self::User,
            Self::Mem => Self::Cpu,
            Self::Command => Self::Mem,
        }
    }

    /// Convert column index to enum variant
    pub fn from_index(idx: usize) -> Self {
        match idx % Self::COUNT {
            0 => Self::Pid,
            1 => Self::User,
            2 => Self::Cpu,
            3 => Self::Mem,
            _ => Self::Command,
        }
    }

    /// Convert enum variant to column index
    pub fn to_index(self) -> usize {
        match self {
            Self::Pid => 0,
            Self::User => 1,
            Self::Cpu => 2,
            Self::Mem => 3,
            Self::Command => 4,
        }
    }

    /// Get column header with optional sort indicator
    pub fn header(self, is_sorted: bool, descending: bool) -> String {
        let base = match self {
            Self::Pid => "PID",
            Self::User => "USER",
            Self::Cpu => "CPU%",
            Self::Mem => "MEM%",
            Self::Command => "COMMAND",
        };
        if is_sorted {
            format!("{}{}", base, if descending { "â–¼" } else { "â–²" })
        } else {
            base.to_string()
        }
    }
}

/// Panel visibility (matches ttop's app.rs - all 14 panels)
#[derive(Debug, Clone, Copy)]
#[allow(clippy::struct_excessive_bools)]
pub struct PanelVisibility {
    // Core panels (P0)
    pub cpu: bool,
    pub memory: bool,
    pub disk: bool,
    pub network: bool,
    pub process: bool,
    // Hardware panels (P1)
    pub gpu: bool,
    pub sensors: bool,
    pub psi: bool,
    pub connections: bool,
    // Optional panels (P2)
    pub battery: bool,
    pub sensors_compact: bool,
    pub system: bool,
    // Advanced panels (P3)
    pub treemap: bool,
    pub files: bool,
}

impl Default for PanelVisibility {
    fn default() -> Self {
        Self {
            // Core panels - always visible by default
            cpu: true,
            memory: true,
            disk: true,
            network: true,
            process: true,
            // Hardware panels - hidden by default, auto-shown via update_visibility()
            gpu: false,
            sensors: false,
            psi: false,
            connections: false,
            // Optional panels - hidden by default, auto-shown via update_visibility()
            battery: false,
            sensors_compact: false,
            system: false,
            // Advanced panels - hidden by default
            treemap: false,
            files: false,
        }
    }
}

#[allow(clippy::struct_excessive_bools)]
pub struct App {
    // System collectors
    pub system: System,
    pub disks: Disks,
    pub networks: Networks,
    /// User lookup table for resolving UID to username
    pub users: Users,

    // Analyzers (detailed metrics from /proc, /sys)
    pub analyzers: AnalyzerRegistry,

    // History buffers (normalized 0-1)
    pub cpu_history: RingBuffer<f64>,
    pub mem_history: RingBuffer<f64>,
    pub net_rx_history: RingBuffer<f64>,
    pub net_tx_history: RingBuffer<f64>,
    /// Per-interface network history (bytes/s per interface)
    pub net_iface_history: std::collections::HashMap<String, (RingBuffer<f64>, RingBuffer<f64>)>,
    /// Selected network interface index for Tab cycling (PMAT-GAP-031 - ttop parity)
    pub selected_interface_index: usize,
    /// GPU utilization history (0-100%)
    pub gpu_history: RingBuffer<f64>,
    /// VRAM usage history (0-100%)
    pub vram_history: RingBuffer<f64>,
    /// Cached GPU info (updated during `update()`)
    pub gpu_info: Option<GpuInfo>,

    // Per-core CPU data
    pub per_core_percent: Vec<f64>,
    /// Per-core frequency in MHz (SPEC-024 async update requirement)
    pub per_core_freq: Vec<u64>,
    /// Per-core temperature in °C (SPEC-024 async update requirement)
    pub per_core_temp: Vec<f32>,

    // Memory values
    pub mem_total: u64,
    pub mem_used: u64,
    pub mem_available: u64,
    pub mem_cached: u64,
    pub swap_total: u64,
    pub swap_used: u64,

    // UI state
    pub panels: PanelVisibility,
    pub process_selected: usize,
    pub process_scroll_offset: usize,
    pub sort_column: ProcessSortColumn,
    pub sort_descending: bool,
    pub filter: String,
    pub show_filter_input: bool,
    pub show_help: bool,
    pub running: bool,

    // Signal handling (SPEC-024 Appendix G.6 P0 - ttop parity)
    /// Pending signal confirmation: (pid, process_name, signal_type)
    pub pending_signal: Option<(u32, String, SignalType)>,
    /// Last signal result: (success, message, timestamp) - auto-clears after 3s (PMAT-GAP-033)
    pub signal_result: Option<(bool, String, std::time::Instant)>,

    // Panel navigation and explode (SPEC-024 v5.0 Features D, E)
    /// Currently focused panel (receives keyboard input)
    pub focused_panel: Option<PanelType>,
    /// Exploded (fullscreen) panel, if any
    pub exploded_panel: Option<PanelType>,
    /// Selected column index for DataFrame navigation (0-based, left-to-right)
    pub selected_column: usize,
    /// Files panel view mode (PMAT-GAP-034 - ttop parity)
    pub files_view_mode: FilesViewMode,
    /// Last focused panel before collapse (PMAT-GAP-035 - ttop parity)
    /// Used to restore focus when panel is shown again
    pub collapse_memory: Option<PanelType>,

    // Configuration (SPEC-024 v5.0 Feature A)
    pub config: PtopConfig,

    // Frame timing
    pub frame_id: u64,
    pub avg_frame_time_us: u64,
    pub show_fps: bool,

    // Deterministic mode for pixel-perfect testing
    pub deterministic: bool,
    /// Fixed uptime in seconds (used in deterministic mode)
    pub fixed_uptime: u64,

    // Cached system info (O(1) render - no I/O in render path)
    /// Cached load average (updated in collect_metrics)
    pub load_avg: sysinfo::LoadAvg,
    /// Cached hostname (read once at startup)
    pub hostname: String,
    /// Cached kernel version (read once at startup)
    pub kernel_version: String,
    /// Cached container detection (read once at startup)
    pub in_container: bool,

    // Display rules (SPEC-024 Appendix F)
    /// System capabilities (detected at startup)
    pub system_capabilities: crate::widgets::SystemCapabilities,

    // Snapshot data from background collector (CB-INPUT-006)
    /// Process list from last snapshot
    pub snapshot_processes: Vec<ProcessInfo>,
    /// Disk info from last snapshot
    pub snapshot_disks: Vec<DiskInfo>,
    /// Network info from last snapshot
    pub snapshot_networks: Vec<NetworkInfo>,
    /// PSI data from last snapshot
    pub snapshot_psi: Option<PsiData>,
    /// Connections data from last snapshot
    pub snapshot_connections: Option<ConnectionsData>,
    /// Treemap data from last snapshot
    pub snapshot_treemap: Option<TreemapData>,
    /// Sensor health data from last snapshot
    pub snapshot_sensor_health: Option<SensorHealthData>,
    /// Disk I/O data from last snapshot
    pub snapshot_disk_io: Option<DiskIoData>,
    /// Disk entropy data from last snapshot
    pub snapshot_disk_entropy: Option<DiskEntropyData>,
    /// File analyzer data from last snapshot
    pub snapshot_file_analyzer: Option<FileAnalyzerData>,
}

impl App {
    /// Create new App with collectors initialized
    ///
    /// # Arguments
    /// * `deterministic` - If true, uses fixed mock data for pixel-perfect testing
    /// Create a new App with default configuration
    pub fn new(deterministic: bool) -> Self {
        Self::with_config(deterministic, PtopConfig::load())
    }

    /// Create a new App with a custom configuration
    pub fn with_config(deterministic: bool, config: PtopConfig) -> Self {
        Self::with_config_options(deterministic, config, false)
    }

    /// Create a new App with lightweight initialization (faster startup for headless mode)
    pub fn with_config_lightweight(deterministic: bool, config: PtopConfig) -> Self {
        Self::with_config_options(deterministic, config, true)
    }

    /// Internal constructor with options
    fn with_config_options(deterministic: bool, config: PtopConfig, lightweight: bool) -> Self {
        let mut system = System::new();

        // Initial refresh (need 2 samples for CPU delta)
        // Use 50ms instead of 100ms for faster startup while still getting valid CPU readings
        system.refresh_cpu_specifics(CpuRefreshKind::everything());
        std::thread::sleep(Duration::from_millis(50));
        system.refresh_cpu_specifics(CpuRefreshKind::everything());
        system.refresh_memory_specifics(MemoryRefreshKind::everything());

        // Skip heavy process refresh in lightweight mode (for headless/render-once)
        // Process CPU% also needs 2 samples for delta calculation (same as core CPU%)
        if !lightweight {
            system.refresh_processes_specifics(
                ProcessesToUpdate::All,
                true,
                ProcessRefreshKind::everything()
                    .with_cpu()
                    .with_memory()
                    .with_user(sysinfo::UpdateKind::OnlyIfNotSet),
            );
            // Second refresh after delay to get valid CPU percentages
            std::thread::sleep(Duration::from_millis(50));
            system.refresh_processes_specifics(
                ProcessesToUpdate::All,
                true,
                ProcessRefreshKind::nothing().with_cpu(),
            );
        }

        let disks = Disks::new_with_refreshed_list();
        let networks = Networks::new_with_refreshed_list();

        // ttop deterministic mode uses 48 cores with all zeros
        let core_count = if deterministic {
            48
        } else {
            system.cpus().len()
        };

        // Initialize analyzers and detect available features
        let analyzers = AnalyzerRegistry::new();

        // Auto-detect panel visibility based on available analyzers
        // SPEC-024: Match ttop layout - prefer Sensors over PSI on desktop
        let mut panels = PanelVisibility::default();

        // Only show sensors panel if there are actual sensor readings
        // Sensors takes priority over PSI in ttop layout
        let has_sensors = analyzers
            .sensor_health
            .as_ref()
            .is_some_and(|sh| !sh.data().sensors.is_empty());
        if has_sensors {
            panels.sensors = true;
            // Don't show PSI if sensors available (ttop style)
        } else if analyzers.psi.is_some() {
            // Fallback: show PSI only if no sensors
            panels.psi = true;
        }

        if analyzers.gpu_procs.is_some() {
            panels.gpu = true;
        }
        if analyzers.connections.is_some() {
            panels.connections = true;
        }
        if analyzers.treemap.is_some() {
            panels.files = true;
        }

        // In deterministic mode, match ttop's panel layout exactly
        if deterministic {
            panels = PanelVisibility {
                cpu: true,
                memory: true,
                disk: true,
                network: true,
                process: true,
                gpu: true,
                sensors: true,
                psi: false, // ttop shows Containers, not PSI
                connections: true,
                battery: false,
                sensors_compact: false,
                system: false,
                treemap: false,
                files: true,
            };
        }

        let users = Users::new_with_refreshed_list();

        let mut app = Self {
            system,
            disks,
            networks,
            users,
            analyzers,
            cpu_history: RingBuffer::new(60),
            mem_history: RingBuffer::new(60),
            net_rx_history: RingBuffer::new(60),
            net_tx_history: RingBuffer::new(60),
            net_iface_history: std::collections::HashMap::new(),
            selected_interface_index: 0, // PMAT-GAP-031: default to first interface
            gpu_history: RingBuffer::new(60),
            vram_history: RingBuffer::new(60),
            gpu_info: None,
            per_core_percent: vec![0.0; core_count],
            per_core_freq: vec![0; core_count], // SPEC-024 async update
            // Initialize temperatures immediately for non-deterministic mode
            per_core_temp: if deterministic {
                vec![0.0; core_count]
            } else {
                read_core_temperatures(core_count)
            },
            mem_total: 0,
            mem_used: 0,
            mem_available: 0,
            mem_cached: 0,
            swap_total: 0,
            swap_used: 0,
            panels,
            process_selected: 0,
            process_scroll_offset: 0,
            sort_column: ProcessSortColumn::Cpu,
            sort_descending: true,
            filter: String::new(),
            show_filter_input: false,
            show_help: false,
            running: true,
            // Signal handling (SPEC-024 Appendix G.6 P0)
            pending_signal: None,
            signal_result: None,
            // Panel navigation (SPEC-024 v5.0 Feature D)
            focused_panel: Some(PanelType::Cpu), // Start with CPU focused
            exploded_panel: None,
            selected_column: 0, // Start with first column (PID)
            files_view_mode: FilesViewMode::default(), // PMAT-GAP-034: size view default
            collapse_memory: None, // PMAT-GAP-035: no collapsed focused panel
            config,
            frame_id: 0,
            avg_frame_time_us: 0,
            show_fps: false,
            deterministic,
            // ttop deterministic mode: 0 uptime
            fixed_uptime: 0,
            // Cached system info (read once, O(1) render)
            // Initialize load_avg immediately for non-deterministic mode
            load_avg: if deterministic {
                sysinfo::LoadAvg {
                    one: 0.0,
                    five: 0.0,
                    fifteen: 0.0,
                }
            } else {
                System::load_average()
            },
            hostname: read_hostname(),
            kernel_version: read_kernel_version(),
            in_container: detect_container(),
            // Display rules (SPEC-024 Appendix F)
            system_capabilities: crate::widgets::SystemCapabilities::detect(),
            // Snapshot data (CB-INPUT-006)
            snapshot_processes: Vec::new(),
            snapshot_disks: Vec::new(),
            snapshot_networks: Vec::new(),
            snapshot_psi: None,
            snapshot_connections: None,
            snapshot_treemap: None,
            snapshot_sensor_health: None,
            snapshot_disk_io: None,
            snapshot_disk_entropy: None,
            snapshot_file_analyzer: None,
        };

        // In deterministic mode, populate with fixed data
        if deterministic {
            app.init_deterministic_data();
        }

        // Detect GPU at startup — avoids "No GPU" flash on first frames
        // while background collector is still initializing
        app.gpu_info = read_gpu_info();

        app
    }

    /// Initialize fixed data for deterministic mode
    /// Matches ttop's deterministic mode exactly: all zeros
    fn init_deterministic_data(&mut self) {
        // ttop deterministic: 48 cores all at 0%
        self.per_core_percent = vec![0.0; 48];

        // ttop deterministic: all memory values are 0
        self.mem_total = 0;
        self.mem_used = 0;
        self.mem_available = 0;
        self.mem_cached = 0;
        self.swap_total = 0;
        self.swap_used = 0;

        // ttop deterministic: fixed uptime (5 days, 3 hours, 47 minutes)
        self.fixed_uptime = 5 * 86400 + 3 * 3600 + 47 * 60;

        // ttop deterministic: empty history (all zeros)
        for _ in 0..60 {
            self.cpu_history.push(0.0);
            self.mem_history.push(0.0);
            self.net_rx_history.push(0.0);
            self.net_tx_history.push(0.0);
        }
    }

    /// Get PSI data if available
    pub fn psi_data(&self) -> Option<&PsiData> {
        // Use snapshot data for CB-INPUT-006 async pattern consistency
        self.snapshot_psi.as_ref()
    }

    /// Collect metrics from all sources
    pub fn collect_metrics(&mut self) {
        self.frame_id += 1;
        // Provability: frame_id is monotonically increasing
        debug_assert!(
            self.frame_id > 0,
            "frame_id must be positive after increment"
        );

        // Check for config hot reload (SPEC-024 v5.2.0 Feature A)
        // Only check every 10 frames to reduce filesystem overhead
        if self.frame_id % 10 == 0 {
            if let Some(new_config) = self.config.check_reload() {
                eprintln!("[ptop] config reloaded");
                self.config = new_config;
            }
        }

        // In deterministic mode, skip real data collection
        if self.deterministic {
            return;
        }

        // Update cached load average (O(1) render - no I/O in render path)
        self.load_avg = System::load_average();

        // CPU
        self.system
            .refresh_cpu_specifics(CpuRefreshKind::everything());

        let cpu_total: f32 = self
            .system
            .cpus()
            .iter()
            .map(sysinfo::Cpu::cpu_usage)
            .sum::<f32>()
            / self.system.cpus().len().max(1) as f32;
        self.cpu_history.push(cpu_total as f64 / 100.0);

        // Per-core
        self.per_core_percent = self
            .system
            .cpus()
            .iter()
            .map(|c| c.cpu_usage() as f64)
            .collect();
        // Provability: per_core_percent length matches CPU count
        debug_assert_eq!(
            self.per_core_percent.len(),
            self.system.cpus().len(),
            "per_core_percent must have one entry per CPU"
        );

        // SPEC-024: Per-core frequency and temperature for render-once mode
        // (async mode uses MetricsSnapshot, but sync mode needs direct update)
        self.per_core_freq = self
            .system
            .cpus()
            .iter()
            .map(sysinfo::Cpu::frequency)
            .collect();
        self.per_core_temp = read_core_temperatures(self.system.cpus().len());

        // Memory
        self.system
            .refresh_memory_specifics(MemoryRefreshKind::everything());

        self.mem_total = self.system.total_memory();
        self.mem_used = self.system.used_memory();
        self.mem_available = self.system.available_memory();
        // Read cached memory directly from /proc/meminfo (sysinfo doesn't expose this)
        self.mem_cached = read_cached_memory();
        self.swap_total = self.system.total_swap();
        self.swap_used = self.system.used_swap();

        if self.mem_total > 0 {
            self.mem_history
                .push(self.mem_used as f64 / self.mem_total as f64);
        }

        // Processes - O(1) OPTIMIZATION: Skip refresh if we already have process data
        // Full scan only on frame 0 or every 60 frames (~60 seconds at 1fps)
        // We already get initial process data in with_config(), so frame 0 can skip too
        // IMPORTANT: First few frames need full refresh to calculate CPU delta (sysinfo requirement)
        let process_count = self.system.processes().len();
        let needs_initial_data = process_count == 0;
        let needs_periodic_refresh = self.frame_id > 0 && self.frame_id % 60 == 0;
        let needs_delta_calculation = self.frame_id <= 3; // First 3 frames need full refresh for CPU %

        if needs_initial_data || needs_periodic_refresh || needs_delta_calculation {
            // Full refresh to discover new processes
            self.system.refresh_processes_specifics(
                ProcessesToUpdate::All,
                true,
                ProcessRefreshKind::nothing()
                    .with_cpu()
                    .with_memory()
                    .with_user(sysinfo::UpdateKind::OnlyIfNotSet),
            );
        } else if self.frame_id > 0 {
            // Incremental: only refresh top 50 processes by CPU (O(1) cached view)
            // Pre-collect PIDs to avoid iterator invalidation
            let top_pids: Vec<_> = self
                .system
                .processes()
                .iter()
                .filter(|(_, p)| p.cpu_usage() > 0.1)
                .take(50)
                .map(|(pid, _)| *pid)
                .collect();

            if !top_pids.is_empty() {
                self.system.refresh_processes_specifics(
                    ProcessesToUpdate::Some(&top_pids),
                    true,
                    ProcessRefreshKind::nothing()
                        .with_cpu()
                        .with_memory()
                        .with_user(sysinfo::UpdateKind::OnlyIfNotSet),
                );
            }
        }
        // frame_id == 0: use cached data from with_config() initialization

        // Disk
        self.disks.refresh(true);

        // Network
        self.networks.refresh(true);

        let (rx, tx) = self
            .networks
            .iter()
            .fold((0u64, 0u64), |acc, (_name, data)| {
                (acc.0 + data.received(), acc.1 + data.transmitted())
            });
        // Normalize (assume max 1GB/s)
        self.net_rx_history
            .push((rx as f64 / 1_000_000_000.0).min(1.0));
        self.net_tx_history
            .push((tx as f64 / 1_000_000_000.0).min(1.0));

        // GPU (SPEC-024 D012: track real GPU history)
        // Skip in deterministic mode (nvidia-smi is non-deterministic)
        if !self.deterministic {
            self.gpu_info = read_gpu_info();
            if let Some(ref gpu) = self.gpu_info {
                // Push utilization (0-100%)
                self.gpu_history.push(gpu.utilization.unwrap_or(0) as f64);
                // Push VRAM percentage (0-100%)
                let vram_pct = match (gpu.vram_used, gpu.vram_total) {
                    (Some(used), Some(total)) if total > 0 => (used as f64 / total as f64) * 100.0,
                    _ => 0.0,
                };
                self.vram_history.push(vram_pct);
            }
        }

        // Collect analyzer data (PSI, etc.)
        self.analyzers.collect_all();

        // Copy analyzer data to snapshot fields for render access (sync mode parity with async mode)
        // This ensures render code can use the same snapshot_* fields in both modes.
        self.snapshot_psi = self.analyzers.psi.as_ref().map(|p| p.data().clone());
        self.snapshot_connections = self
            .analyzers
            .connections
            .as_ref()
            .map(|c| c.data().clone());
        self.snapshot_treemap = self.analyzers.treemap.as_ref().map(|t| t.data().clone());
        self.snapshot_sensor_health = self
            .analyzers
            .sensor_health
            .as_ref()
            .map(|s| s.data().clone());
        self.snapshot_disk_io = self.analyzers.disk_io.as_ref().map(|d| d.data().clone());
        self.snapshot_disk_entropy = self
            .analyzers
            .disk_entropy
            .as_ref()
            .map(|d| d.data().clone());
        self.snapshot_file_analyzer = self
            .analyzers
            .file_analyzer
            .as_ref()
            .map(|f| f.data().clone());
    }

    /// Update frame timing stats
    pub fn update_frame_stats(&mut self, frame_times: &[Duration]) {
        if frame_times.is_empty() {
            return;
        }
        let total: u128 = frame_times.iter().map(std::time::Duration::as_micros).sum();
        self.avg_frame_time_us = (total / frame_times.len() as u128) as u64;
    }

    /// Apply a metrics snapshot from the background collector.
    /// This is O(1) - just copies/swaps data, no I/O.
    pub fn apply_snapshot(&mut self, snapshot: MetricsSnapshot) {
        self.frame_id += 1;

        // Update CPU data (SPEC-024 async update requirement)
        self.per_core_percent = snapshot.per_core_percent;
        self.per_core_freq = snapshot.per_core_freq;
        self.per_core_temp = snapshot.per_core_temp;
        self.load_avg = snapshot.load_avg;
        self.cpu_history.push(snapshot.cpu_avg);

        // Update memory data
        self.mem_total = snapshot.mem_total;
        self.mem_used = snapshot.mem_used;
        self.mem_available = snapshot.mem_available;
        self.mem_cached = snapshot.mem_cached;
        self.swap_total = snapshot.swap_total;
        self.swap_used = snapshot.swap_used;
        if self.mem_total > 0 {
            self.mem_history
                .push(self.mem_used as f64 / self.mem_total as f64);
        }

        // Update network history
        // Normalize (assume max 1GB/s)
        self.net_rx_history
            .push((snapshot.net_rx as f64 / 1_000_000_000.0).min(1.0));
        self.net_tx_history
            .push((snapshot.net_tx as f64 / 1_000_000_000.0).min(1.0));

        // Update GPU data
        self.gpu_info = snapshot.gpu_info.clone();
        if let Some(ref gpu) = snapshot.gpu_info {
            self.gpu_history.push(gpu.utilization.unwrap_or(0) as f64);
            let vram_pct = match (gpu.vram_used, gpu.vram_total) {
                (Some(used), Some(total)) if total > 0 => (used as f64 / total as f64) * 100.0,
                _ => 0.0,
            };
            self.vram_history.push(vram_pct);
        }

        // Store snapshot data for rendering (processes, disks, networks)
        self.snapshot_processes = snapshot.processes;
        self.snapshot_disks = snapshot.disk_info;

        // Update per-interface history before storing snapshot
        for net in &snapshot.network_info {
            let entry = self
                .net_iface_history
                .entry(net.name.clone())
                .or_insert_with(|| (RingBuffer::new(60), RingBuffer::new(60)));
            entry.0.push(net.received as f64);
            entry.1.push(net.transmitted as f64);
        }
        self.snapshot_networks = snapshot.network_info;
        self.snapshot_psi = snapshot.psi_data;
        self.snapshot_connections = snapshot.connections_data;
        self.snapshot_treemap = snapshot.treemap_data;
        self.snapshot_sensor_health = snapshot.sensor_health_data;
        self.snapshot_disk_io = snapshot.disk_io_data;
        self.snapshot_disk_entropy = snapshot.disk_entropy_data;
        self.snapshot_file_analyzer = snapshot.file_analyzer_data;
    }

    /// Build data availability context for display rules evaluation
    ///
    /// SPEC-024 Appendix F: Declarative display rules require knowing
    /// what data is available to determine panel visibility.
    pub fn data_availability(&self) -> crate::widgets::DataAvailability {
        crate::widgets::DataAvailability {
            psi_available: self.snapshot_psi.as_ref().is_some_and(|psi| {
                psi.available
                    && (psi.cpu.some.avg10 > 0.01
                        || psi.io.some.avg10 > 0.01
                        || psi.memory.some.avg10 > 0.01)
            }),
            sensors_available: self.snapshot_sensor_health.is_some(),
            sensor_count: self
                .snapshot_sensor_health
                .as_ref()
                .map_or(0, |s| s.sensors.len()),
            gpu_available: self.gpu_info.is_some(),
            battery_available: self
                .analyzers
                .battery_data()
                .is_some_and(|b| !b.batteries.is_empty()),
            treemap_ready: self
                .snapshot_treemap
                .as_ref()
                .is_some_and(|t| !t.top_items.is_empty()),
            connections_available: self.snapshot_connections.is_some(),
            connection_count: self
                .snapshot_connections
                .as_ref()
                .map_or(0, |c| c.connections.len()),
        }
    }

    /// Evaluate display rules for a panel
    ///
    /// SPEC-024 Appendix F: Returns DisplayAction based on system capabilities
    /// and current data availability.
    pub fn evaluate_panel_display(&self, panel: PanelType) -> crate::widgets::DisplayAction {
        use crate::widgets::{
            BatteryDisplayRules, DisplayContext, DisplayRules, DisplayTerminalSize,
            GpuDisplayRules, PsiDisplayRules, SensorsDisplayRules,
        };

        let ctx = DisplayContext {
            system: &self.system_capabilities,
            terminal: DisplayTerminalSize {
                width: 0,
                height: 0,
            }, // Terminal size set by UI
            data: self.data_availability(),
        };

        match panel {
            PanelType::Psi => PsiDisplayRules.evaluate(&ctx),
            PanelType::Sensors => SensorsDisplayRules.evaluate(&ctx),
            PanelType::Gpu => GpuDisplayRules.evaluate(&ctx),
            PanelType::Battery => BatteryDisplayRules.evaluate(&ctx),
            _ => crate::widgets::DisplayAction::Show,
        }
    }

    /// Handle keyboard input. Returns true if app should quit.
    pub fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        // Dispatch to mode-specific handlers
        if self.show_help {
            return self.handle_help_mode_key(code, modifiers);
        }
        if self.pending_signal.is_some() {
            return self.handle_signal_confirmation_key(code, modifiers);
        }
        if self.exploded_panel.is_some() {
            return self.handle_exploded_mode_key(code, modifiers);
        }
        if self.show_filter_input {
            return self.handle_filter_input_key(code);
        }
        self.handle_normal_mode_key(code, modifiers)
    }

    /// Handle keys in help overlay mode. Returns true if app should quit.
    fn handle_help_mode_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        match code {
            KeyCode::Esc | KeyCode::Char('?' | 'h') | KeyCode::F(1) => {
                self.show_help = false;
            }
            KeyCode::Char('q') => return true,
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => return true,
            _ => {} // Swallow all other inputs
        }
        false
    }

    /// Handle keys in signal confirmation mode. Returns true if app should quit.
    fn handle_signal_confirmation_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        match code {
            KeyCode::Char('Y') | KeyCode::Enter => self.confirm_signal(),
            KeyCode::Char('n' | 'N') | KeyCode::Esc => self.cancel_signal(),
            KeyCode::Char('q') => return true,
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => return true,
            KeyCode::Char('x') => self.request_signal(SignalType::Term),
            KeyCode::Char('K') => self.request_signal(SignalType::Kill),
            KeyCode::Char('H') => self.request_signal(SignalType::Hup),
            KeyCode::Char('i') => self.request_signal(SignalType::Int),
            KeyCode::Char('p') => self.request_signal(SignalType::Stop),
            _ => {} // Swallow other inputs
        }
        false
    }

    /// Handle keys in exploded mode. Returns true if app should quit.
    fn handle_exploded_mode_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        match code {
            KeyCode::Esc | KeyCode::Char('z') => self.exploded_panel = None,
            KeyCode::Char('q') => return true,
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => return true,
            KeyCode::Left | KeyCode::Char('h') => self.navigate_column_left(),
            KeyCode::Right | KeyCode::Char('l') => self.navigate_column_right(),
            KeyCode::Enter | KeyCode::Char(' ') => self.sort_by_selected_column(),
            KeyCode::Up | KeyCode::Char('k') => self.navigate_process(-1),
            KeyCode::Down | KeyCode::Char('j') => self.navigate_process(1),
            KeyCode::PageUp => self.navigate_process(-10),
            KeyCode::PageDown => self.navigate_process(10),
            KeyCode::Home | KeyCode::Char('g') => self.process_selected = 0,
            KeyCode::End | KeyCode::Char('G') => self.select_last_process(),
            KeyCode::Char('c') => self.quick_sort(ProcessSortColumn::Cpu, true),
            KeyCode::Char('m') => self.quick_sort(ProcessSortColumn::Mem, true),
            KeyCode::Char('p') => self.quick_sort(ProcessSortColumn::Pid, false),
            KeyCode::Char('n') => self.quick_sort(ProcessSortColumn::Command, false),
            KeyCode::Char('r') => self.sort_descending = !self.sort_descending,
            KeyCode::Char('/' | 'f') => self.show_filter_input = true,
            _ => {} // Swallow other inputs
        }
        false
    }

    /// Handle keys in filter input mode. Returns true if app should quit.
    fn handle_filter_input_key(&mut self, code: KeyCode) -> bool {
        match code {
            KeyCode::Esc => {
                self.show_filter_input = false;
                self.filter.clear();
            }
            KeyCode::Enter => self.show_filter_input = false,
            KeyCode::Backspace => {
                self.filter.pop();
            }
            KeyCode::Char(c) => self.filter.push(c),
            _ => {}
        }
        false
    }

    /// Handle keys in normal mode. Returns true if app should quit.
    #[allow(clippy::match_same_arms)]
    fn handle_normal_mode_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        match code {
            KeyCode::Char('q') | KeyCode::Esc => return true,
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => return true,
            KeyCode::Enter | KeyCode::Char('z') => {
                if let Some(panel) = self.focused_panel {
                    self.exploded_panel = Some(panel);
                }
            }
            KeyCode::Tab if !modifiers.contains(KeyModifiers::SHIFT) => {
                if self.focused_panel == Some(PanelType::Network) {
                    self.cycle_interface();
                } else {
                    self.navigate_panel_forward();
                }
            }
            KeyCode::BackTab => self.navigate_panel_backward(),
            KeyCode::Char('l') if !self.show_filter_input => self.navigate_panel_forward(),
            KeyCode::Char('H') => self.navigate_panel_backward(),
            KeyCode::Char('?' | 'h') | KeyCode::F(1) => {
                self.show_help = !self.show_help;
            }
            KeyCode::Char('1') => self.toggle_panel(PanelType::Cpu),
            KeyCode::Char('2') => self.toggle_panel(PanelType::Memory),
            KeyCode::Char('3') => self.toggle_panel(PanelType::Disk),
            KeyCode::Char('4') => self.toggle_panel(PanelType::Network),
            KeyCode::Char('5') => self.toggle_panel(PanelType::Process),
            KeyCode::Char('6') => self.toggle_panel(PanelType::Gpu),
            KeyCode::Char('7') => self.toggle_panel(PanelType::Sensors),
            KeyCode::Char('8') => self.toggle_panel(PanelType::Connections),
            KeyCode::Char('9') => self.toggle_panel(PanelType::Psi),
            KeyCode::Char('v') if self.focused_panel == Some(PanelType::Files) => {
                self.cycle_files_view_mode();
            }
            KeyCode::Down | KeyCode::Char('j') => self.navigate_process(1),
            KeyCode::Up | KeyCode::Char('k') => self.navigate_process(-1),
            KeyCode::PageDown => self.navigate_process(10),
            KeyCode::PageUp => self.navigate_process(-10),
            KeyCode::Home | KeyCode::Char('g') => self.process_selected = 0,
            KeyCode::End | KeyCode::Char('G') => self.select_last_process(),
            KeyCode::Char('c') => {
                self.sort_column = ProcessSortColumn::Cpu;
                self.sort_descending = true;
            }
            KeyCode::Char('m') => {
                self.sort_column = ProcessSortColumn::Mem;
                self.sort_descending = true;
            }
            KeyCode::Char('p') => {
                self.sort_column = ProcessSortColumn::Pid;
                self.sort_descending = false;
            }
            KeyCode::Char('s') => self.sort_column = self.sort_column.next(),
            KeyCode::Char('r') => self.sort_descending = !self.sort_descending,
            KeyCode::Char('/' | 'f') => self.show_filter_input = true,
            KeyCode::Delete => self.filter.clear(),
            KeyCode::Char('0') => self.panels = PanelVisibility::default(),
            KeyCode::Char('x') => self.request_signal(SignalType::Term),
            KeyCode::Char('X') => self.request_signal(SignalType::Kill),
            _ => {}
        }
        false
    }

    /// Navigate column selection left with wrap-around.
    fn navigate_column_left(&mut self) {
        if self.selected_column > 0 {
            self.selected_column -= 1;
        } else {
            self.selected_column = ProcessSortColumn::COUNT - 1;
        }
    }

    /// Navigate column selection right with wrap-around.
    fn navigate_column_right(&mut self) {
        self.selected_column = (self.selected_column + 1) % ProcessSortColumn::COUNT;
    }

    /// Sort by currently selected column.
    fn sort_by_selected_column(&mut self) {
        let new_col = ProcessSortColumn::from_index(self.selected_column);
        if self.sort_column == new_col {
            self.sort_descending = !self.sort_descending;
        } else {
            self.sort_column = new_col;
            self.sort_descending =
                matches!(new_col, ProcessSortColumn::Cpu | ProcessSortColumn::Mem);
        }
    }

    /// Quick sort by column with specified direction.
    fn quick_sort(&mut self, column: ProcessSortColumn, descending: bool) {
        self.sort_column = column;
        self.selected_column = column.to_index();
        self.sort_descending = descending;
    }

    /// Select last process in list.
    fn select_last_process(&mut self) {
        let count = self.process_count();
        if count > 0 {
            self.process_selected = count - 1;
        }
    }

    /// Navigate to next visible panel (SPEC-024 v5.0 Feature D)
    fn navigate_panel_forward(&mut self) {
        let visible = self.visible_panels();
        if visible.is_empty() {
            return;
        }

        let current_idx = self
            .focused_panel
            .and_then(|p| visible.iter().position(|&v| v == p))
            .unwrap_or(0);

        let next_idx = (current_idx + 1) % visible.len();
        self.focused_panel = Some(visible[next_idx]);
    }

    /// Navigate to previous visible panel (SPEC-024 v5.0 Feature D)
    fn navigate_panel_backward(&mut self) {
        let visible = self.visible_panels();
        if visible.is_empty() {
            return;
        }

        let current_idx = self
            .focused_panel
            .and_then(|p| visible.iter().position(|&v| v == p))
            .unwrap_or(0);

        let prev_idx = if current_idx == 0 {
            visible.len() - 1
        } else {
            current_idx - 1
        };
        self.focused_panel = Some(visible[prev_idx]);
    }

    /// Get list of currently visible panels in order
    pub fn visible_panels(&self) -> Vec<PanelType> {
        let mut visible = Vec::new();

        if self.panels.cpu {
            visible.push(PanelType::Cpu);
        }
        if self.panels.memory {
            visible.push(PanelType::Memory);
        }
        if self.panels.disk {
            visible.push(PanelType::Disk);
        }
        if self.panels.network {
            visible.push(PanelType::Network);
        }
        if self.panels.process {
            visible.push(PanelType::Process);
        }
        if self.panels.gpu {
            visible.push(PanelType::Gpu);
        }
        if self.panels.sensors {
            visible.push(PanelType::Sensors);
        }
        if self.panels.connections {
            visible.push(PanelType::Connections);
        }
        if self.panels.psi {
            visible.push(PanelType::Psi);
        }
        if self.panels.files {
            visible.push(PanelType::Files);
        }

        visible
    }

    /// Check if a panel is currently focused
    pub fn is_panel_focused(&self, panel: PanelType) -> bool {
        self.focused_panel == Some(panel)
    }

    /// Get detail level for a panel based on its current height
    /// Reference: SPEC-024 Section 17.3
    pub fn detail_level_for_panel(&self, _panel: PanelType, height: u16) -> DetailLevel {
        DetailLevel::for_height(height)
    }

    #[allow(clippy::cast_possible_wrap)]
    fn navigate_process(&mut self, delta: isize) {
        let count = self.process_count();
        if count == 0 {
            return;
        }

        let current = self.process_selected as isize;
        let new = (current + delta).clamp(0, (count - 1) as isize) as usize;
        self.process_selected = new;
    }

    /// Get filtered process count
    pub fn process_count(&self) -> usize {
        // ttop deterministic mode: 0 processes
        if self.deterministic {
            return 0;
        }
        self.system
            .processes()
            .values()
            .filter(|p| {
                if self.filter.is_empty() {
                    true
                } else {
                    let name = p.name().to_string_lossy().to_lowercase();
                    name.contains(&self.filter.to_lowercase())
                }
            })
            .count()
    }

    // ========== Signal Handling (SPEC-024 Appendix G.6 P0) ==========

    /// Get the currently selected process (pid, name) if any
    fn get_selected_process(&self) -> Option<(u32, String)> {
        let procs = self.sorted_processes();
        if self.process_selected < procs.len() {
            let p = procs[self.process_selected];
            Some((p.pid().as_u32(), p.name().to_string_lossy().to_string()))
        } else {
            None
        }
    }

    /// Request to send a signal to the selected process
    /// Opens confirmation dialog
    pub fn request_signal(&mut self, signal: SignalType) {
        if let Some((pid, name)) = self.get_selected_process() {
            self.pending_signal = Some((pid, name, signal));
        }
    }

    /// Confirm and send the pending signal
    pub fn confirm_signal(&mut self) {
        if let Some((pid, _name, signal)) = self.pending_signal.take() {
            let (success, message) = self.send_signal(pid, signal);
            self.signal_result = Some((success, message, std::time::Instant::now()));
        }
    }

    /// Cancel pending signal
    pub fn cancel_signal(&mut self) {
        self.pending_signal = None;
    }

    /// Clear old signal result after 3 seconds (PMAT-GAP-033 - ttop parity)
    pub fn clear_old_signal_result(&mut self) {
        if let Some((_, _, timestamp)) = &self.signal_result {
            if timestamp.elapsed() > std::time::Duration::from_secs(3) {
                self.signal_result = None;
            }
        }
    }

    /// Cycle to the next network interface (PMAT-GAP-031 - ttop parity)
    ///
    /// Tab key cycles through available interfaces in order.
    /// Wraps around to 0 when reaching the end.
    pub fn cycle_interface(&mut self) {
        let iface_count = self.snapshot_networks.len();
        if iface_count == 0 {
            self.selected_interface_index = 0;
            return;
        }
        self.selected_interface_index = (self.selected_interface_index + 1) % iface_count;
    }

    /// Get the name of the currently selected interface (PMAT-GAP-031)
    #[must_use]
    pub fn selected_interface_name(&self) -> Option<&str> {
        self.snapshot_networks
            .get(self.selected_interface_index)
            .map(|info| info.name.as_str())
    }

    /// Get the data for the currently selected interface (PMAT-GAP-031)
    #[must_use]
    pub fn selected_interface_data(&self) -> Option<&NetworkInfo> {
        self.snapshot_networks.get(self.selected_interface_index)
    }

    /// Cycle to the next files view mode (PMAT-GAP-034 - ttop parity)
    ///
    /// 'v' key cycles: Size -> Tree -> Flat -> Size
    pub fn cycle_files_view_mode(&mut self) {
        self.files_view_mode = self.files_view_mode.next();
    }

    /// Toggle a panel's visibility with collapse memory (PMAT-GAP-035 - ttop parity)
    ///
    /// When hiding a focused panel:
    /// 1. Store it in collapse_memory
    /// 2. Move focus to first visible panel
    ///
    /// When showing a panel that was previously focused (in collapse_memory):
    /// 1. Restore focus to that panel
    /// 2. Clear collapse_memory
    pub fn toggle_panel(&mut self, panel: PanelType) {
        let is_visible = self.is_panel_visible(panel);

        if is_visible {
            // Hiding the panel
            if self.focused_panel == Some(panel) {
                // Store in collapse_memory
                self.collapse_memory = Some(panel);
                // Move focus to first visible (excluding this one)
                self.set_panel_visible(panel, false);
                let visible = self.visible_panels();
                self.focused_panel = visible.first().copied();
            } else {
                self.set_panel_visible(panel, false);
            }
        } else {
            // Showing the panel
            self.set_panel_visible(panel, true);
            // If this panel was stored in collapse_memory, restore focus
            if self.collapse_memory == Some(panel) {
                self.focused_panel = Some(panel);
                self.collapse_memory = None;
            }
        }
    }

    /// Check if a panel is currently visible
    fn is_panel_visible(&self, panel: PanelType) -> bool {
        match panel {
            PanelType::Cpu => self.panels.cpu,
            PanelType::Memory => self.panels.memory,
            PanelType::Disk => self.panels.disk,
            PanelType::Network => self.panels.network,
            PanelType::Process => self.panels.process,
            PanelType::Gpu => self.panels.gpu,
            PanelType::Sensors => self.panels.sensors,
            PanelType::Connections => self.panels.connections,
            PanelType::Psi => self.panels.psi,
            PanelType::Battery => self.panels.battery,
            PanelType::Files => self.panels.files,
            PanelType::Containers => false, // Not implemented
        }
    }

    /// Set a panel's visibility
    fn set_panel_visible(&mut self, panel: PanelType, visible: bool) {
        match panel {
            PanelType::Cpu => self.panels.cpu = visible,
            PanelType::Memory => self.panels.memory = visible,
            PanelType::Disk => self.panels.disk = visible,
            PanelType::Network => self.panels.network = visible,
            PanelType::Process => self.panels.process = visible,
            PanelType::Gpu => self.panels.gpu = visible,
            PanelType::Sensors => self.panels.sensors = visible,
            PanelType::Connections => self.panels.connections = visible,
            PanelType::Psi => self.panels.psi = visible,
            PanelType::Battery => self.panels.battery = visible,
            PanelType::Files => self.panels.files = visible,
            PanelType::Containers => {} // Not implemented
        }
    }

    /// Send a signal to a process using the system `kill` command
    #[cfg(unix)]
    fn send_signal(&self, pid: u32, signal: SignalType) -> (bool, String) {
        use std::process::Command;

        // Use the system `kill` command for safe signal sending
        let output = Command::new("kill")
            .arg(format!("-{}", signal.number()))
            .arg(pid.to_string())
            .output();

        match output {
            Ok(result) if result.status.success() => {
                (true, format!("Sent SIG{} to PID {}", signal.name(), pid))
            }
            Ok(result) => {
                let stderr = String::from_utf8_lossy(&result.stderr);
                (
                    false,
                    format!(
                        "Failed to send SIG{} to {}: {}",
                        signal.name(),
                        pid,
                        stderr.trim()
                    ),
                )
            }
            Err(e) => (
                false,
                format!("Failed to send SIG{} to {}: {}", signal.name(), pid, e),
            ),
        }
    }

    #[cfg(not(unix))]
    fn send_signal(&self, pid: u32, signal: SignalType) -> (bool, String) {
        (
            false,
            format!(
                "Signal {} not supported on this platform (PID {})",
                signal.name(),
                pid
            ),
        )
    }

    /// Get sorted and filtered processes
    pub fn sorted_processes(&self) -> Vec<&sysinfo::Process> {
        // ttop deterministic mode: empty process list
        if self.deterministic {
            return Vec::new();
        }
        let mut procs: Vec<_> = self
            .system
            .processes()
            .values()
            .filter(|p| {
                if self.filter.is_empty() {
                    true
                } else {
                    let name = p.name().to_string_lossy().to_lowercase();
                    name.contains(&self.filter.to_lowercase())
                }
            })
            .collect();

        procs.sort_by(|a, b| {
            let cmp = match self.sort_column {
                ProcessSortColumn::Pid => a.pid().as_u32().cmp(&b.pid().as_u32()),
                ProcessSortColumn::User => {
                    let ua = a.user_id().map(|u| u.to_string()).unwrap_or_default();
                    let ub = b.user_id().map(|u| u.to_string()).unwrap_or_default();
                    ua.cmp(&ub)
                }
                ProcessSortColumn::Cpu => a
                    .cpu_usage()
                    .partial_cmp(&b.cpu_usage())
                    .unwrap_or(std::cmp::Ordering::Equal),
                ProcessSortColumn::Mem => a.memory().cmp(&b.memory()),
                ProcessSortColumn::Command => {
                    let na = a.name().to_string_lossy();
                    let nb = b.name().to_string_lossy();
                    na.cmp(&nb)
                }
            };
            if self.sort_descending {
                cmp.reverse()
            } else {
                cmp
            }
        });

        procs
    }

    /// Get Disk I/O data if available
    pub fn disk_io_data(&self) -> Option<&super::analyzers::DiskIoData> {
        // Use snapshot data for CB-INPUT-006 async pattern consistency
        self.snapshot_disk_io.as_ref()
    }

    /// Get system uptime in seconds
    pub fn uptime(&self) -> u64 {
        if self.deterministic {
            self.fixed_uptime
        } else {
            System::uptime()
        }
    }
}

// ============================================================================
// Cached System Info Helpers (read once at startup, O(1) render)
// ============================================================================

/// Read hostname from /etc/hostname (called once at startup)
fn read_hostname() -> String {
    std::fs::read_to_string("/etc/hostname")
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|_| "unknown".to_string())
}

/// Read kernel version from /proc/version (called once at startup)
fn read_kernel_version() -> String {
    std::fs::read_to_string("/proc/version")
        .map(|s| s.split_whitespace().take(3).collect::<Vec<_>>().join(" "))
        .unwrap_or_else(|_| "Linux".to_string())
}

/// Detect if running in a container (called once at startup)
fn detect_container() -> bool {
    std::path::Path::new("/.dockerenv").exists()
        || std::fs::read_to_string("/proc/1/cgroup")
            .map(|s| s.contains("docker") || s.contains("containerd"))
            .unwrap_or(false)
}