rusty-stack 0.3.1

A comprehensive ML environment installer and platform toolkit optimized for AMD GPUs with ROCm support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
//! rusty — Unified CLI for Rusty Stack.
//!
//! Provides all Rusty Stack CLI subcommands in a single binary:
//!
//! - `rusty` (no args) — Launch the TUI installer
//! - `rusty update` — Scan, plan, and apply component updates
//! - `rusty upgrade` — Upgrade the Rusty Stack binary itself
//! - `rusty bench` — Run benchmarks
//! - `rusty verify` — Verify ML Stack installation
//! - `rusty uninstall` — Uninstall the Rusty-managed ML stack (cross-shell + cross-distro)
//! - `rusty reinstall` — Force reinstall: uninstall then relaunch the installer
//!
//! # Usage
//!
//! ```text
//! rusty [COMMAND]
//!
//! Commands:
//!   update   Update Rusty Stack ML components
//!   upgrade  Upgrade Rusty Stack to the latest version
//!   bench    Run benchmarks
//!   verify   Verify ML Stack installation
//!
//! Options:
//!   -h, --help     Show help
//!   -V, --version  Show version
//! ```

use clap::{Parser, Subcommand};
use serde::Serialize;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process;

// ---------------------------------------------------------------------------
// CLI definition
// ---------------------------------------------------------------------------

const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Parser, Debug)]
#[command(
    name = "rusty-stack",
    version = VERSION,
    about = "Rusty Stack — AMD GPU ML environment manager",
    long_about = "Unified CLI for Rusty Stack. Provides component updates, binary upgrades, \
                  and benchmark execution. Run without arguments to launch the TUI installer."
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Subcommands>,
}

#[derive(Subcommand, Debug)]
enum Subcommands {
    /// Update Rusty Stack ML components.
    ///
    /// Scans installed components, resolves the manifest, builds an update plan,
    /// classifies updates (safe/guarded/blocked/candidate/experimental), and
    /// applies selected updates.
    ///
    /// Non-interactive JSON output when not TTY or with --json.
    Update {
        /// Produce plan without applying any changes.
        #[arg(long)]
        scan_only: bool,

        /// Apply only safe-classified updates.
        /// Shows plan with countdown confirmation unless --yes is also set.
        #[arg(long)]
        all_safe: bool,

        /// Include experimental components in the plan.
        #[arg(long)]
        include_experimental: bool,

        /// Skip confirmation prompts (auto-apply). Useful for scripting/CI.
        #[arg(long, short = 'y')]
        yes: bool,

        /// Force JSON output mode.
        #[arg(long)]
        json: bool,

        /// Specific components to update.
        /// Each targeted component still runs a full compatibility check.
        #[arg(value_name = "COMPONENT")]
        components: Vec<String>,
    },

    /// Upgrade Rusty Stack to the latest version.
    ///
    /// Downloads and replaces the Rusty Stack binary with the latest released
    /// version. Checks manifest version compatibility, verifies binary
    /// integrity, and supports rollback on failure.
    Upgrade {
        /// Skip interactive confirmation prompts.
        /// Output is structured JSON in this mode.
        #[arg(long, short = 'y')]
        yes: bool,

        /// Path to the binary to upgrade.
        /// Defaults to the current executable.
        #[arg(long)]
        binary_path: Option<PathBuf>,

        /// Directory for backup files.
        /// Defaults to ~/.mlstack/backups.
        #[arg(long)]
        backup_dir: Option<PathBuf>,

        /// Path to the cached remote manifest.
        /// Defaults to ~/.mlstack/cache/remote_manifest.json.
        #[arg(long)]
        cached_manifest: Option<PathBuf>,

        /// Dry run: check for available upgrades without applying.
        #[arg(long)]
        dry_run: bool,
    },

    /// Run benchmarks.
    ///
    /// Executes the specified benchmark and prints results.
    /// Use --json for machine-readable output.
    Bench {
        /// Benchmark to run.
        ///
        /// Pre-installation: gpu-capability, memory-bandwidth, tensor-core
        /// GPU Performance: gemm
        /// Component: pytorch, flash-attention, vllm, deepspeed, megatron
        /// Combined: all-pre, all
        #[arg(value_name = "BENCHMARK")]
        benchmark: Option<String>,

        /// Output results in JSON format.
        #[arg(long)]
        json: bool,

        /// List available benchmarks.
        #[arg(long)]
        list: bool,
    },

    /// Check for Rust dependency updates from crates.io.
    ///
    /// Scans Cargo.toml direct dependencies, queries crates.io for the latest
    /// stable versions, and reports which dependencies have updates available.
    /// Respects a configurable lag period to avoid freshly-published versions.
    ///
    /// Exit codes: 0 = all up to date, 1 = updates available, 2 = error.
    Deps {
        /// Set lag period in days (default: 7).
        /// Only reports updates published more than this many days ago.
        #[arg(long, default_value = "7")]
        lag: u64,

        /// Show full API responses for debugging.
        #[arg(long, short = 'v')]
        verbose: bool,

        /// Path to the crate directory containing Cargo.toml.
        /// Defaults to the rusty-stack crate adjacent to this binary.
        #[arg(long)]
        dir: Option<PathBuf>,

        /// Output results in JSON format.
        #[arg(long)]
        json: bool,
    },

    /// Verify ML Stack installation.
    ///
    /// Checks component installation status using native Rust detection
    /// (no shell subprocesses). Supports three modes:
    ///
    /// - --full: Core component verification (equivalent to verify_installation.sh)
    /// - --enhanced: All-component verification (equivalent to enhanced_verify_installation.sh)
    /// - --build: Verify and identify components needing rebuild (equivalent to verify_and_build.sh)
    Verify {
        /// Run full verification (core components: ROCm, PyTorch, Triton, MPI4Py, DeepSpeed, ML Stack Core).
        #[arg(long)]
        full: bool,

        /// Run enhanced verification (all components including ROCm tools, Python imports, environment).
        #[arg(long)]
        enhanced: bool,

        /// Run verify-and-build mode (core + build-critical components; identifies rebuild targets).
        #[arg(long)]
        build: bool,

        /// Output results in JSON format.
        #[arg(long)]
        json: bool,
    },

    /// Uninstall the Rusty-managed ML stack.
    ///
    /// Removes the Python ML packages, ROCm/amdgpu system packages (unless
    /// --keep-rocm), /opt/rocm (unless --keep-rocm), the env files Rusty wrote,
    /// the shell sourcing lines, and the installed-component registry.
    /// Cross-shell (fish/bash/zsh) and cross-distro (apt/dnf/pacman/zypper).
    Uninstall {
        /// Keep ROCm/amdgpu system packages and /opt/rocm (only remove Python +
        /// env/registry).
        #[arg(long)]
        keep_rocm: bool,

        /// Also remove ~/.mlstack/ (logs, cache, global venv).
        #[arg(long)]
        purge_dir: bool,

        /// Skip the confirmation notice.
        #[arg(long, short = 'y')]
        yes: bool,
    },

    /// Force reinstall: uninstall the stack, then relaunch the TUI installer.
    Reinstall {
        /// Keep ROCm/amdgpu system packages during the uninstall phase.
        #[arg(long)]
        keep_rocm: bool,

        /// Also remove ~/.mlstack/ during the uninstall phase.
        #[arg(long)]
        purge_dir: bool,
    },

    /// Install the ML stack.
    ///
    /// Ensures the install target env exists and launches the installer. Use
    /// `--env <name>` to isolate ALL components into `~/.mlstack/envs/<name>/`
    /// (Tenet 1: install-to-env), or `--global` for the single managed global
    /// env `~/.mlstack/global/`. The sourcing command + path are printed.
    Install {
        /// Isolate all components into ~/.mlstack/envs/<name>/ (named env).
        #[arg(long, value_name = "NAME")]
        env: Option<String>,

        /// Install into the single managed global env ~/.mlstack/global/ (default).
        #[arg(long)]
        global: bool,
    },
}

// ===========================================================================
// Update subcommand implementation
// ===========================================================================

// ===========================================================================
// Shared sudo-credential helpers (install + uninstall/reinstall)
// ===========================================================================

/// Sudo credential resolution shared by the install and uninstall/reinstall
/// paths. `sudo -n` fails whenever a password is required; these helpers read a
/// password from a TTY (no echo) so privileged steps can run via an askpass
/// helper unattended.
mod sudo_creds {
    use std::io::{IsTerminal, Write};

    /// Read a password from TTY without echo. Returns `None` if not a TTY or
    /// reading fails. Uses raw stdin reads (avoids `read_line` buffering).
    pub fn read_password_from_tty() -> Option<String> {
        use std::io::Read;
        if !std::io::stdin().is_terminal() {
            // Not a TTY — do not consume piped stdin as sudo password.
            return None;
        }
        // Disable echo + canonical mode via termios, read raw bytes to newline.
        #[cfg(unix)]
        {
            let mut termios: libc::termios = unsafe { std::mem::zeroed() };
            if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut termios) } != 0 {
                return None;
            }
            let original = termios;
            termios.c_lflag &= !(libc::ECHO | libc::ICANON);
            if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &termios) } != 0 {
                return None;
            }
            let mut password = Vec::new();
            let mut byte = [0u8; 1];
            loop {
                match std::io::stdin().read(&mut byte) {
                    Ok(0) => break, // EOF
                    Ok(_) if byte[0] == b'\n' => break,
                    Ok(_) if byte[0] == b'\r' => break,
                    Ok(_) => password.push(byte[0]),
                    Err(_) => break,
                }
            }
            unsafe {
                libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &original);
            };
            eprintln!(); // newline after password input
            String::from_utf8(password).ok()
        }
        #[cfg(not(unix))]
        {
            None
        }
    }

    /// True when sudo can run non-interactively for the current user (cached
    /// credential or NOPASSWD policy).
    pub fn can_sudo_non_interactive() -> bool {
        std::process::Command::new("sudo")
            .arg("-n")
            .arg("true")
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    /// Resolve a sudo password for the uninstall/reinstall privileged steps.
    ///
    /// Precedence: already-root ⇒ `None` (no sudo needed);
    /// `MLSTACK_SUDO_PASSWORD` env; non-interactive sudo already works ⇒
    /// `None`; otherwise prompt on the TTY.
    pub fn resolve_for_uninstall() -> Option<String> {
        #[cfg(unix)]
        if unsafe { libc::geteuid() } == 0 {
            return None;
        }
        if let Ok(pw) = std::env::var("MLSTACK_SUDO_PASSWORD") {
            if !pw.is_empty() {
                return Some(pw);
            }
        }
        if can_sudo_non_interactive() {
            return None;
        }
        if std::io::stdin().is_terminal() {
            eprint!("    sudo password for uninstall: ");
            let _ = std::io::stderr().flush();
            read_password_from_tty()
        } else {
            None
        }
    }
}

