modde-cli 0.2.1

CLI interface for modde
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
use std::path::PathBuf;
#[cfg(feature = "remote-telemetry")]
use std::{env, time::Duration};

#[cfg(feature = "remote-telemetry")]
use anyhow::Context;
use anyhow::Result;
use clap::{Parser, Subcommand};
use tracing_subscriber::EnvFilter;
#[cfg(feature = "remote-telemetry")]
use tracing_subscriber::prelude::*;

mod commands;
#[cfg(feature = "remote-telemetry")]
mod telemetry;

#[derive(Parser)]
#[command(name = "modde", version, about = "NixOS-native game mod manager")]
struct Cli {
    /// Override data directory (default: ~/.local/share/modde or $`MODDE_DATA_DIR`)
    #[arg(long, global = true, env = "MODDE_DATA_DIR")]
    data_dir: Option<PathBuf>,

    /// Write a DHAT heap profile. Requires the `heap-profile` cargo feature.
    #[arg(long, global = true, env = "MODDE_HEAP_PROFILE")]
    heap_profile: Option<PathBuf>,

    /// Panic after startup to smoke test remote telemetry crash capture.
    #[cfg(feature = "remote-telemetry")]
    #[arg(long, global = true, hide = true)]
    debug_panic: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    #[command(hide = true)]
    Dev {
        #[command(subcommand)]
        action: DevAction,
    },
    /// Manage profiles
    Profile {
        #[command(subcommand)]
        action: ProfileAction,
    },
    /// Switch profile, deploy mods, and launch the game
    Play {
        /// Profile to activate (uses active profile if omitted)
        profile: Option<String>,
        #[arg(long)]
        game: String,
        /// Skip mod deployment (just switch + launch)
        #[arg(long)]
        no_deploy: bool,
        /// Skip profile switch (just deploy + launch active)
        #[arg(long)]
        no_switch: bool,
        /// Skip save auto-capture after game exit
        #[arg(long)]
        no_capture: bool,
    },
    /// Deploy mods for the active or specified profile
    Deploy {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
    },
    /// Rollback to the previous deployment
    Rollback {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
    },
    /// Install mods from various sources
    Install {
        #[command(subcommand)]
        source: InstallSource,
    },
    /// Manage individual mods (remove, diagnose unknown-type dossiers)
    Mod {
        #[command(subcommand)]
        action: ModAction,
    },
    /// Verify installed file integrity
    Verify {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
    },
    /// Nexus Mods account management
    Nexus {
        #[command(subcommand)]
        action: NexusAction,
    },
    /// Manage vanilla game snapshots
    Stock {
        #[command(subcommand)]
        action: StockAction,
    },
    /// FOMOD installer utilities
    Fomod {
        #[command(subcommand)]
        action: FomodAction,
    },
    /// Manage save file assignments
    Save {
        #[command(subcommand)]
        action: SaveAction,
    },
    /// Check for mod updates from Nexus
    Update {
        #[command(subcommand)]
        action: UpdateAction,
    },
    /// LOOT masterlist integration (Bethesda plugin sorting)
    Loot {
        #[command(subcommand)]
        action: LootAction,
    },
    /// Run external tools with overwrite capture
    Tool {
        #[command(subcommand)]
        action: ToolAction,
    },
    /// Handle nxm:// download links from Nexus Mods
    Nxm {
        #[command(subcommand)]
        action: NxmAction,
    },
    /// Browse, download, and generate Home Manager snippets for Wabbajack modlists
    Wabbajack {
        #[command(subcommand)]
        action: WabbajackAction,
    },
    /// Scan game directory for installed mods
    Scan {
        #[arg(long)]
        game: String,
        /// Path to game installation (auto-detected if omitted)
        #[arg(long)]
        game_dir: Option<PathBuf>,
        /// Path to .wabbajack file for manifest matching
        #[arg(long)]
        manifest: Option<PathBuf>,
        /// Import discovered mods into this profile
        #[arg(long)]
        import_to: Option<String>,
        /// Minimum file presence fraction (0.0-1.0)
        #[arg(long, default_value = "0.5")]
        threshold: f32,
        /// Report only, don't write to database
        #[arg(long)]
        dry_run: bool,
        /// Before merging, remove any pre-existing filesystem-scanner
        /// rows (cet/*, reds/*, tweak/*, archive/*, redmod/*) from the
        /// target profile that the manifest already covers. Requires
        /// `--manifest` and `--import-to`. See `modde profile dedup`
        /// for the standalone equivalent.
        #[arg(long)]
        prune_duplicates: bool,
    },
    /// Analyse mod collisions and suggest optimisations
    Collisions {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
        /// Show all collisions including cosmetic ones
        #[arg(long)]
        all: bool,
        /// Suggest hide commands for redundant files
        #[arg(long)]
        suggest_hides: bool,
    },
    /// Run diagnostics to detect common modding issues
    Diagnostics {
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: Option<String>,
    },
    /// Export mod list to CSV
    Export {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
        /// Comma-separated columns
        #[arg(long)]
        columns: Option<String>,
        /// Output file (stdout if omitted)
        #[arg(long)]
        output: Option<String>,
    },
    /// Manage mod and plugin order backups
    Backup {
        #[command(subcommand)]
        action: BackupAction,
    },
    /// Detect installed games across Steam and Heroic launchers
    Detect,
    /// Manage user-defined games
    Game {
        #[command(subcommand)]
        action: GameAction,
    },
    /// Manage modde instances (multiple data directories)
    Instance {
        #[command(subcommand)]
        action: InstanceAction,
    },
    /// Manage named launch targets (`xEdit`, `BodySlide`, `FNIS`, etc.)
    ///
    /// Thin alias for the executable subset of `modde tool`. The
    /// underlying storage is shared, so `modde exec list` and
    /// `modde tool list-executables` print the same rows.
    Exec {
        #[command(subcommand)]
        action: ExecAction,
    },
    /// Install and update modde-maintained Codex skills
    Skill {
        #[command(subcommand)]
        action: SkillAction,
    },
    /// Import existing TOML profiles into the database
    Import,
    /// Launch the graphical user interface
    Gui,
}

#[derive(Subcommand)]
enum ExecAction {
    /// Save (or update) a named launch target.
    ///
    /// Re-running with the same name overwrites the existing entry,
    /// so `add` doubles as `edit`.
    Add {
        name: String,
        executable: PathBuf,
        #[arg(long)]
        game: String,
        #[arg(long)]
        working_dir: Option<PathBuf>,
        #[arg(long, default_value = "__overwrite__")]
        output_mod: String,
        #[arg(long)]
        wine_dll_overrides: Option<String>,
        #[arg(long = "env")]
        environment: Vec<String>,
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// List configured launch targets for a game.
    List {
        #[arg(long)]
        game: String,
    },
    /// Remove a launch target.
    Remove {
        name: String,
        #[arg(long)]
        game: String,
    },
    /// Run a saved launch target with overwrite capture.
    Run {
        name: String,
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: Option<String>,
        #[arg(last = true)]
        args: Vec<String>,
    },
}

#[derive(Subcommand)]
enum DevAction {
    #[command(hide = true)]
    ExportToolSchema {
        #[arg(long, default_value = "nix/tool-schema.nix")]
        out: PathBuf,
    },
}

#[derive(Subcommand)]
enum SkillAction {
    /// List built-in modde skills and install status
    List,
    /// Print the target skill directory
    Path,
    /// Install or update one built-in skill, or `all`
    Install {
        /// Skill name, or `all`
        name: String,
        /// Replace installed skills even when the installed version is newer
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum InstanceAction {
    /// Create a new instance
    Create {
        name: String,
        #[arg(long)]
        data_dir: PathBuf,
    },
    /// List all instances
    List,
    /// Switch to an instance
    Switch { name: String },
}

#[derive(Subcommand)]
enum GameAction {
    /// Add or overwrite a user-defined game registration
    Add {
        id: String,
        #[arg(long)]
        display_name: String,
        #[arg(long)]
        executable_dir: PathBuf,
        #[arg(long)]
        steam_app_id: Option<String>,
        #[arg(long)]
        install_dir_name: Option<String>,
        #[arg(long)]
        mod_dir: Option<PathBuf>,
        #[arg(long)]
        nexus_domain: Option<String>,
        #[arg(long = "proxy-dll")]
        proxy_dlls: Vec<String>,
        /// Overwrite an existing user-defined game TOML
        #[arg(long)]
        force: bool,
    },
    /// List user-defined games
    List,
    /// Remove a user-defined game registration
    Remove {
        id: String,
        /// Skip the confirmation prompt
        #[arg(long)]
        yes: bool,
    },
    /// Detect executable-bearing directories under a game install
    Detect { install_path: PathBuf },
    /// Show a resolved game registration
    Show { id: String },
    /// Export a game registration to TOML
    Export {
        id: String,
        #[arg(long)]
        with_optiscaler: bool,
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// Import a game registration from TOML
    Import {
        path: PathBuf,
        #[arg(long)]
        force: bool,
    },
    #[allow(clippy::doc_markdown)]
    /// Import OptiScaler profiles from TOML for a game
    ImportProfile {
        path: PathBuf,
        #[arg(long = "for")]
        game: String,
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum BackupAction {
    /// Create a backup of a mod
    Create { mod_id: String },
    /// Restore a mod from its latest backup
    Restore { mod_id: String },
    /// List available backups for a mod
    List { mod_id: String },
    /// Backup current plugin load order
    Plugins {
        #[arg(long)]
        profile: String,
        #[arg(long)]
        game: String,
    },
    /// Restore plugin load order from backup
    RestorePlugins {
        #[arg(long)]
        profile: String,
        #[arg(long)]
        game: String,
    },
}

#[derive(Subcommand)]
enum ProfileAction {
    /// List all profiles
    List {
        /// Filter by game
        #[arg(long)]
        game: Option<String>,
    },
    /// Switch to a profile (swaps saves automatically)
    Switch {
        name: String,
        #[arg(long)]
        game: String,
    },
    /// Create a new profile
    Create {
        name: String,
        #[arg(long)]
        game: String,
    },
    /// Delete a profile
    Delete {
        name: String,
        #[arg(long)]
        game: Option<String>,
    },
    /// Experiment with a profile (can be stacked, like git branches)
    Try {
        name: String,
        #[arg(long)]
        game: String,
    },
    /// Roll back to the previous profile (undo the last `try`)
    Rollback {
        #[arg(long)]
        game: String,
    },
    /// Accept the current experiment, clearing the rollback stack
    Commit {
        #[arg(long)]
        game: String,
    },
    /// Show the active profile for a game
    Active {
        #[arg(long)]
        game: String,
    },
    /// Fork a profile (clone mods + saves into a new profile)
    Fork {
        /// Source profile to clone from
        source: String,
        /// Name for the new profile
        name: String,
        #[arg(long)]
        game: String,
        /// Fork unlocked: strip the profile-level load order lock AND
        /// all per-mod pins from the new profile. Use this when you
        /// want to diverge from a Wabbajack / Collection install and
        /// freely reorder mods in the fork.
        #[arg(long)]
        unlock: bool,
    },
    /// Apply a manual profile-level load order lock
    Lock {
        name: String,
        #[arg(long)]
        game: Option<String>,
        /// Optional free-text note explaining why
        #[arg(long)]
        note: Option<String>,
    },
    /// Clear the profile-level load order lock
    Unlock {
        name: String,
        #[arg(long)]
        game: Option<String>,
    },
    /// Show lock status for a profile
    LockInfo {
        name: String,
        #[arg(long)]
        game: Option<String>,
    },
    /// Pin an individual mod in place (per-mod lock).
    LockMod {
        /// Profile name
        name: String,
        /// Mod ID to pin
        mod_id: String,
        #[arg(long)]
        game: Option<String>,
        /// Optional free-text note explaining why
        #[arg(long)]
        note: Option<String>,
    },
    /// Release an individual mod's per-mod pin.
    UnlockMod {
        /// Profile name
        name: String,
        /// Mod ID to unpin
        mod_id: String,
        #[arg(long)]
        game: Option<String>,
    },
    /// Detect (and optionally remove) filesystem-scanner rows in a
    /// profile that duplicate mods the Wabbajack manifest already
    /// installs. See `plans/greedy-shimmying-pine.md` for background.
    ///
    /// Two modes:
    ///   * Without `--manifest`: layer-1 heuristic — list any
    ///     filesystem-scanner rows (cet/*, reds/*, tweak/*, archive/*,
    ///     redmod/*) on a locked profile. Read-only; a no-`--apply`
    ///     report of "suspects".
    ///   * With `--manifest <path>`: layer-2 classification — use the
    ///     manifest's install directives to classify each suspect as
    ///     LEAKED (safe to delete) or GENUINE (user addition, keep).
    ///     Pass `--apply` to delete the LEAKED rows.
    Dedup {
        /// Profile name
        name: String,
        #[arg(long)]
        game: Option<String>,
        /// Path to a .wabbajack file to use as the authoritative
        /// reference for classification. If omitted, only the
        /// layer-1 heuristic runs.
        #[arg(long)]
        manifest: Option<PathBuf>,
        /// Actually delete the rows classified as LEAKED. Without this
        /// flag the command is a dry-run report.
        #[arg(long)]
        apply: bool,
    },
}

#[derive(Subcommand)]
enum ModAction {
    /// Remove an installed mod from a profile and unlink its staged
    /// files. Uses the V8 `installed_mod_files` manifest so removal is
    /// precise — no orphaned files, no collateral damage.
    Remove {
        /// Mod id as stored in the profile (usually
        /// `<domain>_<mod_id>_<file_id>` for Nexus installs).
        mod_id: String,
        /// Profile to remove from. Defaults to the active / unambiguous
        /// one.
        #[arg(long)]
        profile: Option<String>,
    },
    /// Print the skill dossier path and inline prompt for a mod whose
    /// install type could not be detected. Handy for piping into
    /// `claude` or pasting into a chat manually.
    Diagnose { mod_id: String },
}

#[derive(Subcommand)]
enum InstallSource {
    /// Install a Nexus Collection
    NexusCollection {
        slug: String,
        #[arg(long)]
        version: Option<String>,
        #[arg(long)]
        profile: Option<String>,
    },
    /// Install from a Wabbajack modlist
    Wabbajack {
        path: PathBuf,
        #[arg(long)]
        profile: Option<String>,
        /// Game installation directory to deploy mods into
        #[arg(long)]
        game_dir: Option<PathBuf>,
        /// Force full reinstall, skipping preflight checks
        #[arg(long, default_value_t = false)]
        force: bool,
        /// Stage the modlist into modde's data directory but skip the final copy
        /// into `--game-dir`. Useful for Stock-Game lists that should not write
        /// into the live game install.
        #[arg(long, default_value_t = false)]
        no_deploy: bool,
        /// Log per-archive failures (downloads, missing files, broken upstream
        /// links) instead of aborting. The install proceeds as far as possible
        /// and the operator can drop manually-fetched archives into the store
        /// before re-running.
        #[arg(long, default_value_t = false)]
        continue_on_error: bool,
        /// Explicitly discard existing Wabbajack staging before installing.
        #[arg(long, default_value_t = false)]
        reset_staging: bool,
        /// Skip staging validation before deploy.
        #[arg(long, default_value_t = false)]
        skip_validate: bool,
        /// Write Wabbajack apply diagnostics JSONL to this directory.
        #[arg(long)]
        diagnostics_dir: Option<PathBuf>,
        /// Diagnostics heartbeat interval in seconds.
        #[arg(long, default_value_t = 30)]
        diagnostics_interval: u64,
        /// Warn when apply makes no batch/sentinel progress for this many seconds.
        #[arg(long, default_value_t = 600)]
        stall_warn_seconds: u64,
        /// Abort when stalled this long and cgroup memory/swap are saturated.
        #[arg(long, default_value_t = 1800)]
        stall_abort_seconds: u64,
        /// Source archive retention after successful archive-batch integration.
        #[arg(long, value_enum, default_value_t = WabbajackArchiveRetentionArg::Keep)]
        archive_retention: WabbajackArchiveRetentionArg,
        /// Behavior when optional manual/Nexus Wabbajack archives are missing.
        #[arg(long, value_enum, default_value_t = WabbajackMissingArchivePolicyArg::Fail)]
        missing_archive_policy: WabbajackMissingArchivePolicyArg,
        /// Frontload assisted manual archive acquisition before applying.
        #[arg(long, default_value_t = false)]
        acquire_missing: bool,
        /// Browser download directory to watch during assisted acquisition.
        #[arg(long)]
        acquire_download_dir: Option<PathBuf>,
        /// Per-archive assisted acquisition timeout in seconds.
        #[arg(long, default_value_t = 900)]
        acquire_timeout: u64,
        /// Include Nexus archives in frontloaded acquisition.
        #[arg(long, default_value_t = false)]
        acquire_include_nexus: bool,
        /// Use controlled Chromium tabs for frontloaded acquisition.
        #[arg(long, default_value_t = false)]
        acquire_browser_controller: bool,
        /// Disable automatic frontloaded manual archive acquisition.
        #[arg(long, default_value_t = false)]
        no_acquire_missing: bool,
    },
    /// Install a single mod from Nexus
    Mod {
        url: String,
        #[arg(long)]
        profile: Option<String>,
        /// Path to a FOMOD declarative config (TOML or JSON) for non-interactive installation
        #[arg(long)]
        fomod_config: Option<String>,
    },
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum WabbajackArchiveRetentionArg {
    Keep,
    PruneApplied,
    Auto,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum WabbajackMissingArchivePolicyArg {
    Fail,
    OmitFiles,
    OmitMods,
}

impl From<WabbajackMissingArchivePolicyArg>
    for modde_sources::wabbajack::impact::MissingArchivePolicy
{
    fn from(value: WabbajackMissingArchivePolicyArg) -> Self {
        match value {
            WabbajackMissingArchivePolicyArg::Fail => Self::Fail,
            WabbajackMissingArchivePolicyArg::OmitFiles => Self::OmitFiles,
            WabbajackMissingArchivePolicyArg::OmitMods => Self::OmitMods,
        }
    }
}

impl From<WabbajackArchiveRetentionArg>
    for modde_sources::wabbajack::installer::ArchiveRetentionPolicy
{
    fn from(value: WabbajackArchiveRetentionArg) -> Self {
        match value {
            WabbajackArchiveRetentionArg::Keep => Self::Keep,
            WabbajackArchiveRetentionArg::PruneApplied => Self::PruneApplied,
            WabbajackArchiveRetentionArg::Auto => Self::Auto,
        }
    }
}

#[derive(Subcommand)]
enum NexusAction {
    /// Save API key to keyring
    Auth,
    /// Show API key validity and premium status
    Status,
}

#[derive(Subcommand)]
enum FomodAction {
    /// Generate a declarative FOMOD config template from a mod's ModuleConfig.xml
    Generate {
        /// Path to the mod directory containing fomod/ModuleConfig.xml
        mod_path: String,
        /// Include all plugins (not just defaults)
        #[arg(long)]
        all: bool,
        /// Output format: toml, json, or nix
        #[arg(long, default_value = "toml")]
        format: String,
    },
    /// Apply a declarative FOMOD config non-interactively
    Apply {
        /// Path to the mod directory
        mod_path: String,
        /// Path to the declarative config (TOML or JSON)
        #[arg(long)]
        config: String,
        /// Destination directory for installed files
        #[arg(long)]
        dest: String,
    },
    /// Inspect a mod's FOMOD steps, groups, and plugins
    Inspect {
        /// Path to the mod directory containing fomod/ModuleConfig.xml
        mod_path: String,
    },
}

#[derive(Subcommand)]
enum StockAction {
    /// Create a vanilla game snapshot
    Snapshot { game_id: String },
    /// Verify snapshot integrity
    Verify { game_id: String },
}

#[derive(Subcommand)]
enum UpdateAction {
    /// Check for updates on Nexus Mods
    Check {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
        /// Time period to check: "1d", "1w", or "1m"
        #[arg(long, default_value = "1w")]
        period: String,
        /// Check Nexus-tracked profile mods instead of modde itself.
        #[arg(long)]
        mods: bool,
    },
    /// Download and install the latest MAIN file for any tracked mod
    /// in the profile that has a newer version on Nexus.
    ///
    /// Refuses to run on locked profiles (Wabbajack / Collection /
    /// TOML import) unless `--confirm-locked` is passed — the lock
    /// exists precisely to prevent the load order drifting away from
    /// its authoritative source. Mods whose semver major bumps are
    /// flagged "breaking" and require `--accept-breaking` plus a
    /// secondary y/N confirmation per mod.
    Apply {
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
        /// Time period to scan: "1d", "1w", or "1m"
        #[arg(long, default_value = "1w")]
        period: String,
        /// Print the mods that would be updated without downloading.
        #[arg(long)]
        dry_run: bool,
        /// Acknowledge that the profile is locked (Wabbajack / Collection
        /// / TOML import) and that updating drifts it away from the
        /// authoritative source. Required for any locked profile.
        #[arg(long)]
        confirm_locked: bool,
        /// Permit applying updates that look like breaking semver bumps
        /// (major version change). Each breaking mod still requires an
        /// interactive y/N confirmation.
        #[arg(long)]
        accept_breaking: bool,
        /// Skip interactive prompts (assume "yes" to per-mod breaking
        /// confirmations). Refuses any breaking update unless
        /// `--accept-breaking` is also set.
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum LootAction {
    /// Sort plugins using LOOT masterlist rules
    Sort {
        #[arg(long)]
        game: String,
        /// Path to game Data directory (auto-detected if omitted)
        #[arg(long)]
        data_dir: Option<PathBuf>,
    },
    /// Validate plugins for Form 43 and missing master errors
    Validate {
        #[arg(long)]
        game: String,
    },
}

#[derive(Subcommand)]
enum ToolAction {
    /// Run an external tool with overwrite capture
    Run {
        /// Path to executable
        executable: PathBuf,
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game: Option<String>,
        /// Arguments to pass to the tool
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Save a named executable launch target for a game
    AddExecutable {
        /// Display name, e.g. `xEdit` or `BodySlide`
        name: String,
        /// Path to executable
        executable: PathBuf,
        #[arg(long)]
        game: String,
        /// Working directory. Defaults to the detected game install directory.
        #[arg(long)]
        working_dir: Option<PathBuf>,
        /// Output mod for captured files. Defaults to __overwrite__.
        #[arg(long, default_value = "__overwrite__")]
        output_mod: String,
        /// Wine DLL overrides, e.g. dinput8=n,b;winmm=n,b
        #[arg(long)]
        wine_dll_overrides: Option<String>,
        /// Environment variable assignments, KEY=VALUE
        #[arg(long = "env")]
        environment: Vec<String>,
        /// Default arguments to pass when running this executable
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// List saved executable launch targets for a game
    ListExecutables {
        #[arg(long)]
        game: String,
    },
    /// Remove a saved executable launch target
    RemoveExecutable {
        name: String,
        #[arg(long)]
        game: String,
    },
    /// Run a saved executable launch target with overwrite capture
    RunExecutable {
        name: String,
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: Option<String>,
        /// Additional arguments appended after the saved defaults
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// List detected tools for a game
    List {
        #[arg(long)]
        game: String,
    },
    /// Show status of all gaming tools/overlays for a game
    Status {
        #[arg(long)]
        game: String,
    },
    /// Enable a gaming tool/overlay for a game
    Enable {
        /// Tool ID (mangohud, vkbasalt, gamemode, reshade, optiscaler, proton)
        tool_id: String,
        #[arg(long)]
        game: String,
    },
    /// Disable a gaming tool/overlay for a game
    Disable {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
    },
    /// Configure a gaming tool's settings
    Configure {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
        /// Setting key=value pairs
        #[arg(last = true)]
        settings: Vec<String>,
    },
    /// Apply tool patches to the game directory (`ReShade` DLLs, `OptiScaler`, etc.)
    Apply {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
    },
    /// Revert tool patches from the game directory
    Revert {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
    },
    /// List releases for a release-backed tool
    Releases {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
    },
    /// Install a specific release asset for a release-backed tool
    InstallRelease {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
        #[arg(long)]
        tag: String,
        #[arg(long)]
        asset: String,
    },
    /// Install a specific release asset from a local path for a release-backed tool
    InstallReleaseFromPath {
        /// Tool ID
        tool_id: String,
        #[arg(long)]
        game: String,
        #[arg(long)]
        tag: String,
        #[arg(long)]
        asset: String,
        /// Local path to the already-downloaded asset
        path: PathBuf,
    },
}

#[derive(Subcommand)]
enum NxmAction {
    /// Handle an nxm:// download URI
    Handle {
        /// The nxm:// URI
        uri: String,
        #[arg(long)]
        profile: Option<String>,
    },
    /// Install the nxm:// URI handler for your desktop
    Install,
}

#[derive(Subcommand)]
pub enum WabbajackAction {
    /// Search public Wabbajack modlist catalogs
    Search {
        query: Option<String>,
        #[arg(long)]
        game: Option<String>,
        /// Catalog source: official, authored, or both
        #[arg(long, default_value = "both")]
        source: String,
        #[arg(long)]
        json: bool,
    },
    /// Download a .wabbajack file by URL, machine URL, or title
    Download {
        url_or_machine_url: String,
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// Generate a Home Manager profile snippet for a .wabbajack source
    HmSnippet {
        url_or_file: String,
        #[arg(long)]
        profile: String,
        #[arg(long)]
        game: String,
        #[arg(long)]
        game_dir: Option<PathBuf>,
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// Import local archives into the modde store by matching Wabbajack hashes
    ImportArchive {
        manifest: PathBuf,
        archives: Vec<PathBuf>,
    },
    /// Open manual Wabbajack archive pages and import matching browser downloads
    AcquireMissing {
        manifest: PathBuf,
        #[arg(long)]
        download_dir: Option<PathBuf>,
        #[arg(long)]
        data_dir: Option<PathBuf>,
        #[arg(long)]
        browser_profile: Option<PathBuf>,
        #[arg(long, default_value_t = false)]
        include_nexus: bool,
        #[arg(long, default_value_t = false)]
        browser_controller: bool,
        #[arg(long, default_value_t = 900)]
        timeout: u64,
        #[arg(long, default_value_t = false)]
        json: bool,
    },
    /// Report missing manual/Nexus archives and their install impact
    MissingImpact {
        manifest: PathBuf,
        #[arg(long)]
        data_dir: Option<PathBuf>,
        #[arg(long)]
        json: bool,
        /// Print Home Manager manualArchives entries for missing archives.
        #[arg(long)]
        nix_snippet: bool,
    },
    /// Print missing manual archive URLs that require operator visits
    ManualLinks {
        manifest: PathBuf,
        #[arg(long)]
        data_dir: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    /// Assess readiness for a large Wabbajack install without mutating state
    Assess {
        manifest: PathBuf,
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        game_dir: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    /// Summarize Wabbajack diagnostics JSONL from a previous install run
    AnalyzeDiagnostics {
        diagnostics_dir: PathBuf,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum SaveAction {
    /// Assign a save to a profile
    Assign {
        /// Path to the save file or directory
        path: PathBuf,
        #[arg(long)]
        profile: String,
        #[arg(long)]
        game: Option<String>,
        /// Optional label for this save
        #[arg(long)]
        label: Option<String>,
    },
    /// Remove a save assignment
    Unassign {
        /// Path to the save file or directory
        path: PathBuf,
    },
    /// List saves for a profile
    List {
        #[arg(long)]
        profile: String,
        #[arg(long)]
        game: Option<String>,
    },
    /// Scan for unassigned saves
    Scan {
        #[arg(long)]
        game: String,
    },
    /// Adopt existing saves from the game directory into a profile's vault
    Adopt {
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: String,
    },
    /// Capture current saves into the vault (creates a new snapshot)
    Capture {
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: String,
        /// Optional message for this snapshot
        #[arg(short, long)]
        message: Option<String>,
    },
    /// Show save snapshot history for a profile
    History {
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: String,
        /// Max entries to show
        #[arg(long, default_value = "20")]
        limit: usize,
    },
    /// Restore saves from a specific snapshot
    Restore {
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: String,
        /// Commit ID (or prefix) to restore
        commit: String,
    },
    /// Auto-detect and capture new saves (called by launch wrapper on game exit)
    AutoCapture {
        #[arg(long)]
        game: String,
        /// Profile to capture into (defaults to active profile)
        #[arg(long)]
        profile: Option<String>,
    },
    /// Watch for save changes and auto-capture (polling)
    Watch {
        #[arg(long)]
        game: String,
        #[arg(long)]
        profile: Option<String>,
        /// Poll interval in seconds
        #[arg(long, default_value = "30")]
        interval: u64,
    },
}

fn main() -> Result<()> {
    #[cfg(not(feature = "remote-telemetry"))]
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    #[cfg(feature = "remote-telemetry")]
    let telemetry_runtime = tokio::runtime::Runtime::new()?;
    #[cfg(feature = "remote-telemetry")]
    let _telemetry_runtime_guard = telemetry_runtime.enter();
    #[cfg(feature = "remote-telemetry")]
    init_tracing()?;
    #[cfg(feature = "remote-telemetry")]
    init_remote_telemetry(&telemetry_runtime)?;

    let cli = Cli::parse();
    #[cfg(feature = "remote-telemetry")]
    {
        assert!(!cli.debug_panic, "remote telemetry debug panic");
    }

    let _heap_profiler = start_heap_profiler(cli.heap_profile.as_deref())?;

    if let Some(dir) = cli.data_dir.clone() {
        modde_core::paths::set_data_dir(dir);
    }

    // GUI launches its own runtime (iced), so handle it outside tokio.
    if matches!(cli.command, Commands::Gui) {
        modde_ui::app::run().map_err(|e| anyhow::anyhow!("GUI error: {e}"))?;
        return Ok(());
    }

    // Whether this command may have mutated the profile DB / store.
    // Used after the dispatch below to push a refresh signal to any
    // running GUI(s). Read-only commands skip the notify so we don't
    // spam GUIs on `modde profile show` or `modde update check`.
    let mutates_state = command_mutates_state(&cli.command);
    let lazy_update_check = !mutates_state && command_runs_lazy_product_update_check(&cli.command);

    let result = run_command(cli);
    if mutates_state && result.is_ok() {
        let _ = modde_core::ipc::notify_refresh();
    }
    if lazy_update_check && result.is_ok() {
        maybe_print_product_update_notice();
    }
    result
}

#[cfg(feature = "remote-telemetry")]
fn init_tracing() -> Result<()> {
    let fmt_layer = tracing_subscriber::fmt::layer();
    let filter = EnvFilter::from_default_env();
    let registry = tracing_subscriber::registry().with(filter).with(fmt_layer);

    if let Some(config) = remote_telemetry_config()? {
        let layer = detritus::Layer::builder()
            .endpoint(config.endpoint.clone())
            .token(config.token.clone())
            .source(config.source.clone())
            .queue_dir(config.logs_dir.clone())
            .build()
            .context("failed to initialize remote telemetry tracing layer")?;

        registry
            .with(layer)
            .try_init()
            .context("failed to initialize tracing subscriber")?;
    } else {
        registry
            .try_init()
            .context("failed to initialize tracing subscriber")?;
    }

    Ok(())
}

#[cfg(feature = "remote-telemetry")]
#[derive(Clone)]
struct RemoteTelemetryConfig {
    endpoint: url::Url,
    token: secrecy::SecretString,
    source: detritus::SourceId,
    logs_dir: PathBuf,
    crashes_dir: PathBuf,
}

#[cfg(feature = "remote-telemetry")]
fn remote_telemetry_config() -> Result<Option<RemoteTelemetryConfig>> {
    let Some(endpoint) = env::var("RS_MODDE_TELEMETRY_ENDPOINT").ok() else {
        return Ok(None);
    };
    let Some(token) = env::var("RS_MODDE_TELEMETRY_TOKEN").ok() else {
        return Ok(None);
    };

    let endpoint = url::Url::parse(&endpoint).context("invalid RS_MODDE_TELEMETRY_ENDPOINT")?;
    let source = detritus::SourceId {
        project: "rs-modde".to_owned(),
        platform: target_platform(),
        version: env!("CARGO_PKG_VERSION").to_owned(),
        install_id: telemetry::persistent_install_id()?,
    };
    let telemetry_dir = telemetry::telemetry_dir()?;

    Ok(Some(RemoteTelemetryConfig {
        endpoint,
        token: secrecy::SecretString::from(token),
        source,
        logs_dir: telemetry_dir.join("logs"),
        crashes_dir: telemetry_dir.join("crashes"),
    }))
}

#[cfg(feature = "remote-telemetry")]
fn init_remote_telemetry(runtime: &tokio::runtime::Runtime) -> Result<()> {
    let Some(config) = remote_telemetry_config()? else {
        return Ok(());
    };

    detritus::install_panic_hook(detritus::PanicHookConfig {
        endpoint: config.endpoint.clone(),
        token: config.token.clone(),
        source: config.source.clone(),
        spool_dir: config.crashes_dir.clone(),
        kind: detritus::PanicKind::PanicTarball,
        build: detritus_protocol::BuildInfo {
            git_sha: option_env!("MODDE_GIT_SHA").unwrap_or("unknown").to_owned(),
            profile: option_env!("PROFILE").unwrap_or("unknown").to_owned(),
            target_triple: target_platform(),
        },
        context: serde_json::json!({}),
        sent_retention_days: 90,
    })
    .context("failed to install remote telemetry panic hook")?;

    let ship_result = runtime.block_on(async {
        tokio::time::timeout(
            Duration::from_secs(3),
            detritus::ship_pending_crashes(
                &config.crashes_dir,
                config.endpoint.clone(),
                config.token.clone(),
            ),
        )
        .await
    });

    match ship_result {
        Ok(Ok(_)) => {}
        Ok(Err(error)) => tracing::warn!(%error, "failed to ship pending remote telemetry crashes"),
        Err(_) => tracing::warn!("timed out shipping pending remote telemetry crashes"),
    }

    Ok(())
}

#[cfg(feature = "remote-telemetry")]
fn target_platform() -> String {
    format!("{}-{}", env::consts::ARCH, env::consts::OS)
}

#[cfg(feature = "heap-profile")]
fn start_heap_profiler(path: Option<&std::path::Path>) -> Result<Option<()>> {
    if let Some(path) = path {
        anyhow::bail!(
            "--heap-profile={} is not available in this build because the `turso` dependency already defines the process global allocator; use `--diagnostics-dir` for bounded-memory telemetry",
            path.display()
        );
    }
    Ok(None)
}

#[cfg(not(feature = "heap-profile"))]
fn start_heap_profiler(path: Option<&std::path::Path>) -> Result<Option<()>> {
    if let Some(path) = path {
        anyhow::bail!(
            "--heap-profile={} requires building modde-cli with `--features heap-profile`",
            path.display()
        );
    }
    Ok(None)
}

fn run_command(cli: Cli) -> Result<()> {
    // Sync commands that don't need the tokio runtime
    match cli.command {
        Commands::Dev {
            action: DevAction::ExportToolSchema { out },
        } => return commands::nix_schema::handle_export(&out),
        Commands::Profile { action } => return commands::profile::handle(action),
        Commands::Scan {
            game,
            game_dir,
            manifest,
            import_to,
            threshold,
            dry_run,
            prune_duplicates,
        } => {
            return commands::scan::handle(
                game,
                game_dir,
                manifest,
                import_to,
                threshold,
                dry_run,
                prune_duplicates,
            );
        }
        Commands::Diagnostics { game, profile } => {
            return commands::diagnostics::handle(&game, profile);
        }
        Commands::Export {
            profile,
            game,
            columns,
            output,
        } => {
            return commands::export::handle(profile, game, columns, output);
        }
        Commands::Backup { action } => {
            return commands::backup::handle(action);
        }
        Commands::Detect => return commands::detect::handle(),
        Commands::Game {
            action: GameAction::List,
        } => return commands::game::handle_list(),
        Commands::Game {
            action: GameAction::Remove { id, yes },
        } => return commands::game::handle_remove(&id, yes),
        Commands::Game {
            action: GameAction::Detect { install_path },
        } => return commands::game::handle_detect(install_path),
        Commands::Game {
            action: GameAction::Show { id },
        } => return commands::game::handle_show(&id),
        Commands::Game {
            action:
                GameAction::Export {
                    id,
                    with_optiscaler,
                    output,
                },
        } => return commands::game::handle_export(&id, with_optiscaler, output),
        Commands::Game {
            action: GameAction::Import { path, force },
        } => return commands::game::handle_import(path, force),
        Commands::Game {
            action: GameAction::ImportProfile { path, game, force },
        } => return commands::game::handle_import_profile(path, game, force),
        Commands::Instance { action } => {
            return match action {
                InstanceAction::Create { name, data_dir } => {
                    commands::instance::handle_create(&name, data_dir)
                }
                InstanceAction::List => commands::instance::handle_list(),
                InstanceAction::Switch { name } => commands::instance::handle_switch(&name),
            };
        }
        Commands::Import => return commands::import::handle(),
        Commands::Fomod { action } => return commands::fomod::handle(action),
        Commands::Loot { action } => {
            return match action {
                LootAction::Sort { game, data_dir } => commands::loot::handle_sort(&game, data_dir),
                LootAction::Validate { game } => commands::loot::handle_validate(&game),
            };
        }
        Commands::Tool {
            action: ToolAction::List { game },
        } => {
            return commands::tool::handle_list(&game);
        }
        Commands::Tool {
            action: ToolAction::Status { game },
        } => {
            return commands::tool::handle_status(&game);
        }
        Commands::Tool {
            action: ToolAction::Enable { tool_id, game },
        } => {
            return commands::tool::handle_enable(&tool_id, &game);
        }
        Commands::Tool {
            action: ToolAction::Disable { tool_id, game },
        } => {
            return commands::tool::handle_disable(&tool_id, &game);
        }
        Commands::Tool {
            action:
                ToolAction::Configure {
                    tool_id,
                    game,
                    settings,
                },
        } => {
            return commands::tool::handle_configure(&tool_id, &game, &settings);
        }
        Commands::Tool {
            action: ToolAction::Apply { tool_id, game },
        } => {
            return commands::tool::handle_apply(&tool_id, &game);
        }
        Commands::Tool {
            action: ToolAction::Revert { tool_id, game },
        } => {
            return commands::tool::handle_revert(&tool_id, &game);
        }
        Commands::Nxm {
            action: NxmAction::Install,
        } => {
            commands::nxm::install_handler()?;
            return Ok(());
        }
        Commands::Exec {
            action:
                ExecAction::Add {
                    name,
                    executable,
                    game,
                    working_dir,
                    output_mod,
                    wine_dll_overrides,
                    environment,
                    args,
                },
        } => {
            return commands::tool::handle_add_executable(
                &name,
                executable,
                &game,
                working_dir,
                &output_mod,
                wine_dll_overrides,
                &environment,
                &args,
            );
        }
        Commands::Exec {
            action: ExecAction::List { game },
        } => {
            return commands::tool::handle_list_executables(&game);
        }
        Commands::Exec {
            action: ExecAction::Remove { name, game },
        } => {
            return commands::tool::handle_remove_executable(&name, &game);
        }
        Commands::Skill { action } => {
            return commands::skill::handle(action);
        }
        Commands::Wabbajack { .. } => {}
        _ => {}
    }

    tokio::runtime::Runtime::new()?.block_on(async {
        match cli.command {
            Commands::Play {
                profile,
                game,
                no_deploy,
                no_switch,
                no_capture,
            } => commands::play::handle(profile, game, no_deploy, no_switch, no_capture).await?,
            Commands::Deploy { profile, game } => commands::deploy::handle(profile, game).await?,
            Commands::Collisions {
                profile,
                game,
                all,
                suggest_hides,
            } => commands::collisions::handle(profile, game, all, suggest_hides).await?,
            Commands::Rollback { profile, game } => {
                commands::rollback::handle(profile, game).await?;
            }
            Commands::Install { source } => commands::install::handle(source).await?,
            Commands::Mod { action } => match action {
                ModAction::Remove { mod_id, profile } => {
                    commands::uninstall::handle(mod_id, profile).await?;
                }
                ModAction::Diagnose { mod_id } => {
                    commands::uninstall::handle_diagnose(mod_id).await?;
                }
            },
            Commands::Verify { profile, game } => commands::verify::handle(profile, game).await?,
            Commands::Nexus { action } => commands::nexus::handle(action).await?,
            Commands::Stock { action } => commands::stock::handle(action).await?,
            Commands::Save { action } => commands::save::handle(action).await?,
            Commands::Game {
                action:
                    GameAction::Add {
                        id,
                        display_name,
                        executable_dir,
                        steam_app_id,
                        install_dir_name,
                        mod_dir,
                        nexus_domain,
                        proxy_dlls,
                        force,
                    },
            } => {
                commands::game::handle_add(commands::game::AddGameArgs {
                    id,
                    display_name,
                    executable_dir,
                    steam_app_id,
                    install_dir_name,
                    mod_dir,
                    nexus_domain,
                    proxy_dlls,
                    force,
                })
                .await?;
            }
            Commands::Update { action } => match action {
                UpdateAction::Check {
                    profile,
                    game,
                    period,
                    mods,
                } => {
                    if mods || profile.is_some() || game.is_some() {
                        commands::update::handle_check(profile, game, period).await?;
                    } else {
                        commands::update::handle_product_check().await?;
                    }
                }
                UpdateAction::Apply {
                    profile,
                    game,
                    period,
                    dry_run,
                    confirm_locked,
                    accept_breaking,
                    yes,
                } => {
                    commands::update::handle_apply(commands::update::ApplyOptions {
                        profile_name: profile,
                        game_id: game,
                        period,
                        dry_run,
                        safety: commands::update::ApplySafety {
                            confirm_locked,
                            accept_breaking,
                            yes,
                        },
                    })
                    .await?;
                }
            },
            Commands::Tool { action } => match action {
                ToolAction::Run {
                    executable,
                    profile,
                    game,
                    args,
                } => commands::tool::handle_run(executable, args, profile, game).await?,
                ToolAction::AddExecutable {
                    name,
                    executable,
                    game,
                    working_dir,
                    output_mod,
                    wine_dll_overrides,
                    environment,
                    args,
                } => {
                    commands::tool::handle_add_executable(
                        &name,
                        executable,
                        &game,
                        working_dir,
                        &output_mod,
                        wine_dll_overrides,
                        &environment,
                        &args,
                    )?;
                }
                ToolAction::ListExecutables { game } => {
                    commands::tool::handle_list_executables(&game)?;
                }
                ToolAction::RemoveExecutable { name, game } => {
                    commands::tool::handle_remove_executable(&name, &game)?;
                }
                ToolAction::RunExecutable {
                    name,
                    game,
                    profile,
                    args,
                } => {
                    commands::tool::handle_run_executable(&name, &game, profile, args).await?;
                }
                ToolAction::Releases { tool_id, game } => {
                    commands::tool::handle_releases(&tool_id, &game).await?;
                }
                ToolAction::InstallRelease {
                    tool_id,
                    game,
                    tag,
                    asset,
                } => {
                    commands::tool::handle_install_release(&tool_id, &game, &tag, &asset).await?;
                }
                ToolAction::InstallReleaseFromPath {
                    tool_id,
                    game,
                    tag,
                    asset,
                    path,
                } => {
                    commands::tool::handle_install_release_from_path(
                        &tool_id, &game, &tag, &asset, path,
                    )
                    .await?;
                }
                ToolAction::List { .. }
                | ToolAction::Status { .. }
                | ToolAction::Enable { .. }
                | ToolAction::Disable { .. }
                | ToolAction::Configure { .. }
                | ToolAction::Apply { .. }
                | ToolAction::Revert { .. } => {
                    unreachable!(
                        "these ToolAction variants are dispatched in the pre-tokio sync block"
                    )
                }
            },
            Commands::Nxm { action } => match action {
                NxmAction::Handle { uri, profile } => commands::nxm::handle(uri, profile).await?,
                NxmAction::Install => {
                    unreachable!("NxmAction::Install is dispatched in the pre-tokio sync block")
                }
            },
            Commands::Exec { action } => match action {
                ExecAction::Run {
                    name,
                    game,
                    profile,
                    args,
                } => {
                    commands::tool::handle_run_executable(&name, &game, profile, args).await?;
                }
                // Sync arms handled in the pre-tokio block above.
                ExecAction::Add { .. } | ExecAction::List { .. } | ExecAction::Remove { .. } => {
                    unreachable!("Exec sync arms are dispatched in the pre-tokio block above")
                }
            },
            Commands::Wabbajack { action } => commands::wabbajack::handle(action).await?,
            // Already handled above
            Commands::Profile { .. }
            | Commands::Dev { .. }
            | Commands::Scan { .. }
            | Commands::Detect
            | Commands::Game { .. }
            | Commands::Import
            | Commands::Instance { .. }
            | Commands::Backup { .. }
            | Commands::Diagnostics { .. }
            | Commands::Export { .. }
            | Commands::Fomod { .. }
            | Commands::Loot { .. }
            | Commands::Skill { .. }
            | Commands::Gui => {
                unreachable!("these commands are dispatched before the async runtime block")
            }
        }
        Ok(())
    })
}

/// `true` when the command mutates persistent profile / store / DB
/// state and a running GUI should re-read the DB after it finishes.
///
/// Centralized so we have one place to audit. Read-only commands
/// (`Detect`, `Diagnostics`, `Export`, `Verify`, `update check`, …)
/// return `false` to avoid spamming GUIs with no-op refreshes.
fn command_mutates_state(cmd: &Commands) -> bool {
    match cmd {
        // Pure read paths.
        Commands::Dev { .. }
        | Commands::Detect
        | Commands::Diagnostics { .. }
        | Commands::Export { .. }
        | Commands::Verify { .. }
        | Commands::Collisions { .. }
        | Commands::Gui => false,

        Commands::Game { action } => {
            matches!(
                action,
                GameAction::Add { .. }
                    | GameAction::Remove { .. }
                    | GameAction::Import { .. }
                    | GameAction::ImportProfile { .. }
            )
        }

        // `update check` is read-only; `update apply` mutates.
        Commands::Update { action } => matches!(action, UpdateAction::Apply { .. }),

        // `instance list` is read-only; create/switch flip the active
        // data dir.
        Commands::Instance { action } => !matches!(action, InstanceAction::List),

        // Loot validate just reports, sort rewrites the load order.
        Commands::Loot { action } => matches!(action, LootAction::Sort { .. }),

        // Tool subcommands: queries are read-only, everything else
        // mutates per-game tool config rows.
        Commands::Tool { action } => !matches!(
            action,
            ToolAction::List { .. }
                | ToolAction::Status { .. }
                | ToolAction::Releases { .. }
                | ToolAction::ListExecutables { .. }
        ),

        // Exec is the alias for tool's executable subset. List is a
        // read-only query; the others mutate or run a child process
        // whose overwrite-capture writes to the store.
        Commands::Exec { action } => !matches!(action, ExecAction::List { .. }),

        // Skill list/path are read-only; install writes files under the
        // user-global `.agents/skills` tree.
        Commands::Skill { action } => matches!(action, SkillAction::Install { .. }),

        // Nexus: `auth` writes the API key, `status` prints validity.
        // The status arm doesn't mutate, but the GUI surfaces auth
        // state — a refresh is harmless and cheap. Notify on either.
        Commands::Nexus { .. } => true,

        // `mod diagnose` only prints the dossier; remove mutates.
        Commands::Mod { action } => matches!(action, ModAction::Remove { .. }),

        // `wabbajack search` / `download` / `hm-snippet` / `assess` /
        // `missing-impact` / `manual-links` are read-only;
        // import/acquire commands write into the store.
        Commands::Wabbajack { action } => matches!(
            action,
            WabbajackAction::ImportArchive { .. } | WabbajackAction::AcquireMissing { .. }
        ),

        // Save commands cover read-only listing AND mutating
        // capture/restore/adopt; conservatively notify on all of
        // them — the cost is one socket round-trip per active GUI.
        Commands::Save { .. } => true,

        // `nxm install` registers the URI handler (system-side). We
        // still notify so a GUI showing nxm settings can reflect it.
        Commands::Nxm { .. } => true,

        // Stock snapshots affect deploy decisions; treat as mutating.
        Commands::Stock { .. } => true,

        // Backup capture/restore mutates the data dir.
        Commands::Backup { .. } => true,

        // Everything below is unambiguously mutating.
        Commands::Profile { .. }
        | Commands::Scan { .. }
        | Commands::Import
        | Commands::Fomod { .. }
        | Commands::Install { .. }
        | Commands::Deploy { .. }
        | Commands::Rollback { .. }
        | Commands::Play { .. } => true,
    }
}

fn command_runs_lazy_product_update_check(cmd: &Commands) -> bool {
    !matches!(
        cmd,
        Commands::Gui
            | Commands::Dev { .. }
            | Commands::Update {
                action: UpdateAction::Check { .. }
            }
    )
}

fn maybe_print_product_update_notice() {
    let settings = modde_core::settings::AppSettings::load();
    if !modde_core::update_check::update_checks_enabled(&settings) {
        return;
    }

    let Ok(runtime) = tokio::runtime::Runtime::new() else {
        return;
    };
    match runtime.block_on(modde_core::update_check::check_latest_with_settings(
        &settings,
    )) {
        Ok(Some(update)) => {
            eprintln!(
                "modde update available: {} (current: {}) - {}",
                update.latest_version, update.current_version, update.release_url
            );
        }
        Ok(None) => {}
        Err(error) => tracing::debug!(%error, "product update check failed"),
    }
}

#[cfg(test)]
mod mutation_classification_tests {
    //! Tests for [`command_mutates_state`].
    //!
    //! Goal: lock in which commands push a refresh signal to running
    //! GUIs. A wrong classification has user-visible consequences:
    //!
    //! * False negative (mutating cmd marked read-only) → GUI misses
    //!   an update; user sees stale state until they click around.
    //! * False positive (read-only cmd marked mutating) → harmless
    //!   socket round-trip per active GUI, but adds noise.
    //!
    //! When a new top-level [`Commands`] variant is added, the
    //! exhaustive `match` in `command_mutates_state` will not compile
    //! until you classify it — at which point a test in this module
    //! should pin the answer.
    use super::*;
    use std::path::PathBuf;

    fn list_profiles() -> Commands {
        Commands::Profile {
            action: ProfileAction::List { game: None },
        }
    }

    fn create_profile() -> Commands {
        Commands::Profile {
            action: ProfileAction::Create {
                name: "p".into(),
                game: "skyrim-se".into(),
            },
        }
    }

    fn install_mod() -> Commands {
        Commands::Install {
            source: InstallSource::Mod {
                url: "https://www.nexusmods.com/skyrimspecialedition/mods/1".into(),
                profile: None,
                fomod_config: None,
            },
        }
    }

    fn update_check() -> Commands {
        Commands::Update {
            action: UpdateAction::Check {
                profile: None,
                game: None,
                period: "1w".into(),
                mods: false,
            },
        }
    }

    fn update_apply() -> Commands {
        Commands::Update {
            action: UpdateAction::Apply {
                profile: None,
                game: None,
                period: "1w".into(),
                dry_run: false,
                confirm_locked: false,
                accept_breaking: false,
                yes: false,
            },
        }
    }

    fn instance_list() -> Commands {
        Commands::Instance {
            action: InstanceAction::List,
        }
    }

    fn instance_create() -> Commands {
        Commands::Instance {
            action: InstanceAction::Create {
                name: "x".into(),
                data_dir: PathBuf::from("/tmp/x"),
            },
        }
    }

    fn loot_validate() -> Commands {
        Commands::Loot {
            action: LootAction::Validate {
                game: "skyrim-se".into(),
            },
        }
    }

    fn loot_sort() -> Commands {
        Commands::Loot {
            action: LootAction::Sort {
                game: "skyrim-se".into(),
                data_dir: None,
            },
        }
    }

    fn tool_list() -> Commands {
        Commands::Tool {
            action: ToolAction::List {
                game: "skyrim-se".into(),
            },
        }
    }

    fn tool_apply() -> Commands {
        Commands::Tool {
            action: ToolAction::Apply {
                tool_id: "mangohud".into(),
                game: "skyrim-se".into(),
            },
        }
    }

    fn mod_remove() -> Commands {
        Commands::Mod {
            action: ModAction::Remove {
                mod_id: "x".into(),
                profile: None,
            },
        }
    }

    fn mod_diagnose() -> Commands {
        Commands::Mod {
            action: ModAction::Diagnose { mod_id: "x".into() },
        }
    }

    fn wabbajack_search() -> Commands {
        Commands::Wabbajack {
            action: WabbajackAction::Search {
                query: None,
                game: None,
                source: "both".into(),
                json: false,
            },
        }
    }

    fn wabbajack_import() -> Commands {
        Commands::Wabbajack {
            action: WabbajackAction::ImportArchive {
                manifest: PathBuf::from("m.json"),
                archives: vec![],
            },
        }
    }

    fn wabbajack_acquire_missing() -> Commands {
        Commands::Wabbajack {
            action: WabbajackAction::AcquireMissing {
                manifest: PathBuf::from("m.json"),
                download_dir: None,
                data_dir: None,
                browser_profile: None,
                include_nexus: false,
                browser_controller: false,
                timeout: 1,
                json: false,
            },
        }
    }

    fn wabbajack_assess() -> Commands {
        Commands::Wabbajack {
            action: WabbajackAction::Assess {
                manifest: PathBuf::from("list.wabbajack"),
                profile: None,
                game_dir: None,
                json: false,
            },
        }
    }

    fn skill_list() -> Commands {
        Commands::Skill {
            action: SkillAction::List,
        }
    }

    fn skill_install() -> Commands {
        Commands::Skill {
            action: SkillAction::Install {
                name: "all".into(),
                force: false,
            },
        }
    }

    fn game_add() -> Commands {
        Commands::Game {
            action: GameAction::Add {
                id: "custom-game".into(),
                display_name: "Custom Game".into(),
                executable_dir: PathBuf::from("bin"),
                steam_app_id: None,
                install_dir_name: None,
                mod_dir: None,
                nexus_domain: None,
                proxy_dlls: vec![],
                force: false,
            },
        }
    }

    fn game_remove() -> Commands {
        Commands::Game {
            action: GameAction::Remove {
                id: "custom-game".into(),
                yes: false,
            },
        }
    }

    // ── read-only ────────────────────────────────────────────────

    #[test]
    fn detect_is_read_only() {
        assert!(!command_mutates_state(&Commands::Detect));
    }

    #[test]
    fn diagnostics_is_read_only() {
        assert!(!command_mutates_state(&Commands::Diagnostics {
            game: "skyrim-se".into(),
            profile: None,
        }));
    }

    #[test]
    fn export_is_read_only() {
        assert!(!command_mutates_state(&Commands::Export {
            profile: None,
            game: None,
            columns: None,
            output: None,
        }));
    }

    #[test]
    fn verify_is_read_only() {
        assert!(!command_mutates_state(&Commands::Verify {
            profile: None,
            game: None,
        }));
    }

    #[test]
    fn collisions_is_read_only() {
        assert!(!command_mutates_state(&Commands::Collisions {
            profile: None,
            game: None,
            all: false,
            suggest_hides: false,
        }));
    }

    #[test]
    fn gui_is_read_only() {
        // The GUI command launches the GUI itself; pushing to
        // ourselves at startup would be confusing and pointless.
        assert!(!command_mutates_state(&Commands::Gui));
    }

    #[test]
    fn update_check_is_read_only() {
        assert!(!command_mutates_state(&update_check()));
    }

    #[test]
    fn instance_list_is_read_only() {
        assert!(!command_mutates_state(&instance_list()));
    }

    #[test]
    fn loot_validate_is_read_only() {
        assert!(!command_mutates_state(&loot_validate()));
    }

    #[test]
    fn tool_list_is_read_only() {
        assert!(!command_mutates_state(&tool_list()));
    }

    #[test]
    fn mod_diagnose_is_read_only() {
        assert!(!command_mutates_state(&mod_diagnose()));
    }

    #[test]
    fn wabbajack_search_is_read_only() {
        assert!(!command_mutates_state(&wabbajack_search()));
    }

    #[test]
    fn wabbajack_assess_is_read_only() {
        assert!(!command_mutates_state(&wabbajack_assess()));
    }

    #[test]
    fn skill_list_is_read_only() {
        assert!(!command_mutates_state(&skill_list()));
    }

    #[test]
    fn game_list_is_read_only() {
        assert!(!command_mutates_state(&Commands::Game {
            action: GameAction::List,
        }));
    }

    #[test]
    fn game_detect_is_read_only() {
        assert!(!command_mutates_state(&Commands::Game {
            action: GameAction::Detect {
                install_path: PathBuf::from("/games"),
            },
        }));
    }

    #[test]
    fn game_show_is_read_only() {
        assert!(!command_mutates_state(&Commands::Game {
            action: GameAction::Show {
                id: "custom-game".into(),
            },
        }));
    }

    #[test]
    fn game_export_is_read_only() {
        assert!(!command_mutates_state(&Commands::Game {
            action: GameAction::Export {
                id: "custom-game".into(),
                with_optiscaler: false,
                output: None,
            },
        }));
    }

    // ── mutating ─────────────────────────────────────────────────

    #[test]
    fn profile_list_is_mutating() {
        // Pinned as `mutating` in `command_mutates_state` because
        // the dispatcher routes both List and create/delete through
        // the same `commands::profile::handle` and we don't peek
        // inside the action enum. Document that here; if we later
        // refine the classification, flip this assertion.
        assert!(command_mutates_state(&list_profiles()));
    }

    #[test]
    fn profile_create_is_mutating() {
        assert!(command_mutates_state(&create_profile()));
    }

    #[test]
    fn install_is_mutating() {
        assert!(command_mutates_state(&install_mod()));
    }

    #[test]
    fn update_apply_is_mutating() {
        assert!(command_mutates_state(&update_apply()));
    }

    #[test]
    fn instance_create_is_mutating() {
        assert!(command_mutates_state(&instance_create()));
    }

    #[test]
    fn loot_sort_is_mutating() {
        assert!(command_mutates_state(&loot_sort()));
    }

    #[test]
    fn tool_apply_is_mutating() {
        assert!(command_mutates_state(&tool_apply()));
    }

    #[test]
    fn mod_remove_is_mutating() {
        assert!(command_mutates_state(&mod_remove()));
    }

    #[test]
    fn wabbajack_import_archive_is_mutating() {
        assert!(command_mutates_state(&wabbajack_import()));
    }

    #[test]
    fn wabbajack_acquire_missing_is_mutating() {
        assert!(command_mutates_state(&wabbajack_acquire_missing()));
    }

    #[test]
    fn skill_install_is_mutating() {
        assert!(command_mutates_state(&skill_install()));
    }

    #[test]
    fn game_add_is_mutating() {
        assert!(command_mutates_state(&game_add()));
    }

    #[test]
    fn game_remove_is_mutating() {
        assert!(command_mutates_state(&game_remove()));
    }

    #[test]
    fn deploy_is_mutating() {
        assert!(command_mutates_state(&Commands::Deploy {
            profile: None,
            game: None,
        }));
    }

    #[test]
    fn rollback_is_mutating() {
        assert!(command_mutates_state(&Commands::Rollback {
            profile: None,
            game: None,
        }));
    }

    #[test]
    fn import_is_mutating() {
        assert!(command_mutates_state(&Commands::Import));
    }

    #[test]
    fn stock_is_mutating() {
        assert!(command_mutates_state(&Commands::Stock {
            action: StockAction::Snapshot {
                game_id: "skyrim-se".into(),
            },
        }));
    }
}