mod update_impl {
    use super::*;

    pub fn run(
        scan_only: bool,
        all_safe: bool,
        include_experimental: bool,
        yes: bool,
        json: bool,
        components: Vec<String>,
    ) {
        // Determine output mode: JSON if explicitly requested or not a TTY
        let json_mode = json || !io::stdout().is_terminal();

        // Initialize logging for update operations
        let _log_guard = if json_mode {
            rusty_stack::logging::init_batch_logging("update")
        } else {
            rusty_stack::logging::init_logging("update")
        };
        tracing::info!(
            scan_only = scan_only,
            all_safe = all_safe,
            include_experimental = include_experimental,
            yes = yes,
            json_mode = json_mode,
            components = ?components,
            "Update command started"
        );

        // Build planner options from CLI args
        let options = rusty_stack::orchestrator::planner::PlannerOptions {
            scan_only,
            all_safe,
            include_experimental,
            target_components: components.clone(),
            json_output: json_mode,
        };

        // Phase 1: Scan
        let scan = run_scan();

        if json_mode {
            // JSON output mode
            match build_plan(&scan, &options) {
                Ok(plan) => {
                    let can_apply_non_interactive = yes || all_safe;
                    if scan_only || plan.summary.selected == 0 || !can_apply_non_interactive {
                        let status = if scan_only {
                            "scan_only"
                        } else if plan.summary.selected == 0 {
                            "no_updates"
                        } else {
                            "confirmation_required"
                        };
                        let output = JsonOutput {
                            scan,
                            plan: Some(plan),
                            apply: None,
                            summary: JsonSummary {
                                status: status.to_string(),
                                scan_only,
                                error: None,
                            },
                        };
                        match serde_json::to_string(&output) {
                            Ok(payload) => println!("{payload}"),
                            Err(err) => {
                                eprintln!(
                                    "{{\"status\":\"error\",\"error\":\"failed to serialize update output: {}\"}}",
                                    err.to_string().replace('"', "\\\"")
                                );
                                process::exit(1);
                            }
                        }
                    } else {
                        // Apply the plan
                        let apply_result = apply_plan(&plan);
                        let output = JsonOutput {
                            scan,
                            plan: Some(plan),
                            apply: Some(serde_json::to_value(&apply_result).unwrap_or_default()),
                            summary: JsonSummary {
                                status: if apply_result.has_failures() {
                                    "partial"
                                } else {
                                    "applied"
                                }
                                .to_string(),
                                scan_only: false,
                                error: None,
                            },
                        };
                        match serde_json::to_string(&output) {
                            Ok(payload) => println!("{payload}"),
                            Err(err) => {
                                eprintln!(
                                    "{{\"status\":\"error\",\"error\":\"failed to serialize update output: {}\"}}",
                                    err.to_string().replace('"', "\\\"")
                                );
                                process::exit(1);
                            }
                        }
                        if apply_result.has_failures() {
                            process::exit(1);
                        }
                    }
                }
                Err(error) => {
                    let output = JsonOutput {
                        scan,
                        plan: None,
                        apply: None,
                        summary: JsonSummary {
                            status: "error".to_string(),
                            scan_only,
                            error: Some(error.to_string()),
                        },
                    };
                    match serde_json::to_string(&output) {
                        Ok(payload) => println!("{payload}"),
                        Err(err) => {
                            eprintln!(
                                "{{\"status\":\"error\",\"error\":\"failed to serialize update error output: {}\"}}",
                                err.to_string().replace('"', "\\\"")
                            );
                        }
                    }
                    process::exit(1);
                }
            }
        } else {
            // Interactive/human-readable output mode
            println!("Rusty Stack Update v{VERSION}");
            println!("========================\n");

            print!("{}", format_scan_human(&scan));

            // Phase 2: Plan
            match build_plan(&scan, &options) {
                Ok(plan) => {
                    print!("{}", format_plan_output_human(&plan));

                    if scan_only {
                        println!("\n(scan-only mode: no changes will be applied)");
                    } else if plan.summary.selected == 0 {
                        println!("\nNo updates selected.");
                        tracing::info!("No updates selected");
                    } else if yes || all_safe {
                        // --all-safe or --yes: show countdown unless --yes skips it
                        if yes {
                            tracing::info!(
                                count = plan.summary.selected,
                                "Auto-applying (--yes flag)"
                            );
                            println!(
                                "\nApplying {} updates (auto-confirmed)...",
                                plan.summary.selected
                            );
                        } else {
                            // --all-safe: 10-second countdown with cancel
                            if !countdown_confirm(plan.summary.selected) {
                                tracing::info!("Update cancelled during countdown");
                                println!("\nCancelled.");
                                return;
                            }
                        }
                        let log_path = rusty_stack::logging::log_dir();
                        println!("  Logging to: {}", log_path.display());
                        println!();
                        let apply_result = apply_plan(&plan);
                        print_apply_summary(&apply_result);
                        if apply_result.has_failures() {
                            process::exit(1);
                        }
                    } else {
                        // Interactive: prompt for confirmation
                        println!("\nReady to apply {} updates.", plan.summary.selected);
                        print!("Apply now? [y/N] ");
                        let _ = io::stdout().flush();
                        let mut input = String::new();
                        if io::stdin().read_line(&mut input).is_ok() {
                            match input.trim().to_lowercase().as_str() {
                                "y" | "yes" => {
                                    let apply_result = apply_plan(&plan);
                                    print_apply_summary(&apply_result);
                                    if apply_result.has_failures() {
                                        process::exit(1);
                                    }
                                }
                                _ => {
                                    println!("Cancelled.");
                                }
                            }
                        }
                    }
                }
                Err(error) => {
                    eprintln!("Error: {error}");
                    process::exit(1);
                }
            }
        }
    }

    /// Run the scan phase: detect hardware, installed components, versions.
    fn run_scan() -> rusty_stack::orchestrator::planner::ScanOutput {
        use rusty_stack::orchestrator::planner::{InstalledComponent, ScanOutput};
        use rusty_stack::platform::registry::{
            detect_all_installed, get_version, known_components,
        };

        let installed_ids = detect_all_installed();
        let mut installed = Vec::new();

        for id in &installed_ids {
            let version = get_version(id);
            installed.push(InstalledComponent {
                id: id.clone(),
                version,
                status: "installed".to_string(),
            });
        }

        // Also include known components that are NOT installed
        for comp in known_components() {
            if !installed_ids.contains(&comp.id) {
                installed.push(InstalledComponent {
                    id: comp.id.clone(),
                    version: "not installed".to_string(),
                    status: "not-installed".to_string(),
                });
            }
        }

        // Detect ROCm info
        let (rocm_version, gpu_architecture, rocm_channel) = detect_rocm_info();

        ScanOutput {
            installed,
            manifest_source: "baseline".to_string(),
            rocm_channel,
            rocm_version,
            gpu_architecture,
        }
    }

    /// Detect ROCm version, GPU architecture, and channel.
    fn detect_rocm_info() -> (String, String, String) {
        #[cfg(unix)]
        {
            use rusty_stack::platform::linux::detect_gpu;

            let gpu_info = detect_gpu();
            let rocm_version = gpu_info.rocm_version.clone();

            let gpu_architecture = if gpu_info.architecture.is_empty() {
                "unknown".to_string()
            } else {
                gpu_info.architecture.clone()
            };

            // Determine channel from version
            let rocm_channel = if rocm_version.is_empty() {
                String::new()
            } else if rocm_version.starts_with("6.4") {
                "legacy".to_string()
            } else if rocm_version.starts_with("7.2") {
                // 7.2.0-7.2.3 -> stable; 7.2.4+ -> latest
                let patch: u32 = rocm_version
                    .split('.')
                    .nth(2)
                    .and_then(|p| p.parse().ok())
                    .unwrap_or(0);
                if patch <= 3 {
                    "stable".to_string()
                } else {
                    "latest".to_string()
                }
            } else if rocm_version.starts_with("7.1") {
                "stable".to_string()
            } else {
                "latest".to_string()
            };

            (rocm_version, gpu_architecture, rocm_channel)
        }

        #[cfg(not(unix))]
        {
            (String::new(), "unknown".to_string(), String::new())
        }
    }

    /// Build the update plan from scan results and manifest.
    fn build_plan(
        scan: &rusty_stack::orchestrator::planner::ScanOutput,
        options: &rusty_stack::orchestrator::planner::PlannerOptions,
    ) -> Result<
        rusty_stack::orchestrator::planner::PlanOutput,
        rusty_stack::orchestrator::planner::PlannerError,
    > {
        use rusty_stack::core::manifest::{self, Manifest, ManifestFetcher};
        use rusty_stack::core::types::ExecutorKind;
        use rusty_stack::orchestrator::planner::{
            CompatibilityContext, PlanOutput, PlanSummary, PlannerItemOutput, UpdatePlanner,
        };
        use std::collections::HashSet;

        struct UpdateManifestFetcher;
        impl UpdateManifestFetcher {
            fn cached_manifest_path() -> std::path::PathBuf {
                std::env::var("HOME")
                    .map(std::path::PathBuf::from)
                    .unwrap_or_else(|_| std::path::PathBuf::from("."))
                    .join(".mlstack")
                    .join("cache")
                    .join("remote_manifest.json")
            }
        }
        impl ManifestFetcher for UpdateManifestFetcher {
            fn fetch_remote(&self) -> Option<Manifest> {
                let url = std::env::var("MLSTACK_REMOTE_MANIFEST_URL").ok()?;
                let body = ureq::Agent::new_with_defaults()
                    .get(&url)
                    .header("Accept", "application/json")
                    .header("User-Agent", "rusty-stack-update")
                    .call()
                    .ok()?
                    .into_body()
                    .read_to_string()
                    .ok()?;
                serde_json::from_str::<Manifest>(&body).ok()
            }

            fn load_cached(&self) -> Option<Manifest> {
                let path = Self::cached_manifest_path();
                let json = std::fs::read_to_string(path).ok()?;
                serde_json::from_str::<Manifest>(&json).ok()
            }
        }

        // Resolve update manifest with trust-checked fallback chain:
        // fresh remote (when configured) -> cached -> bundled baseline.
        let manifest = manifest::resolve_manifest(&UpdateManifestFetcher).manifest;

        // Build compatibility context from scan results
        let mut context = CompatibilityContext::new();
        context.rocm_version = scan.rocm_version.clone();
        context.rocm_channel = scan.rocm_channel.clone();
        context.gpu_architecture = scan.gpu_architecture.clone();
        context.available_executors = HashSet::from([
            ExecutorKind::LegacyScript,
            ExecutorKind::Rust,
            ExecutorKind::ExternalPackageManager,
        ]);

        for comp in &scan.installed {
            if comp.status == "installed" {
                context.installed_components.insert(comp.id.clone());
                context
                    .installed_versions
                    .insert(comp.id.clone(), comp.version.clone());
            }
        }

        context.runtime_version = VERSION.to_string();

        // Build the plan
        let planner = UpdatePlanner::new();
        let items = planner.build_plan(&manifest, &context, options)?;

        let plan_output: Vec<PlannerItemOutput> =
            items.iter().map(PlannerItemOutput::from).collect();
        let summary = PlanSummary::from_items(&items);

        Ok(PlanOutput {
            plan: plan_output,
            summary,
        })
    }

    /// Format the scan as human-readable text.
    fn format_scan_human(scan: &rusty_stack::orchestrator::planner::ScanOutput) -> String {
        let mut output = String::new();

        output.push_str(&format!(
            "ROCm: {} ({})\n",
            scan.rocm_version, scan.rocm_channel
        ));
        output.push_str(&format!("GPU:  {}\n\n", scan.gpu_architecture));

        output.push_str("Installed components:\n");
        for comp in &scan.installed {
            if comp.status == "installed" {
                output.push_str(&format!("  {} v{}\n", comp.id, comp.version));
            }
        }

        output
    }

    /// Format the plan output as human-readable text.
    fn format_plan_output_human(plan: &rusty_stack::orchestrator::planner::PlanOutput) -> String {
        let mut output = String::new();

        output.push_str(&format!(
            "\nUpdate Plan ({} items: {} safe, {} guarded, {} candidate, {} experimental, {} blocked)\n\n",
            plan.summary.total,
            plan.summary.safe,
            plan.summary.guarded,
            plan.summary.candidate,
            plan.summary.experimental,
            plan.summary.blocked,
        ));

        for item in &plan.plan {
            let sel = if item.selected { "✓" } else { " " };
            let vis = if item.visible { "" } else { " [hidden]" };
            let version_str = if item.current_version.is_empty() {
                format!("(new) → {}", item.proposed_version)
            } else if item.current_version == item.proposed_version {
                format!("{} (reinstall)", item.current_version)
            } else {
                format!("{} → {}", item.current_version, item.proposed_version)
            };
            output.push_str(&format!(
                "  {} {:15} {}  ({}){}\n",
                sel, item.component_id, version_str, item.classification, vis,
            ));
        }

        output.push_str(&format!(
            "\nSelected: {} of {} items\n",
            plan.summary.selected, plan.summary.total
        ));

        output
    }

    /// Show a 10-second countdown confirmation before applying updates.
    ///
    /// Press Enter to apply immediately, 'n' or Ctrl+C to cancel.
    /// Returns `true` if confirmed, `false` if cancelled.
    fn countdown_confirm(count: usize) -> bool {
        use std::io::stdin;
        use std::thread;
        use std::time::{Duration, Instant};

        println!("\n  ┌───────────────────────────────────────────────────┐");
        println!(
            "  │ {} update{} will be applied in 10 seconds.        │",
            count,
            if count > 1 { "s" } else { "" }
        );
        println!("  │ Press Enter to apply now, 'n' to cancel.         │");
        println!("  └───────────────────────────────────────────────────┘");

        // Set stdin to non-blocking raw mode for the countdown
        #[cfg(unix)]
        {
            use std::io::Read;
            let mut termios: libc::termios = unsafe { std::mem::zeroed() };
            if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut termios) } == 0 {
                let original = termios;
                // Set to raw mode (no echo, no canonical, non-blocking reads)
                termios.c_lflag &= !(libc::ICANON | libc::ECHO);
                termios.c_cc[libc::VMIN] = 0;
                termios.c_cc[libc::VTIME] = 0;
                let _ = unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &termios) };

                let mut confirmed = false;
                let mut cancelled = false;

                for remaining in (1..=10).rev() {
                    eprint!("\r  ⏳ Applying in {:2}s... ", remaining);
                    let _ = std::io::stderr().flush();

                    // Poll stdin for one full second so the countdown is truly 10 seconds.
                    let tick_start = Instant::now();
                    while tick_start.elapsed() < Duration::from_secs(1) {
                        thread::sleep(Duration::from_millis(100));
                        let mut buf = [0u8; 1];
                        if let Ok(1) = stdin().read(&mut buf) {
                            match buf[0] {
                                b'\n' | b'\r' => {
                                    confirmed = true;
                                    break;
                                }
                                b'n' | b'N' | b'q' | b'Q' => {
                                    cancelled = true;
                                    break;
                                }
                                3 => {
                                    // Ctrl+C
                                    cancelled = true;
                                    break;
                                }
                                _ => {}
                            }
                        }
                    }
                    if confirmed || cancelled {
                        break;
                    }
                }

                // Restore original terminal settings
                let _ = unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &original) };

                eprint!("\r{}\r", " ".repeat(40));

                if cancelled {
                    return false;
                }
                if confirmed {
                    println!("  ✓ Confirmed.");
                    return true;
                }
                // Countdown expired — auto-confirm
                println!("  ✓ Countdown elapsed — auto-applying.");
                return true;
            }
        }

        // Fallback for non-unix: simple prompt
        print!("  Apply {} updates? [Y/n] ", count);
        let _ = std::io::stdout().flush();
        let mut input = String::new();
        if io::stdin().read_line(&mut input).is_ok() {
            let answer = input.trim().to_lowercase();
            answer != "n" && answer != "no"
        } else {
            false
        }
    }
    /// Apply the selected items using the native installer (direct function calls).
    ///
    /// Uses `DirectInstallerExecutor` which calls `installer::run_installation()`
    /// directly - no subprocess spawning.
    fn apply_plan(
        plan: &rusty_stack::orchestrator::planner::PlanOutput,
    ) -> rusty_stack::orchestrator::apply::ApplySummary {
        use rusty_stack::orchestrator::apply::{ApplyEngine, ApplyExecutor, ApplyOptions};
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        // Sudo-password helpers live in the top-level `sudo_creds` module so the
        // uninstall/reinstall paths can share them.

        /// Direct installer executor - calls Rust installer functions in-process.
        struct DirectInstallerExecutor {
            cancelled: Arc<AtomicBool>,
        }

        impl DirectInstallerExecutor {
            fn new(cancelled: Arc<AtomicBool>) -> Self {
                Self { cancelled }
            }
            fn component_for_id(id: &str) -> Option<rusty_stack::state::Component> {
                rusty_stack::state::default_components()
                    .into_iter()
                    .find(|c| c.id == id)
                    .map(|mut c| {
                        c.selected = true;
                        c
                    })
            }
        }

        impl ApplyExecutor for DirectInstallerExecutor {
            fn apply_component(
                &self,
                component_id: &str,
                proposed_version: &str,
            ) -> Result<(), String> {
                if self.cancelled.load(Ordering::Relaxed) {
                    return Err(format!("{} cancelled by user", component_id));
                }
                tracing::info!(
                    component = component_id,
                    proposed_version,
                    "Starting component installation"
                );
                let Some(component) = Self::component_for_id(component_id) else {
                    return Err(format!("Unknown component ID: {}", component_id));
                };

                // Resolve sudo password for components that need it
                #[cfg(unix)]
                let sudo_password = if component.needs_sudo {
                    if unsafe { libc::geteuid() } == 0 {
                        None
                    } else if let Ok(pw) = std::env::var("MLSTACK_SUDO_PASSWORD") {
                        if pw.is_empty() {
                            None
                        } else {
                            Some(pw)
                        }
                    } else if sudo_creds::can_sudo_non_interactive() {
                        tracing::info!(
                            component = component_id,
                            "Using non-interactive sudo path (-n)"
                        );
                        None
                    } else {
                        eprint!("    sudo password for {}: ", component.name);
                        let _ = std::io::stderr().flush();
                        let password = sudo_creds::read_password_from_tty();
                        if let Some(ref _pw) = password {
                            tracing::info!(component = component_id, "Sudo password provided");
                        } else {
                            tracing::warn!(component = component_id, "No sudo password provided");
                        }
                        password
                    }
                } else {
                    None
                };
                #[cfg(not(unix))]
                let sudo_password: Option<String> = None;

                let (tx, rx) = std::sync::mpsc::channel();
                let (_, input_rx) = std::sync::mpsc::channel();
                let scripts_dir = rusty_stack::detect_scripts_dir();
                let config = rusty_stack::config::InstallerConfig::load_or_default(&scripts_dir)
                    .unwrap_or_else(|_| {
                        rusty_stack::config::InstallerConfig::default_with_paths(
                            &scripts_dir,
                            format!(
                                "{}/logs",
                                std::env::var("HOME").unwrap_or_else(|_| ".".into())
                            ),
                            rusty_stack::config::config_file_path().unwrap_or_else(|_| {
                                std::path::PathBuf::from("/tmp/mlstack/config/config.json")
                            }),
                        )
                    });

                // Propagate config flags to env vars that run_installation reads
                if config.force_reinstall {
                    std::env::set_var("MLSTACK_FORCE_REINSTALL", "1");
                    std::env::set_var("FORCE", "true");
                    std::env::set_var("PYTORCH_REINSTALL", "true");
                }
                if config.install_method != "auto" {
                    std::env::set_var("MLSTACK_INSTALL_METHOD", &config.install_method);
                }
                let component_name = component.name.clone();
                let cid = component_id.to_string();
                let handle = std::thread::spawn(move || {
                    rusty_stack::installer::run_installation(
                        vec![component],
                        config,
                        sudo_password,
                        tx,
                        input_rx,
                    );
                });
                let mut success = true;
                let mut error_msg = String::new();
                let spinner: &[char] = &[
                    '\u{280b}', '\u{2819}', '\u{2839}', '\u{2838}', '\u{283c}', '\u{2834}',
                    '\u{2826}', '\u{2827}', '\u{2807}', '\u{280f}',
                ];
                let mut si = 0usize;
                loop {
                    match rx.recv_timeout(std::time::Duration::from_millis(100)) {
                        Ok(rusty_stack::installer::InstallerEvent::Log(line, _)) => {
                            println!("    | {}", line);
                            tracing::info!(component = %cid, log = %line);
                        }
                        Ok(rusty_stack::installer::InstallerEvent::Progress {
                            progress,
                            message,
                            ..
                        }) => {
                            let pct = (progress * 100.0) as u8;
                            let s = spinner[si % spinner.len()];
                            si += 1;
                            eprint!("\r    {} {} [{:>3}%] {}    ", s, cid, pct, message);
                            let _ = std::io::stderr().flush();
                        }
                        Ok(rusty_stack::installer::InstallerEvent::ComponentStart {
                            name, ..
                        }) => {
                            eprint!("\r    ");
                            println!("    > Installing {}...", name);
                            tracing::info!(component = %cid, name = %name, "Component started");
                        }
                        Ok(rusty_stack::installer::InstallerEvent::ComponentComplete {
                            success: s,
                            message,
                            ..
                        }) => {
                            eprint!("\r{}\r", " ".repeat(80));
                            if s {
                                println!("    ok {} - {}", component_name, message);
                                tracing::info!(component = %cid, "Completed successfully");
                            } else {
                                println!("    FAIL {} - {}", component_name, message);
                                tracing::error!(component = %cid, error = %message, "Failed");
                                success = false;
                                error_msg = message;
                            }
                        }
                        Ok(rusty_stack::installer::InstallerEvent::VerificationReport {
                            lines,
                            ..
                        }) => {
                            for line in &lines {
                                println!("    | {}", line);
                            }
                        }
                        Ok(rusty_stack::installer::InstallerEvent::Finished { success: s }) => {
                            if !s {
                                success = false;
                                if error_msg.is_empty() {
                                    error_msg = "Finished with errors".into();
                                }
                            }
                            break;
                        }
                        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                            if self.cancelled.load(Ordering::Relaxed) {
                                return Err(format!("{} cancelled", cid));
                            }
                        }
                        Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                            break;
                        }
                    }
                }
                let _ = handle.join();
                eprint!("\r{}\r", " ".repeat(80));
                if success {
                    tracing::info!(component=%cid,"Succeeded");
                    Ok(())
                } else {
                    tracing::error!(component=%cid,error=%error_msg,"Failed");
                    Err(error_msg)
                }
            }
        }

        // Convert plan output back to PlannerItems for the apply engine.
        // We reconstruct minimal PlannerItems from the plan output data.
        let items: Vec<rusty_stack::orchestrator::planner::PlannerItem> = plan
            .plan
            .iter()
            .map(|item| {
                use rusty_stack::core::plan::{PlanItem, PlanItemInput};
                use rusty_stack::core::types::ValidationTier;
                use rusty_stack::orchestrator::planner::UpdateClassification;

                let classification = match item.classification.as_str() {
                    "safe" => UpdateClassification::Safe,
                    "guarded" => UpdateClassification::Guarded,
                    "blocked" => UpdateClassification::Blocked,
                    "candidate" => UpdateClassification::Candidate,
                    "experimental" => UpdateClassification::Experimental,
                    _ => UpdateClassification::Guarded,
                };

                let tier = match item.risk_tier.as_str() {
                    "validated" => ValidationTier::Validated,
                    "candidate" => ValidationTier::Candidate,
                    "experimental" => ValidationTier::Experimental,
                    "blocked" => ValidationTier::Blocked,
                    _ => ValidationTier::Candidate,
                };

                rusty_stack::orchestrator::planner::PlannerItem {
                    plan_item: PlanItem::new(PlanItemInput {
                        component_id: item.component_id.clone(),
                        current_version: item.current_version.clone(),
                        proposed_version: item.proposed_version.clone(),
                        validation_tier: tier,
                        selected: item.selected,
                        rationale: item.rationale.clone(),
                        dependencies: item.dependencies.clone(),
                        isolation_safe: matches!(classification, UpdateClassification::Safe),
                    }),
                    classification,
                    visible: item.visible,
                    selected: item.selected,
                    classification_reason: item.rationale.clone(),
                    requires_hardware_check: false,
                    min_rocm_version: String::new(),
                }
            })
            .collect();

        let cancelled = Arc::new(AtomicBool::new(false));
        let engine = ApplyEngine::new(DirectInstallerExecutor::new(cancelled));
        engine.apply(&items, &ApplyOptions::default())
    }

    /// Print a human-readable summary of the apply results.
    fn print_apply_summary(summary: &rusty_stack::orchestrator::apply::ApplySummary) {
        println!("\nApply Results:");
        println!("---------------");

        if !summary.success.is_empty() {
            println!("\n  Succeeded ({}):", summary.success.len());
            for item in &summary.success {
                println!(
                    "    ✓ {} {} → {}",
                    item.component_id, item.current_version, item.proposed_version
                );
            }
        }

        if !summary.failed.is_empty() {
            println!("\n  Failed ({}):", summary.failed.len());
            for item in &summary.failed {
                println!("    ✗ {} — {}", item.component_id, item.error_message);
            }
        }

        if !summary.blocked.is_empty() {
            println!("\n  Blocked by dependency ({}):", summary.blocked.len());
            for item in &summary.blocked {
                println!("    ! {} — {}", item.component_id, item.error_message);
            }
        }

        if !summary.held_back.is_empty() {
            println!("\n  Held back ({}):", summary.held_back.len());
            for item in &summary.held_back {
                println!("    - {} (not selected)", item.component_id);
            }
        }

        let total = summary.total();
        let succeeded = summary.success.len();
        if summary.has_failures() {
            println!(
                "\n  {}/{} components updated successfully.",
                succeeded, total
            );
        } else {
            println!("\n  All {} components updated successfully.", succeeded);
        }
    }

    // JSON output types for update
    #[derive(Debug, Serialize)]
    struct JsonOutput {
        scan: rusty_stack::orchestrator::planner::ScanOutput,
        plan: Option<rusty_stack::orchestrator::planner::PlanOutput>,
        apply: Option<serde_json::Value>,
        summary: JsonSummary,
    }

    #[derive(Debug, Serialize)]
    struct JsonSummary {
        status: String,
        scan_only: bool,
        #[serde(skip_serializing_if = "Option::is_none")]
        error: Option<String>,
    }
}

// ===========================================================================
// Upgrade subcommand implementation
// ===========================================================================

mod upgrade_impl {
    use super::*;
    use rusty_stack::orchestrator::upgrade::{
        self, BinaryDownloader, DownloadResult, ReleaseInfo, ReleaseProvider, SmokeTester,
        UpgradeError, UpgradeOptions, UpgradeResult, UpgradeStatus, UserInteractor, VersionInfo,
    };

    pub fn run(
        yes: bool,
        binary_path: Option<PathBuf>,
        backup_dir: Option<PathBuf>,
        cached_manifest: Option<PathBuf>,
        dry_run: bool,
    ) {
        let schema_version = rusty_stack::core::manifest::CURRENT_SCHEMA_VERSION;

        let current_version = VersionInfo {
            version: VERSION.to_string(),
            schema_version,
        };

        let options = UpgradeOptions {
            non_interactive: yes,
            binary_path,
            backup_dir,
            cached_manifest_path: cached_manifest,
        };

        // Dry run mode
        if dry_run {
            match RealReleaseProvider.fetch_latest_release() {
                Ok(release) => {
                    let upgrade_available = is_release_newer(VERSION, &release.version);
                    if yes {
                        let output = serde_json::json!({
                            "current_version": VERSION,
                            "schema_version": schema_version,
                            "latest_version": release.version,
                            "latest_schema_version": release.schema_version,
                            "upgrade_available": upgrade_available,
                            "download_url": release.download_url,
                        });
                        match serde_json::to_string(&output) {
                            Ok(payload) => println!("{payload}"),
                            Err(err) => {
                                eprintln!(
                                    "{{\"status\":\"error\",\"error\":\"failed to serialize dry-run output: {}\"}}",
                                    err.to_string().replace('"', "\\\"")
                                );
                                process::exit(1);
                            }
                        }
                    } else {
                        println!("Current version: v{VERSION}");
                        println!("Schema version: {schema_version}");
                        println!("Latest release: v{}", release.version);
                        println!(
                            "Upgrade available: {}",
                            if upgrade_available { "yes" } else { "no" }
                        );
                    }
                }
                Err(error) => {
                    if yes {
                        let output = serde_json::json!({
                            "current_version": VERSION,
                            "schema_version": schema_version,
                            "upgrade_available": false,
                            "error": error.to_string(),
                        });
                        match serde_json::to_string(&output) {
                            Ok(payload) => eprintln!("{payload}"),
                            Err(err) => {
                                eprintln!(
                                    "{{\"status\":\"error\",\"error\":\"failed to serialize dry-run error output: {}\"}}",
                                    err.to_string().replace('"', "\\\"")
                                );
                            }
                        }
                        process::exit(1);
                    } else {
                        println!("Current version: v{VERSION}");
                        println!("Schema version: {schema_version}");
                        eprintln!("Unable to check latest release: {error}");
                        process::exit(1);
                    }
                }
            }
            return;
        }

        let result = upgrade::run_upgrade(
            &current_version,
            &options,
            &RealReleaseProvider,
            &RealDownloader,
            &RealSmokeTester,
            &RealInteractor,
        );

        match result {
            Ok(upgrade_result) => {
                if yes {
                    println!("{}", format_json_output(&upgrade_result));
                } else {
                    print_interactive_result(&upgrade_result);
                }
                process::exit(0);
            }
            Err(error) => {
                if matches!(error, UpgradeError::NoUpgradeAvailable { .. }) {
                    if yes {
                        eprintln!("{}", format_error_json(&error));
                    } else {
                        print_interactive_error(&error);
                    }
                    process::exit(0);
                }
                if yes {
                    eprintln!("{}", format_error_json(&error));
                } else {
                    print_interactive_error(&error);
                }
                process::exit(1);
            }
        }
    }

    fn is_release_newer(current: &str, latest: &str) -> bool {
        let current = current.trim().trim_start_matches('v');
        let latest = latest.trim().trim_start_matches('v');
        match (
            semver::Version::parse(current),
            semver::Version::parse(latest),
        ) {
            (Ok(cur), Ok(lat)) => lat > cur,
            _ => latest != current,
        }
    }

    // Real implementations for CLI usage

    const RELEASES_API_URL: &str =
        "https://api.github.com/repos/scooter-lacroix/Stan-s-ML-Stack/releases/latest";
    const UPGRADE_USER_AGENT: &str = "rusty-stack-upgrade";

    /// Real release provider that fetches from GitHub releases API.
    struct RealReleaseProvider;

    impl ReleaseProvider for RealReleaseProvider {
        fn fetch_latest_release(&self) -> std::result::Result<ReleaseInfo, UpgradeError> {
            let release: serde_json::Value = ureq::Agent::new_with_defaults()
                .get(RELEASES_API_URL)
                .header("Accept", "application/vnd.github+json")
                .header("User-Agent", UPGRADE_USER_AGENT)
                .call()
                .map_err(|e| UpgradeError::DownloadFailed {
                    reason: format!("failed to fetch latest release: {e}"),
                })?
                .into_body()
                .read_json()
                .map_err(|e| UpgradeError::DownloadFailed {
                    reason: format!("failed to parse latest release JSON: {e}"),
                })?;

            let tag = release
                .get("tag_name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| UpgradeError::DownloadFailed {
                    reason: "latest release is missing tag_name".to_string(),
                })?;
            let version = tag.strip_prefix('v').unwrap_or(tag).to_string();

            let assets = release
                .get("assets")
                .and_then(|v| v.as_array())
                .ok_or_else(|| UpgradeError::DownloadFailed {
                    reason: "latest release is missing assets".to_string(),
                })?;

            let wanted_suffix = target_release_asset_suffix();
            let selected_asset = assets
                .iter()
                .find(|asset| {
                    asset
                        .get("name")
                        .and_then(|v| v.as_str())
                        .map(|name| name.ends_with(wanted_suffix))
                        .unwrap_or(false)
                })
                .ok_or_else(|| UpgradeError::DownloadFailed {
                    reason: format!(
                        "no release asset found for this platform (expected suffix: {wanted_suffix})"
                    ),
                })?;

            let asset_name = selected_asset
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| UpgradeError::DownloadFailed {
                    reason: "selected asset is missing name".to_string(),
                })?;
            let download_url = selected_asset
                .get("browser_download_url")
                .and_then(|v| v.as_str())
                .ok_or_else(|| UpgradeError::DownloadFailed {
                    reason: "selected asset is missing browser_download_url".to_string(),
                })?
                .to_string();

            let checksum = selected_asset
                .get("digest")
                .and_then(|v| v.as_str())
                .and_then(|digest| digest.strip_prefix("sha256:"))
                .map(|s| s.to_string())
                .or_else(|| checksum_from_sums_asset(assets, asset_name))
                .ok_or_else(|| UpgradeError::DownloadFailed {
                    reason: format!("no SHA256 checksum found for release asset '{asset_name}'"),
                })?;

            Ok(ReleaseInfo {
                version,
                download_url,
                checksum,
                min_runtime_version: "0.0.0".to_string(),
                schema_version: rusty_stack::core::manifest::CURRENT_SCHEMA_VERSION,
            })
        }
    }

    /// Real binary downloader using HTTP.
    struct RealDownloader;

    impl BinaryDownloader for RealDownloader {
        fn download(
            &self,
            release: &ReleaseInfo,
        ) -> std::result::Result<DownloadResult, UpgradeError> {
            let url = release.download_url.as_str();
            let archive_bytes = ureq::Agent::new_with_defaults()
                .get(url)
                .header("User-Agent", UPGRADE_USER_AGENT)
                .call()
                .map_err(|e| UpgradeError::DownloadFailed {
                    reason: format!("failed to download release asset: {e}"),
                })?
                .into_body()
                .read_to_vec()
                .map_err(|e| UpgradeError::DownloadFailed {
                    reason: format!("failed to read downloaded asset bytes: {e}"),
                })?;

            if url.ends_with(".tar.gz") || url.ends_with(".tgz") {
                upgrade::verify_integrity(&archive_bytes, &release.checksum)?;
                return Ok(DownloadResult {
                    binary_data: extract_binary_from_tar_gz(&archive_bytes)?,
                    integrity_verified: true,
                });
            }

            if url.ends_with(".zip") {
                upgrade::verify_integrity(&archive_bytes, &release.checksum)?;
                return Ok(DownloadResult {
                    binary_data: extract_binary_from_zip(&archive_bytes)?,
                    integrity_verified: true,
                });
            }

            Ok(DownloadResult {
                binary_data: archive_bytes,
                integrity_verified: false,
            })
        }
    }

    fn target_release_asset_suffix() -> &'static str {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        {
            "linux-x86_64.tar.gz"
        }
        #[cfg(all(target_os = "windows", target_arch = "x86_64"))]
        {
            "windows-x86_64.zip"
        }
        #[cfg(not(any(
            all(target_os = "linux", target_arch = "x86_64"),
            all(target_os = "windows", target_arch = "x86_64")
        )))]
        {
            "unsupported-platform"
        }
    }

    fn expected_binary_name() -> &'static str {
        #[cfg(target_os = "windows")]
        {
            "rusty-stack.exe"
        }
        #[cfg(not(target_os = "windows"))]
        {
            "rusty-stack"
        }
    }

    fn checksum_from_sums_asset(
        assets: &[serde_json::Value],
        target_asset_name: &str,
    ) -> Option<String> {
        let sums_url = assets.iter().find_map(|asset| {
            let name = asset.get("name")?.as_str()?;
            if name == "SHA256SUMS" {
                asset
                    .get("browser_download_url")?
                    .as_str()
                    .map(|s| s.to_string())
            } else {
                None
            }
        })?;

        let sums_text = ureq::Agent::new_with_defaults()
            .get(&sums_url)
            .header("User-Agent", UPGRADE_USER_AGENT)
            .call()
            .ok()?
            .into_body()
            .read_to_string()
            .ok()?;

        for line in sums_text.lines() {
            let mut parts = line.split_whitespace();
            let checksum = parts.next()?;
            let filename = parts.next()?.trim_start_matches('*');
            if filename == target_asset_name {
                return Some(checksum.to_string());
            }
        }
        None
    }

    fn find_file_recursively(root: &Path, filename: &str) -> Option<PathBuf> {
        let entries = std::fs::read_dir(root).ok()?;
        for entry in entries {
            let Ok(entry) = entry else {
                continue;
            };
            let path = entry.path();
            if path.is_dir() {
                if let Some(found) = find_file_recursively(&path, filename) {
                    return Some(found);
                }
                continue;
            }
            if path
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n == filename)
                .unwrap_or(false)
            {
                return Some(path);
            }
        }
        None
    }

    fn extract_binary_from_tar_gz(data: &[u8]) -> std::result::Result<Vec<u8>, UpgradeError> {
        let temp_dir = tempfile::tempdir().map_err(|e| UpgradeError::DownloadFailed {
            reason: format!("failed to create temp dir for archive extraction: {e}"),
        })?;
        let archive_path = temp_dir.path().join("release.tar.gz");
        std::fs::write(&archive_path, data).map_err(|e| UpgradeError::DownloadFailed {
            reason: format!("failed to write temporary archive: {e}"),
        })?;

        let status = std::process::Command::new("tar")
            .arg("-xzf")
            .arg(&archive_path)
            .arg("-C")
            .arg(temp_dir.path())
            .status()
            .map_err(|e| UpgradeError::DownloadFailed {
                reason: format!("failed to execute tar for archive extraction: {e}"),
            })?;

        if !status.success() {
            return Err(UpgradeError::DownloadFailed {
                reason: format!(
                    "archive extraction failed with exit code {:?}",
                    status.code()
                ),
            });
        }

        let binary_path = find_file_recursively(temp_dir.path(), expected_binary_name())
            .ok_or_else(|| UpgradeError::DownloadFailed {
                reason: format!(
                    "archive did not contain expected binary '{}'",
                    expected_binary_name()
                ),
            })?;

        std::fs::read(&binary_path).map_err(|e| UpgradeError::DownloadFailed {
            reason: format!(
                "failed to read extracted binary from {}: {e}",
                binary_path.display()
            ),
        })
    }

    #[cfg(target_os = "windows")]
    fn extract_binary_from_zip(data: &[u8]) -> std::result::Result<Vec<u8>, UpgradeError> {
        let temp_dir = tempfile::tempdir().map_err(|e| UpgradeError::DownloadFailed {
            reason: format!("failed to create temp dir for zip extraction: {e}"),
        })?;
        let archive_path = temp_dir.path().join("release.zip");
        std::fs::write(&archive_path, data).map_err(|e| UpgradeError::DownloadFailed {
            reason: format!("failed to write temporary zip archive: {e}"),
        })?;

        let script = format!(
            "Expand-Archive -LiteralPath '{}' -DestinationPath '{}' -Force",
            archive_path.display(),
            temp_dir.path().display()
        );
        let status = std::process::Command::new("powershell")
            .args(["-NoLogo", "-NoProfile", "-Command", &script])
            .status()
            .map_err(|e| UpgradeError::DownloadFailed {
                reason: format!("failed to execute PowerShell zip extraction: {e}"),
            })?;

        if !status.success() {
            return Err(UpgradeError::DownloadFailed {
                reason: format!("zip extraction failed with exit code {:?}", status.code()),
            });
        }

        let binary_path = find_file_recursively(temp_dir.path(), expected_binary_name())
            .ok_or_else(|| UpgradeError::DownloadFailed {
                reason: format!(
                    "zip archive did not contain expected binary '{}'",
                    expected_binary_name()
                ),
            })?;

        std::fs::read(&binary_path).map_err(|e| UpgradeError::DownloadFailed {
            reason: format!(
                "failed to read extracted binary from {}: {e}",
                binary_path.display()
            ),
        })
    }

    #[cfg(not(target_os = "windows"))]
    fn extract_binary_from_zip(_data: &[u8]) -> std::result::Result<Vec<u8>, UpgradeError> {
        Err(UpgradeError::DownloadFailed {
            reason: "zip upgrades are not supported on this platform".to_string(),
        })
    }

    /// Real smoke tester that runs the binary with --version.
    struct RealSmokeTester;

    impl SmokeTester for RealSmokeTester {
        fn test(&self, binary_path: &Path) -> std::result::Result<(), UpgradeError> {
            let output = std::process::Command::new(binary_path)
                .arg("--version")
                .output()
                .map_err(|e| UpgradeError::SmokeTestFailed {
                    reason: format!("failed to execute smoke test: {e}"),
                })?;

            if output.status.success() {
                Ok(())
            } else {
                let stderr = String::from_utf8_lossy(&output.stderr);
                Err(UpgradeError::SmokeTestFailed {
                    reason: format!(
                        "smoke test failed with exit code {:?}: {stderr}",
                        output.status.code()
                    ),
                })
            }
        }
    }

    /// Real user interactor using stdin/stdout.
    struct RealInteractor;

    impl UserInteractor for RealInteractor {
        fn confirm_upgrade(&self, current: &str, target: &str) -> bool {
            print!("Upgrade Rusty Stack from v{current} to v{target}? [y/N] ");
            io::stdout().flush().ok();

            let mut input = String::new();
            io::stdin().read_line(&mut input).ok();
            matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
        }
    }

    fn format_json_output(upgrade_result: &UpgradeResult) -> String {
        serde_json::to_string_pretty(upgrade_result)
            .unwrap_or_else(|e| format!("{{\"error\": \"failed to serialize result: {e}\"}}"))
    }

    fn format_error_json(error: &UpgradeError) -> String {
        let status = match error {
            UpgradeError::Declined => "declined",
            UpgradeError::NoUpgradeAvailable { .. } => "no_upgrade",
            UpgradeError::IncompatibleRuntime { .. } => "refused",
            UpgradeError::RuntimeTooOld { .. } => "refused",
            _ => "error",
        };
        format!(
            r#"{{"status": "{status}", "error": "{}"}}"#,
            error.to_string().replace('"', "\\\"")
        )
    }

    fn print_interactive_result(result: &UpgradeResult) {
        match result.status {
            UpgradeStatus::Success => {
                println!(
                    "✓ Successfully upgraded Rusty Stack from v{} to v{}",
                    result.previous_version, result.new_version
                );
                println!("  Backup saved to: {}", result.backup_path.display());
            }
            UpgradeStatus::RolledBack => {
                println!(
                    "✗ Upgrade from v{} to v{} failed — rolled back to previous version",
                    result.previous_version, result.new_version
                );
            }
            UpgradeStatus::Refused => {
                println!("Upgrade refused due to compatibility issues.");
            }
        }
    }

    fn print_interactive_error(error: &UpgradeError) {
        match error {
            UpgradeError::IncompatibleRuntime { current, required } => {
                eprintln!(
                    "✗ Upgrade refused: current version v{current} does not meet required v{required}"
                );
                eprintln!("  A newer runtime is required before upgrading.");
            }
            UpgradeError::RuntimeTooOld {
                current_schema,
                manifest_schema,
            } => {
                eprintln!(
                    "✗ Runtime too old: schema v{current_schema} cannot parse manifest schema v{manifest_schema}"
                );
                eprintln!(
                    "  A manual upgrade is required. Please download the latest binary from:"
                );
                eprintln!("  https://github.com/scooter-lacroix/Stan-s-ML-Stack/releases");
            }
            UpgradeError::IntegrityCheckFailed { expected, actual } => {
                eprintln!("✗ Binary integrity check failed!");
                eprintln!("  Expected: {expected}");
                eprintln!("  Actual:   {actual}");
                eprintln!("  The downloaded binary may be corrupted or tampered with.");
            }
            UpgradeError::SmokeTestFailed { reason } => {
                eprintln!("✗ Post-upgrade smoke test failed: {reason}");
                eprintln!("  Rolled back to previous version.");
            }
            UpgradeError::DownloadFailed { reason } => {
                eprintln!("✗ Download failed: {reason}");
            }
            UpgradeError::Declined => {
                println!("Upgrade cancelled.");
            }
            UpgradeError::NoUpgradeAvailable { current, latest } => {
                println!("Already up to date (current: v{current}, latest: v{latest}).");
            }
            UpgradeError::IoError { path, reason } => {
                eprintln!("✗ I/O error at {path}: {reason}");
            }
        }
    }
}

// ===========================================================================
// Bench subcommand implementation
// ===========================================================================

mod bench_impl {
    use super::*;

    #[derive(Debug, Serialize)]
    struct BenchmarkOutput {
        name: String,
        success: bool,
        execution_time_ms: u128,
        results: serde_json::Value,
        errors: Vec<String>,
    }

    pub fn run(benchmark: Option<&str>, json: bool, list: bool) {
        if list {
            print_benchmark_list();
            return;
        }

        let name = match benchmark {
            Some(name) => name,
            None => {
                eprintln!("error: no benchmark specified. Use --list to see available benchmarks.");
                process::exit(1);
            }
        };

        // Delegate to benchmark_runners module
        let result = match rusty_stack::benchmark_runners::run_benchmark(name) {
            Ok(output) => {
                // Convert from benchmark_runners::BenchmarkOutput to our local type
                BenchmarkOutput {
                    name: output.name,
                    success: output.success,
                    execution_time_ms: output.execution_time_ms,
                    results: output.results,
                    errors: output.errors,
                }
            }
            Err(err_msg) => {
                let output = BenchmarkOutput {
                    name: name.to_string(),
                    success: false,
                    execution_time_ms: 0,
                    results: serde_json::Value::Object(serde_json::Map::new()),
                    errors: vec![err_msg],
                };
                if json {
                    let json_str = serde_json::to_string_pretty(&output).unwrap_or_default();
                    println!("{}", json_str);
                } else {
                    eprintln!("Error: {}", output.errors.join(", "));
                }
                process::exit(1);
            }
        };

        if json {
            let json_str = serde_json::to_string_pretty(&result).unwrap_or_default();
            println!("{}", json_str);
        } else {
            println!("Benchmark: {}", result.name);
            println!(
                "Status: {}",
                if result.success { "SUCCESS" } else { "FAILED" }
            );
            println!("Time: {} ms", result.execution_time_ms);

            if !result.errors.is_empty() {
                println!("Errors:");
                for e in &result.errors {
                    println!("  - {}", e);
                }
            }

            if result.success {
                if let Some(map) = result.results.as_object() {
                    println!("\nResults:");
                    for (key, value) in map {
                        if let Some(obj) = value.as_object() {
                            let status = obj
                                .get("success")
                                .and_then(|v| v.as_bool())
                                .map(|ok| if ok { "SUCCESS" } else { "FAILED" })
                                .unwrap_or("UNKNOWN");
                            let time_ms = obj
                                .get("execution_time_ms")
                                .and_then(|v| v.as_u64())
                                .unwrap_or(0);
                            println!("  {} [{} | {} ms]", key, status, time_ms);
                            if let Some(metrics) = obj.get("metrics").and_then(|m| m.as_object()) {
                                for (metric_key, metric_val) in metrics.iter().take(4) {
                                    println!("    - {}: {}", metric_key, metric_val);
                                }
                                if metrics.len() > 4 {
                                    println!("    - ... {} more metrics", metrics.len() - 4);
                                }
                            }
                        } else {
                            println!("  {}: {}", key, value);
                        }
                    }
                }
            }
        }

        if !result.success {
            process::exit(1);
        }
    }

    fn print_benchmark_list() {
        println!("Available benchmarks:");
        println!();
        println!("Pre-installation:");
        println!("  gpu-capability       - GPU capability detection");
        println!("  memory-bandwidth     - HBM memory bandwidth test");
        println!("  tensor-core          - Tensor Core performance");
        println!();
        println!("GPU Performance:");
        println!("  gemm                 - Matrix multiplication benchmark");
        println!();
        println!("Component Benchmarks:");
        println!("  pytorch              - PyTorch performance tests");
        println!("  llama-cpp            - LLaMA.cpp benchmark suite");
        println!("  flash-attention      - Flash Attention vs standard");
        println!("  vllm                 - vLLM throughput benchmark");
        println!("  deepspeed            - DeepSpeed ZeRO performance");
        println!("  megatron             - Megatron-LM throughput/import benchmark");
        println!();
        println!("Combined:");
        println!("  all-pre              - All pre-installation benchmarks");
        println!("  all                  - All benchmarks (optional failures non-fatal)");
    }
}

// ===========================================================================
// Deps subcommand implementation
// ===========================================================================

mod deps_impl {
    use super::*;

    pub fn run(lag_days: u64, verbose: bool, dir: Option<PathBuf>, json: bool) {
        let crate_dir = dir.unwrap_or_else(|| {
            // Default: look for rusty-stack/ relative to the repo root
            let exe = std::env::current_exe().unwrap_or_default();
            let repo_root = exe
                .parent()
                .and_then(|p| p.parent())
                .and_then(|p| p.parent())
                .unwrap_or(Path::new("."));
            repo_root.join("rusty-stack")
        });

        let cargo_toml_path = crate_dir.join("Cargo.toml");
        if !cargo_toml_path.exists() {
            eprintln!(
                "error: Cargo.toml not found at {}",
                cargo_toml_path.display()
            );
            process::exit(2);
        }

        let cargo_lock_path = crate_dir
            .join("Cargo.lock")
            .exists()
            .then(|| crate_dir.join("Cargo.lock"))
            .or_else(|| {
                let project_lock = crate_dir.parent()?.join("Cargo.lock");
                project_lock.exists().then_some(project_lock)
            });

        let deps = parse_direct_deps(&cargo_toml_path);
        if deps.is_empty() {
            println!("No dependencies found in Cargo.toml");
            return;
        }

        if !json {
            println!("═══════════════════════════════════════════════════════════════");
            println!("  Dependency Update Check");
            println!("  Crate:     {}", crate_dir.display());
            println!("  Lag:       {} days", lag_days);
            println!("═══════════════════════════════════════════════════════════════");
            println!();
            println!(
                "Found {} direct dependencies. Checking crates.io...",
                deps.len()
            );
            println!();
        }

        let mut up_to_date = 0u32;
        let mut updates_available = 0u32;
        let mut lag_blocked = 0u32;
        let mut check_failed = 0u32;
        let mut results = Vec::new();

        for dep in &deps {
            let locked_ver = cargo_lock_path
                .as_ref()
                .and_then(|p| find_locked_version(p, &dep.name))
                .unwrap_or_else(|| "0.0.0".to_string());

            match query_crates_io(&dep.name) {
                Ok(info) => {
                    if verbose && !json {
                        println!(
                            "  API response for {}: latest={}, updated={}",
                            dep.name,
                            info.latest,
                            info.updated.as_deref().unwrap_or("N/A")
                        );
                    }

                    let locked = semver::Version::parse(&locked_ver).ok();
                    let latest = semver::Version::parse(&info.latest).ok();

                    let is_newer = match (&locked, &latest) {
                        (Some(l), Some(r)) => r > l,
                        _ => info.latest != locked_ver,
                    };

                    if !is_newer {
                        if !json {
                            println!(
                                "  \u{2705} {} \u{2014} {} (up to date)",
                                dep.name, locked_ver
                            );
                        }
                        results.push(DepResult {
                            name: dep.name.clone(),
                            locked: locked_ver.clone(),
                            latest: info.latest.clone(),
                            status: "up_to_date".into(),
                        });
                        up_to_date += 1;
                    } else if let Some(days_since) = info.days_since_publish() {
                        if days_since >= lag_days as i64 {
                            if !json {
                                println!("  \u{1F4E6} {} \u{2014} {} \u{2192} {} (published {} days ago)", dep.name, locked_ver, info.latest, days_since);
                            }
                            results.push(DepResult {
                                name: dep.name.clone(),
                                locked: locked_ver.clone(),
                                latest: info.latest.clone(),
                                status: "update_available".into(),
                            });
                            updates_available += 1;
                        } else {
                            if !json {
                                println!("  \u{23F3} {} \u{2014} {} \u{2192} {} (published {} days ago, lag: {}d)", dep.name, locked_ver, info.latest, days_since, lag_days);
                            }
                            results.push(DepResult {
                                name: dep.name.clone(),
                                locked: locked_ver.clone(),
                                latest: info.latest.clone(),
                                status: "lag_blocked".into(),
                            });
                            lag_blocked += 1;
                        }
                    } else {
                        if !json {
                            println!("  \u{1F4E6} {} \u{2014} {} \u{2192} {} (no publish date, assuming eligible)", dep.name, locked_ver, info.latest);
                        }
                        results.push(DepResult {
                            name: dep.name.clone(),
                            locked: locked_ver.clone(),
                            latest: info.latest.clone(),
                            status: "update_available".into(),
                        });
                        updates_available += 1;
                    }
                }
                Err(e) => {
                    if !json {
                        println!(
                            "  \u{26A0}\u{FE0F}  {} \u{2014} failed to query crates.io: {}",
                            dep.name, e
                        );
                    }
                    results.push(DepResult {
                        name: dep.name.clone(),
                        locked: locked_ver.clone(),
                        latest: "unknown".into(),
                        status: "check_failed".into(),
                    });
                    check_failed += 1;
                }
            }
        }

        if json {
            let output = serde_json::json!({
                "crate": crate_dir.display().to_string(),
                "lag_days": lag_days,
                "results": results,
                "summary": {
                    "up_to_date": up_to_date,
                    "updates_available": updates_available,
                    "lag_blocked": lag_blocked,
                    "check_failed": check_failed,
                }
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&output).unwrap_or_default()
            );
        } else {
            println!();
            println!("═══════════════════════════════════════════════════════════════");
            println!("  Summary");
            println!("\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}");
            println!("  Up to date:        {}", up_to_date);
            println!("  Updates available: {}", updates_available);
            println!("  Lag-blocked:       {}", lag_blocked);
            println!("  Check failed:      {}", check_failed);
            println!("═══════════════════════════════════════════════════════════════");
        }

        if updates_available > 0 {
            process::exit(1);
        } else if check_failed > 0 {
            process::exit(2);
        }
    }

    // -- Helpers --

    struct DirectDep {
        name: String,
    }

    #[derive(Serialize)]
    struct DepResult {
        name: String,
        locked: String,
        latest: String,
        status: String,
    }

    struct CrateInfo {
        latest: String,
        updated: Option<String>,
    }

    impl CrateInfo {
        fn days_since_publish(&self) -> Option<i64> {
            let updated = self.updated.as_ref()?;
            let published =
                chrono::DateTime::<chrono::FixedOffset>::parse_from_rfc3339(updated).ok()?;
            let now = chrono::Utc::now();
            let duration = now.signed_duration_since(published.with_timezone(&chrono::Utc));
            Some(duration.num_days())
        }
    }

    fn parse_direct_deps(cargo_toml: &Path) -> Vec<DirectDep> {
        let content = std::fs::read_to_string(cargo_toml).unwrap_or_default();
        let mut deps = Vec::new();
        let mut in_deps = false;
        let mut in_dep_subtable = false;

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed == "[dependencies]" {
                in_deps = true;
                in_dep_subtable = false;
                continue;
            }
            if in_deps && trimmed.starts_with('[') {
                if let Some(name) = trimmed
                    .strip_prefix("[dependencies.")
                    .and_then(|s| s.strip_suffix(']'))
                    .map(|s| s.trim_matches('"').to_string())
                    .filter(|s| !s.is_empty())
                {
                    deps.push(DirectDep { name });
                    in_dep_subtable = true;
                    continue;
                }
                break;
            }
            if in_deps && !in_dep_subtable {
                // Match: name = "version" or name = { version = "...", ... }
                if let Some(eq_pos) = trimmed.find('=') {
                    let name = trimmed[..eq_pos].trim().to_string();
                    if name.is_empty() || name.starts_with('#') {
                        continue;
                    }
                    deps.push(DirectDep { name });
                }
            }
        }
        deps
    }

    fn find_locked_version(lock_path: &Path, dep_name: &str) -> Option<String> {
        let content = std::fs::read_to_string(lock_path).ok()?;
        let needle = format!("name = \"{}\"", dep_name);
        let mut found_name = false;
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed == needle {
                found_name = true;
                continue;
            }
            if found_name && trimmed.starts_with("version =") {
                return trimmed.split('"').nth(1).map(|s| s.to_string());
            }
            if found_name && trimmed.starts_with("name =") {
                found_name = false;
            }
        }
        None
    }

    fn query_crates_io(name: &str) -> anyhow::Result<CrateInfo> {
        let url = format!("https://crates.io/api/v1/crates/{}", name);
        let agent = ureq::Agent::new_with_defaults();

        let response = agent
            .get(&url)
            .header(
                "User-Agent",
                "rusty-stack-dep-checker (github.com/scooter-lacroix)",
            )
            .call()
            .map_err(|e| anyhow::anyhow!("HTTP request failed: {}", e))?;

        let body: serde_json::Value = response
            .into_body()
            .read_json()
            .map_err(|e| anyhow::anyhow!("Failed to parse JSON: {}", e))?;

        let latest = body["crate"]["max_stable_version"]
            .as_str()
            .or_else(|| body["crate"]["max_version"].as_str())
            .unwrap_or("0.0.0")
            .to_string();

        let updated = body["crate"]["updated_at"]
            .as_str()
            .map(|s: &str| s.to_string());

        Ok(CrateInfo { latest, updated })
    }
}

// ===========================================================================
// Verify subcommand implementation
// ===========================================================================

mod verify_impl {
    use super::*;

    pub fn run(_full: bool, enhanced: bool, build: bool, json: bool) {
        // Determine mode — default to full if none specified
        let mode = if enhanced {
            "enhanced"
        } else if build {
            "build"
        } else {
            "full" // default or --full
        };

        let result = match mode {
            "enhanced" => rusty_stack::verification::enhanced_verify(),
            "build" => rusty_stack::verification::verify_and_build(),
            _ => rusty_stack::verification::full_verify(),
        };

        if json {
            let output = rusty_stack::verification::format_result_json(&result);
            println!("{}", output);
        } else {
            let output = rusty_stack::verification::format_result_human(&result);
            print!("{}", output);
        }

        // For --build mode, list failed components that need rebuild
        if build && !result.all_passed {
            let failed = rusty_stack::verification::failed_components(&result);
            if !json {
                eprintln!("\nComponents needing rebuild:");
                for id in &failed {
                    eprintln!("  - {}", id);
                }
            }
        }

        if !result.all_passed {
            process::exit(1);
        }
    }
}

// ===========================================================================
// Main
// ===========================================================================

// ===========================================================================
// Uninstall / Reinstall subcommand implementation
// ===========================================================================

mod uninstall_impl {
    use super::*;

    pub fn run(keep_rocm: bool, purge_dir: bool, yes: bool, _sudo_password: Option<String>) {
        let _log_guard = rusty_stack::logging::init_logging("uninstall");
        println!("Rusty Stack — uninstall (keep_rocm={keep_rocm}, purge_dir={purge_dir})");
        // Resolve a sudo password (env > TTY prompt) so privileged steps
        // (system-package purge, /opt/rocm removal) can run unattended via
        // askpass — `sudo -n` alone fails when a password is required.
        let sudo_password = sudo_creds::resolve_for_uninstall();
        let opts = rusty_stack::uninstall::UninstallOptions {
            keep_rocm,
            purge_mlstack_dir: purge_dir,
            yes,
            sudo_password,
        };
        match rusty_stack::uninstall::uninstall_stack(&opts) {
            Ok(report) => {
                println!("\n=== Uninstall report ===");
                println!(
                    "pip packages targeted: {}",
                    if report.pip_uninstall_attempted.is_empty() {
                        "(none)".into()
                    } else {
                        report.pip_uninstall_attempted.join(", ")
                    }
                );
                println!(
                    "ROCm system packages purged: {}",
                    report.system_packages_purged
                );
                println!("/opt/rocm removed: {}", report.opt_rocm_removed);
                if !report.env_files_removed.is_empty() {
                    println!("removed: {}", report.env_files_removed.join(", "));
                }
                if !report.sourcing_lines_stripped.is_empty() {
                    println!(
                        "shell sourcing stripped from: {}",
                        report.sourcing_lines_stripped.join(", ")
                    );
                }
                println!("registry cleared: {}", report.registry_cleared);
                if !report.warnings.is_empty() {
                    eprintln!("\nWarnings:");
                    for w in &report.warnings {
                        eprintln!("  - {w}");
                    }
                }
                println!("\nUninstall complete. Reboot recommended before reinstalling.");
            }
            Err(e) => {
                eprintln!("Uninstall failed: {e:#}");
                process::exit(1);
            }
        }
    }
}

mod reinstall_impl {
    use super::*;

    /// Force-reinstall = uninstall the stack, then relaunch the TUI installer.
    /// (Stage 6: previously broken — `rusty` had no reinstall path at all.)
    pub fn run(keep_rocm: bool, purge_dir: bool, _sudo_password: Option<String>) {
        let _log_guard = rusty_stack::logging::init_logging("reinstall");
        println!("Rusty Stack — reinstall: uninstalling, then relaunching installer…");
        let sudo_password = sudo_creds::resolve_for_uninstall();
        let opts = rusty_stack::uninstall::UninstallOptions {
            keep_rocm,
            purge_mlstack_dir: purge_dir,
            yes: true,
            sudo_password,
        };
        if let Err(e) = rusty_stack::uninstall::uninstall_stack(&opts) {
            eprintln!("Uninstall phase failed: {e:#}");
            process::exit(1);
        }
        println!("\nUninstall phase complete. Launching TUI installer…");
        #[cfg(feature = "tui")]
        {
            if let Err(e) = rusty_stack::run_tui() {
                eprintln!("TUI error: {e}");
                process::exit(1);
            }
        }
        #[cfg(not(feature = "tui"))]
        {
            eprintln!("TUI not available in this build; run a TUI-enabled `rusty` to install.");
        }
    }
}

mod install_impl {
    use super::*;

    /// Install command (Tenet 1): ensures the target env (named or global),
    /// pins it for the installer, prints the sourcing command + path, then
    /// launches the installer. `--env <name>` isolates all components into
    /// `~/.mlstack/envs/<name>/`; `--global` (default) uses `~/.mlstack/global/`.
    pub fn run(env: Option<String>, global: bool) {
        let _log_guard = rusty_stack::logging::init_logging("install");
        use rusty_stack::platform::environment::{
            ensure_global_venv, ensure_named_venv, resolve_canonical_python_bin,
        };
        let bootstrap = resolve_canonical_python_bin();

        match env.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
            Some(name) => match ensure_named_venv(name, &bootstrap) {
                Ok(py) => {
                    std::env::set_var("MLSTACK_ENV_NAME", name);
                    println!("[install] Named env '{name}' ready: {}", py.display());
                    println!("[install] ALL components will install into ~/.mlstack/envs/{name}/");
                    println!("\n=== Sourcing command (run in your shell to activate the env) ===");
                    println!("  bash/zsh:  source ~/.mlstack/envs/{name}/bin/activate");
                    println!("  fish:      source ~/.mlstack/envs/{name}/bin/activate.fish");
                    println!("  env path:  ~/.mlstack/envs/{name}/");
                }
                Err(e) => {
                    eprintln!("[install] failed to create named env '{name}': {e:#}");
                    process::exit(1);
                }
            },
            None => {
                let _ = global;
                match ensure_global_venv(&bootstrap) {
                    Ok(py) => {
                        std::env::set_var("MLSTACK_PYTHON_BIN", py.to_string_lossy().to_string());
                        println!("[install] Global env ready: {}", py.display());
                        println!(
                            "[install] Components will install into the managed global env ~/.mlstack/global/"
                        );
                        println!("\n=== Sourcing command ===");
                        println!("  bash/zsh:  source ~/.mlstack_env");
                        println!(
                            "  fish:      ~/.config/fish/conf.d/mlstack_env.fish (auto-loaded)"
                        );
                    }
                    Err(e) => {
                        eprintln!("[install] failed to create global env: {e:#}");
                        process::exit(1);
                    }
                }
            }
        }

        println!("\nLaunching installer…");
        #[cfg(feature = "tui")]
        {
            if let Err(e) = rusty_stack::run_tui() {
                eprintln!("TUI error: {e}");
                process::exit(1);
            }
        }
        #[cfg(not(feature = "tui"))]
        {
            eprintln!("TUI not available in this build.");
        }
    }
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Some(Subcommands::Update {
            scan_only,
            all_safe,
            include_experimental,
            yes,
            json,
            components,
        }) => {
            update_impl::run(
                scan_only,
                all_safe,
                include_experimental,
                yes,
                json,
                components,
            );
        }
        Some(Subcommands::Upgrade {
            yes,
            binary_path,
            backup_dir,
            cached_manifest,
            dry_run,
        }) => {
            upgrade_impl::run(yes, binary_path, backup_dir, cached_manifest, dry_run);
        }
        Some(Subcommands::Bench {
            benchmark,
            json,
            list,
        }) => {
            bench_impl::run(benchmark.as_deref(), json, list);
        }
        Some(Subcommands::Deps {
            lag,
            verbose,
            dir,
            json,
        }) => {
            deps_impl::run(lag, verbose, dir, json);
        }
        Some(Subcommands::Verify {
            full,
            enhanced,
            build,
            json,
        }) => {
            verify_impl::run(full, enhanced, build, json);
        }
        Some(Subcommands::Uninstall {
            keep_rocm,
            purge_dir,
            yes,
        }) => {
            uninstall_impl::run(keep_rocm, purge_dir, yes, None);
        }
        Some(Subcommands::Reinstall {
            keep_rocm,
            purge_dir,
        }) => {
            reinstall_impl::run(keep_rocm, purge_dir, None);
        }
        Some(Subcommands::Install { env, global }) => {
            install_impl::run(env, global);
        }
        None => {
            // No subcommand — launch TUI
            #[cfg(feature = "tui")]
            {
                if let Err(e) = rusty_stack::run_tui() {
                    eprintln!("Error: {e}");
                    process::exit(1);
                }
            }

            #[cfg(not(feature = "tui"))]
            {
                eprintln!(
                    "error: TUI is not available in this build. \
                     Install with TUI support or use a subcommand (update, upgrade, bench)."
                );
                process::exit(1);
            }
        }
    }
}