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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use serde::Serialize;

use modde_core::manifest::wabbajack::{ArchiveState, RawDirective, WabbajackManifest};
use modde_sources::DownloadSource;
use modde_sources::wabbajack::acquire::{
    AcquireResult, AcquireStatus, DirectAcquireOutcome, MissingArchive as AcquireMissingArchive,
    MissingArchiveSourceKind, import_acquired_archive, missing_archives, try_acquire_manual_direct,
    wait_for_matching_download, wait_for_next_matching_download,
};
use modde_sources::wabbajack::catalog::{
    CatalogFilter, CatalogSource, download_wabbajack_file, fetch_catalog, filter_entries,
    find_entry, hm_snippet_for_source, resolve_download_target,
};
use modde_sources::wabbajack::impact::MissingArchiveImpact;
use modde_sources::wabbajack::import::{ArchiveImportStatus, import_archives};
use modde_sources::wabbajack::runner::parse_wabbajack_manifest;

use crate::WabbajackAction;

pub async fn handle(action: WabbajackAction) -> Result<()> {
    match action {
        WabbajackAction::Search {
            query,
            game,
            source,
            json,
        } => search(query, game, source, json).await,
        WabbajackAction::Download {
            url_or_machine_url,
            output,
        } => download(url_or_machine_url, output).await,
        WabbajackAction::HmSnippet {
            url_or_file,
            profile,
            game,
            game_dir,
            output,
        } => hm_snippet(url_or_file, profile, game, game_dir, output).await,
        WabbajackAction::ImportArchive { manifest, archives } => {
            import_archive(manifest, archives).await
        }
        WabbajackAction::AcquireMissing {
            manifest,
            download_dir,
            data_dir,
            browser_profile,
            include_nexus,
            browser_controller,
            timeout,
            json,
        } => acquire_missing(
            manifest,
            download_dir,
            data_dir,
            browser_profile,
            include_nexus,
            browser_controller,
            timeout,
            json,
        )
        .await
        .map(|_| ()),
        WabbajackAction::Assess {
            manifest,
            profile,
            game_dir,
            json,
        } => assess(manifest, profile, game_dir, json).await,
        WabbajackAction::MissingImpact {
            manifest,
            data_dir,
            json,
            nix_snippet,
        } => missing_impact(manifest, data_dir, json, nix_snippet),
        WabbajackAction::ManualLinks {
            manifest,
            data_dir,
            json,
        } => manual_links(manifest, data_dir, json),
        WabbajackAction::AnalyzeDiagnostics {
            diagnostics_dir,
            json,
        } => analyze_diagnostics(&diagnostics_dir, json),
    }
}

#[derive(Debug, Serialize)]
struct ManualLinkReport {
    name: String,
    hash: u64,
    hash_hex: String,
    size: u64,
    domain: String,
    url: String,
    store_path: PathBuf,
}

fn manual_links(manifest_path: PathBuf, data_dir: Option<PathBuf>, json: bool) -> Result<()> {
    let manifest = parse_wabbajack_manifest(&manifest_path)?;
    let store_dir = data_dir
        .unwrap_or_else(modde_core::paths::modde_data_dir)
        .join("store");
    let links = manual_link_reports(&manifest, &store_dir);

    if json {
        println!("{}", serde_json::to_string_pretty(&links)?);
        return Ok(());
    }

    for link in links {
        println!(
            "{} {:016x} {} bytes {} {}",
            link.name, link.hash, link.size, link.domain, link.url
        );
    }
    Ok(())
}

fn manual_link_reports(manifest: &WabbajackManifest, store_dir: &Path) -> Vec<ManualLinkReport> {
    manifest
        .archives
        .iter()
        .filter_map(|archive| {
            let store_path = store_dir.join(format!("{:016x}.archive", archive.hash));
            if store_path.exists() {
                return None;
            }
            let ArchiveState::ManualDownloader { url, .. } = archive.state.as_ref()? else {
                return None;
            };
            let domain = manual_intervention_domain(url)?;
            Some(ManualLinkReport {
                name: archive.name.clone(),
                hash: archive.hash,
                hash_hex: format!("{:016x}", archive.hash),
                size: archive.size,
                domain: domain.to_string(),
                url: url.clone(),
                store_path,
            })
        })
        .collect()
}

fn manual_intervention_domain(url: &str) -> Option<&'static str> {
    let host = url::Url::parse(url).ok()?.host_str()?.to_ascii_lowercase();
    match host.as_str() {
        "workupload.com" | "www.workupload.com" => Some("workupload.com"),
        "sharemods.com" | "www.sharemods.com" => Some("sharemods.com"),
        "loverslab.com" | "www.loverslab.com" => Some("loverslab.com"),
        _ => None,
    }
}

fn missing_impact(
    manifest_path: PathBuf,
    data_dir: Option<PathBuf>,
    json: bool,
    nix_snippet: bool,
) -> Result<()> {
    let manifest = parse_wabbajack_manifest(&manifest_path)?;
    let store_dir = data_dir
        .unwrap_or_else(modde_core::paths::modde_data_dir)
        .join("store");
    let impact = MissingArchiveImpact::analyze(&manifest, &store_dir);

    if nix_snippet {
        print_missing_archive_nix_snippet(&impact);
        return Ok(());
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&impact)?);
        return Ok(());
    }

    println!("Wabbajack missing archive impact");
    println!("  archives: {}", impact.total_archives);
    println!("  directives: {}", impact.total_directives);
    println!(
        "  missing archives: {} ({} bytes)",
        impact.missing_archives.len(),
        impact.missing_archive_bytes
    );
    println!(
        "  directly blocked directives: {} ({} output bytes)",
        impact.blocked_archive_directives, impact.blocked_output_bytes
    );
    println!(
        "  affected CreateBSA outputs: {}",
        impact.affected_create_bsa.len()
    );
    println!(
        "  omit-mods impact: {} roots, {} directives, {} output bytes",
        impact.omit_mod_roots.len(),
        impact.omit_mod_directives,
        impact.omit_mod_output_bytes
    );
    if !impact.missing_archives.is_empty() {
        println!("  missing inputs:");
        for archive in &impact.missing_archives {
            println!(
                "    {:016x} {} ({} bytes) {}",
                archive.hash, archive.name, archive.size, archive.source_hint
            );
            println!("      store: {}", archive.store_path.display());
            println!(
                "      import: modde wabbajack import-archive '{}' <downloaded-file>",
                manifest_path.display()
            );
        }
    }
    if !impact.omit_mod_roots.is_empty() {
        println!("  omit-mods roots:");
        for root in &impact.omit_mod_roots {
            println!(
                "    {}: {} directives, {} bytes",
                root.name, root.directives, root.output_bytes
            );
        }
    }
    Ok(())
}

fn print_missing_archive_nix_snippet(impact: &MissingArchiveImpact) {
    println!("manualArchives = {{");
    for archive in &impact.missing_archives {
        println!("  # source: {}", archive.source_hint);
        println!("  # expected size: {} bytes", archive.size);
        println!("  {} = {{", nix_string(&archive.name));
        println!("    hash = {};", nix_string(&archive.hash_hex));
        println!("    # path = /path/to/{};", archive.name);
        println!("    optional = true;");
        println!("  }};");
    }
    println!("}};");
}

fn nix_string(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('"');
    let mut chars = value.chars().peekable();
    while let Some(ch) = chars.next() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
            _ => out.push(ch),
        }
    }
    out.push('"');
    out
}

#[derive(Debug, Serialize)]
struct AssessReport {
    manifest_path: String,
    name: String,
    game: String,
    profile_name: String,
    store_path: String,
    archives: usize,
    directives: usize,
    archive_states: BTreeMap<String, usize>,
    directive_types: BTreeMap<String, usize>,
    archive_extensions: BTreeMap<String, usize>,
    downloadable_archives: usize,
    store_present: usize,
    store_missing: Vec<MissingArchive>,
    manual_downloads: Vec<ManualArchive>,
    game_file_sources: GameFileSourceReport,
    staging: StagingReport,
    rar_enabled: bool,
    hard_blockers: Vec<String>,
    warnings: Vec<String>,
}

#[derive(Debug, Serialize)]
struct MissingArchive {
    hash: String,
    name: String,
    state: String,
    store_path: String,
    source: Option<String>,
    remediation: String,
}

#[derive(Debug, Serialize)]
struct ManualArchive {
    hash: String,
    name: String,
    url: String,
    prompt: String,
}

#[derive(Debug, Serialize)]
struct GameFileSourceReport {
    total: usize,
    present: usize,
    missing: Vec<String>,
}

#[derive(Debug, Serialize)]
struct StagingReport {
    path: String,
    exists: bool,
    compatible_layout: bool,
    archive_batch_sentinels: usize,
    archive_batch_total: usize,
    create_bsa_sentinels: usize,
    create_bsa_total: usize,
    layout_action: String,
}

#[derive(Debug, Serialize)]
struct DiagnosticsSummary {
    diagnostics_dir: String,
    heartbeat_count: usize,
    archive_batch_count: usize,
    first_unix_ms: Option<u128>,
    last_unix_ms: Option<u128>,
    last_phase: Option<String>,
    abort_requested: bool,
    max_idle_ms: u128,
    peak_rss_kib: Option<u64>,
    peak_swap_kib: Option<u64>,
    peak_cgroup_memory_bytes: Option<u64>,
    peak_cgroup_swap_bytes: Option<u64>,
    peak_byte_cache_bytes: u64,
    slowest_batches: Vec<BatchSummary>,
}

#[derive(Debug, Serialize)]
struct BatchSummary {
    archive_hash: String,
    directive_count: usize,
    patch_count: usize,
    elapsed_ms: u128,
    trust_check_ms: u128,
    extraction_ms: u128,
    patch_ms: u128,
    prune_ms: u128,
    extracted_patch_source_bytes: u64,
    streamed_hash_bytes: u64,
    sidecar_hit: bool,
    memory_archive_hit: bool,
    disk_archive_fallback: bool,
    pruned_bytes: u64,
    rss_delta_kib: Option<i64>,
    swap_delta_kib: Option<i64>,
    error_count: usize,
    first_error: Option<String>,
}

fn analyze_diagnostics(dir: &Path, json: bool) -> Result<()> {
    let heartbeats = read_jsonl::<modde_sources::wabbajack::diagnostics::HeartbeatRecord>(
        &dir.join("heartbeat.jsonl"),
    )?;
    let mut batches = read_jsonl::<modde_sources::wabbajack::diagnostics::ArchiveBatchRecord>(
        &dir.join("archive-batches.jsonl"),
    )?;

    let mut summary = DiagnosticsSummary {
        diagnostics_dir: dir.display().to_string(),
        heartbeat_count: heartbeats.len(),
        archive_batch_count: batches.len(),
        first_unix_ms: heartbeats.first().map(|record| record.unix_ms),
        last_unix_ms: heartbeats.last().map(|record| record.unix_ms),
        last_phase: heartbeats.last().map(|record| record.phase.clone()),
        abort_requested: heartbeats.iter().any(|record| record.abort_requested),
        max_idle_ms: heartbeats
            .iter()
            .map(|record| record.idle_ms)
            .max()
            .unwrap_or(0),
        peak_rss_kib: heartbeats
            .iter()
            .filter_map(|record| record.process.vm_rss_kib)
            .max(),
        peak_swap_kib: heartbeats
            .iter()
            .filter_map(|record| record.process.vm_swap_kib)
            .max(),
        peak_cgroup_memory_bytes: heartbeats
            .iter()
            .filter_map(|record| record.cgroup.as_ref()?.memory_current)
            .max(),
        peak_cgroup_swap_bytes: heartbeats
            .iter()
            .filter_map(|record| record.cgroup.as_ref()?.memory_swap_current)
            .max(),
        peak_byte_cache_bytes: heartbeats
            .iter()
            .map(|record| record.byte_cache_used)
            .max()
            .unwrap_or(0),
        slowest_batches: Vec::new(),
    };

    batches.sort_by_key(|record| std::cmp::Reverse(record.elapsed_ms));
    summary.slowest_batches = batches
        .into_iter()
        .take(10)
        .map(|record| BatchSummary {
            archive_hash: record.archive_hash,
            directive_count: record.directive_count,
            patch_count: record.patch_count,
            elapsed_ms: record.elapsed_ms,
            trust_check_ms: record.trust_check_ms,
            extraction_ms: record.extraction_ms,
            patch_ms: record.patch_ms,
            prune_ms: record.prune_ms,
            extracted_patch_source_bytes: record.extracted_patch_source_bytes,
            streamed_hash_bytes: record.streamed_hash_bytes,
            sidecar_hit: record.sidecar_hit,
            memory_archive_hit: record.memory_archive_hit,
            disk_archive_fallback: record.disk_archive_fallback,
            pruned_bytes: record.pruned_bytes,
            rss_delta_kib: signed_delta(record.rss_before_kib, record.rss_after_kib),
            swap_delta_kib: signed_delta(record.swap_before_kib, record.swap_after_kib),
            error_count: record.error_count,
            first_error: record.first_error,
        })
        .collect();

    if json {
        println!("{}", serde_json::to_string_pretty(&summary)?);
    } else {
        print_diagnostics_summary(&summary);
    }
    Ok(())
}

fn read_jsonl<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Vec<T>> {
    if !path.exists() {
        return Ok(Vec::new());
    }
    let contents = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    contents
        .lines()
        .enumerate()
        .filter(|(_, line)| !line.trim().is_empty())
        .map(|(line_number, line)| {
            serde_json::from_str(line).with_context(|| {
                format!(
                    "failed to parse {} line {}",
                    path.display(),
                    line_number + 1
                )
            })
        })
        .collect()
}

fn signed_delta(before: Option<u64>, after: Option<u64>) -> Option<i64> {
    Some(after? as i64 - before? as i64)
}

fn print_diagnostics_summary(summary: &DiagnosticsSummary) {
    println!("Wabbajack diagnostics: {}", summary.diagnostics_dir);
    println!(
        "  heartbeats: {}, archive batches: {}",
        summary.heartbeat_count, summary.archive_batch_count
    );
    println!(
        "  last phase: {}{}",
        summary.last_phase.as_deref().unwrap_or("unknown"),
        if summary.abort_requested {
            " (abort requested)"
        } else {
            ""
        }
    );
    println!("  max idle: {:.1}s", summary.max_idle_ms as f64 / 1000.0);
    println!(
        "  peaks: rss {}, swap {}, cgroup memory {}, cgroup swap {}, byte cache {}",
        format_kib(summary.peak_rss_kib),
        format_kib(summary.peak_swap_kib),
        format_bytes(summary.peak_cgroup_memory_bytes),
        format_bytes(summary.peak_cgroup_swap_bytes),
        format_bytes(Some(summary.peak_byte_cache_bytes))
    );
    if summary.archive_batch_count == 0
        && matches!(
            summary.last_phase.as_deref(),
            Some("download" | "verify" | "trust-check")
        )
    {
        println!("  bottleneck: archive trust/download verification wall before extraction");
    }
    if !summary.slowest_batches.is_empty() {
        println!("  slowest archive batches:");
        for batch in &summary.slowest_batches {
            println!(
                "    {} elapsed {:.1}s trust {:.1}s extract {:.1}s patch {:.1}s prune {:.1}s directives {} patches {} hash-read {} patch-source {} pruned {} sidecar {} memory {} disk {} rss-delta {} swap-delta {} errors {}",
                batch.archive_hash,
                batch.elapsed_ms as f64 / 1000.0,
                batch.trust_check_ms as f64 / 1000.0,
                batch.extraction_ms as f64 / 1000.0,
                batch.patch_ms as f64 / 1000.0,
                batch.prune_ms as f64 / 1000.0,
                batch.directive_count,
                batch.patch_count,
                format_bytes(Some(batch.streamed_hash_bytes)),
                format_bytes(Some(batch.extracted_patch_source_bytes)),
                format_bytes(Some(batch.pruned_bytes)),
                batch.sidecar_hit,
                batch.memory_archive_hit,
                batch.disk_archive_fallback,
                format_signed_kib(batch.rss_delta_kib),
                format_signed_kib(batch.swap_delta_kib),
                batch.error_count,
            );
            if let Some(error) = &batch.first_error {
                println!("      first error: {error}");
            }
        }
    }
}

fn format_kib(value: Option<u64>) -> String {
    value.map_or_else(
        || "n/a".to_string(),
        |kib| format!("{:.1} MiB", kib as f64 / 1024.0),
    )
}

fn format_signed_kib(value: Option<i64>) -> String {
    value.map_or_else(
        || "n/a".to_string(),
        |kib| format!("{:+.1} MiB", kib as f64 / 1024.0),
    )
}

fn format_bytes(value: Option<u64>) -> String {
    value.map_or_else(
        || "n/a".to_string(),
        |bytes| format!("{:.1} MiB", bytes as f64 / 1024.0 / 1024.0),
    )
}

async fn assess(
    manifest_path: PathBuf,
    profile: Option<String>,
    game_dir: Option<PathBuf>,
    json: bool,
) -> Result<()> {
    let manifest = parse_wabbajack_manifest(&manifest_path)?;
    let profile_name = profile.unwrap_or_else(|| manifest.name.clone());
    let staging_path = modde_core::paths::staging_dir().join(&profile_name);
    let store = modde_core::paths::store_dir();

    let mut archive_states = BTreeMap::new();
    let mut archive_extensions = BTreeMap::new();
    let mut downloadable_archives = 0;
    let mut store_present = 0;
    let mut store_missing = Vec::new();
    let mut manual_downloads = Vec::new();
    let mut hard_blockers = Vec::new();
    let mut warnings = Vec::new();

    for archive in &manifest.archives {
        *archive_states
            .entry(archive_state_label(archive.state.as_ref()))
            .or_default() += 1;
        *archive_extensions
            .entry(archive_extension(&archive.name))
            .or_default() += 1;

        if matches!(
            archive.state,
            Some(ArchiveState::GameFileSourceDownloader { .. })
        ) {
            continue;
        }
        downloadable_archives += 1;
        let store_path = store.join(format!("{:016x}.archive", archive.hash));
        if store_path.exists() {
            store_present += 1;
        } else {
            store_missing.push(missing_archive_report(archive, &store));
            if let Some(ArchiveState::ManualDownloader { url, prompt }) = &archive.state {
                manual_downloads.push(ManualArchive {
                    hash: format!("{:016x}", archive.hash),
                    name: archive.name.clone(),
                    url: url.clone(),
                    prompt: prompt.clone(),
                });
            }
        }
    }

    let mut directive_types = BTreeMap::new();
    for directive in &manifest.directives {
        *directive_types
            .entry(directive_label(directive))
            .or_default() += 1;
    }

    let unknown_directives = directive_types.get("Unknown").copied().unwrap_or(0);
    if unknown_directives > 0 {
        hard_blockers.push(format!(
            "{unknown_directives} unsupported Wabbajack directive(s) parsed as Unknown"
        ));
    }
    if !cfg!(feature = "rar")
        && manifest
            .archives
            .iter()
            .any(|archive| archive_extension(&archive.name) == "rar")
    {
        hard_blockers.push("RAR archives are present but the CLI was built without `rar`".into());
    }
    if !store_missing.is_empty() {
        warnings.push(format!(
            "{} downloadable archive(s) are missing from the store",
            store_missing.len()
        ));
    }

    let game_sources = assess_game_file_sources(&manifest, game_dir.as_deref());
    if !game_sources.missing.is_empty() {
        hard_blockers.push(format!(
            "{} game-file source(s) are missing",
            game_sources.missing.len()
        ));
    }

    let compatible_layout = modde_sources::wabbajack::staging::StagingStore::new(&staging_path)
        .has_compatible_layout()
        .await;
    let archive_batch_total = manifest.install_directives_grouped_by_archive().len();
    let create_bsa_total = manifest
        .install_directives()
        .iter()
        .filter(|directive| {
            matches!(
                directive,
                modde_core::manifest::wabbajack::InstallDirective::CreateBSA { .. }
            )
        })
        .count();
    let staging = StagingReport {
        path: staging_path.display().to_string(),
        exists: staging_path.exists(),
        compatible_layout,
        archive_batch_sentinels: count_json_files(staging_path.join("_state/archive-batches")),
        archive_batch_total,
        create_bsa_sentinels: count_json_files(staging_path.join("_state/create-bsa")),
        create_bsa_total,
        layout_action: if !staging_path.exists() {
            "create".into()
        } else if compatible_layout {
            "resume".into()
        } else {
            "adopt".into()
        },
    };
    if staging.exists && !staging.compatible_layout {
        warnings.push("existing staging will be adopted instead of deleted".into());
    }

    let report = AssessReport {
        manifest_path: manifest_path.display().to_string(),
        name: manifest.name.clone(),
        game: manifest.game.clone(),
        profile_name,
        store_path: store.display().to_string(),
        archives: manifest.archives.len(),
        directives: manifest.directives.len(),
        archive_states,
        directive_types,
        archive_extensions,
        downloadable_archives,
        store_present,
        store_missing,
        manual_downloads,
        game_file_sources: game_sources,
        staging,
        rar_enabled: cfg!(feature = "rar"),
        hard_blockers,
        warnings,
    };

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_assess_report(&report);
    }

    if !report.hard_blockers.is_empty() {
        anyhow::bail!(
            "assessment found {} hard blocker(s)",
            report.hard_blockers.len()
        );
    }
    Ok(())
}

fn assess_game_file_sources(
    manifest: &WabbajackManifest,
    game_dir: Option<&Path>,
) -> GameFileSourceReport {
    let mut total = 0;
    let mut present = 0;
    let mut missing = Vec::new();
    let Some(game_dir) = game_dir else {
        let required = manifest
            .archives
            .iter()
            .filter(|archive| {
                matches!(
                    archive.state,
                    Some(ArchiveState::GameFileSourceDownloader { .. })
                )
            })
            .count();
        return GameFileSourceReport {
            total: required,
            present: 0,
            missing: if required == 0 {
                Vec::new()
            } else {
                vec!["--game-dir was not provided".into()]
            },
        };
    };

    for archive in &manifest.archives {
        let Some(state @ ArchiveState::GameFileSourceDownloader { .. }) = archive.state.as_ref()
        else {
            continue;
        };
        total += 1;
        let Some(rel) = state.game_file_path() else {
            missing.push(format!("{} has no recognized game-file path", archive.name));
            continue;
        };
        let normalized = rel.replace('\\', "/");
        if game_dir.join(&normalized).exists() {
            present += 1;
        } else {
            missing.push(rel.to_string());
        }
    }

    GameFileSourceReport {
        total,
        present,
        missing,
    }
}

fn print_assess_report(report: &AssessReport) {
    println!("Wabbajack assessment: {} ({})", report.name, report.game);
    println!("  manifest: {}", report.manifest_path);
    println!("  profile: {}", report.profile_name);
    println!("  store: {}", report.store_path);
    println!(
        "  archives: {} (downloadable {}, store present {}, missing {})",
        report.archives,
        report.downloadable_archives,
        report.store_present,
        report.store_missing.len()
    );
    println!("  directives: {}", report.directives);
    println!(
        "  RAR support: {}",
        if report.rar_enabled {
            "enabled"
        } else {
            "disabled"
        }
    );
    println!(
        "  game-file sources: {}/{} present",
        report.game_file_sources.present, report.game_file_sources.total
    );
    println!(
        "  staging: {} (exists: {}, layout: {}, archive sentinels: {}/{}, BSA sentinels: {}/{})",
        report.staging.path,
        report.staging.exists,
        report.staging.layout_action,
        report.staging.archive_batch_sentinels,
        report.staging.archive_batch_total,
        report.staging.create_bsa_sentinels,
        report.staging.create_bsa_total
    );

    if !report.store_missing.is_empty() {
        println!("  missing archives:");
        for archive in report.store_missing.iter().take(20) {
            println!("    {}  {}  {}", archive.hash, archive.state, archive.name);
            println!("      store: {}", archive.store_path);
            if let Some(source) = &archive.source {
                println!("      source: {source}");
            }
            println!("      action: {}", archive.remediation);
        }
        if report.store_missing.len() > 20 {
            println!("    ... and {} more", report.store_missing.len() - 20);
        }
    }
    if !report.hard_blockers.is_empty() {
        println!("  hard blockers:");
        for blocker in &report.hard_blockers {
            println!("    - {blocker}");
        }
    }
    if !report.warnings.is_empty() {
        println!("  warnings:");
        for warning in &report.warnings {
            println!("    - {warning}");
        }
    }
    println!("  readiness:");
    if report.hard_blockers.is_empty() && report.store_missing.is_empty() {
        println!("    - ready for validated staging/deploy");
    } else if report.hard_blockers.is_empty() {
        println!(
            "    - partial staging is possible with `install wabbajack --no-deploy --continue-on-error --skip-validate`"
        );
        println!("    - validated deploy requires resolving the missing archives above");
    } else {
        println!("    - fix hard blockers before starting the install");
    }
    if report.staging.layout_action == "adopt" {
        println!(
            "    - existing staging will be rescued in place; add `--reset-staging` only for a deliberate rebuild"
        );
    }
}

fn missing_archive_report(
    archive: &modde_core::manifest::wabbajack::ArchiveEntry,
    store: &Path,
) -> MissingArchive {
    let hash = format!("{:016x}", archive.hash);
    let store_path = store.join(format!("{hash}.archive"));
    let state = archive_state_label(archive.state.as_ref());
    let source = archive_source_hint(archive.state.as_ref());
    let remediation = match &archive.state {
        Some(ArchiveState::ManualDownloader { .. }) => {
            format!("download manually, then import or place it at {}", store_path.display())
        }
        Some(ArchiveState::NexusDownloader { .. }) => {
            "rerun with a valid Nexus API key/premium session, or import the matching archive manually".into()
        }
        Some(ArchiveState::GameFileSourceDownloader { .. }) => {
            "fix --game-dir or restore the game file source".into()
        }
        Some(_) => "rerun download/import for this archive, then reassess".into(),
        None => "archive has no downloader metadata; import the exact matching file manually".into(),
    };

    MissingArchive {
        hash,
        name: archive.name.clone(),
        state,
        store_path: store_path.display().to_string(),
        source,
        remediation,
    }
}

fn archive_source_hint(state: Option<&ArchiveState>) -> Option<String> {
    match state? {
        ArchiveState::NexusDownloader {
            game_name,
            mod_id,
            file_id,
        } => Some(format!(
            "Nexus game={game_name}, mod_id={mod_id}, file_id={file_id}"
        )),
        ArchiveState::GitHubDownloader {
            user,
            repo,
            tag,
            asset,
        } => Some(format!("GitHub {user}/{repo} tag={tag} asset={asset}")),
        ArchiveState::GoogleDriveDownloader { id } => Some(format!("Google Drive id={id}")),
        ArchiveState::MegaDownloader { url }
        | ArchiveState::MediaFireDownloader { url }
        | ArchiveState::ManualDownloader { url, .. }
        | ArchiveState::HttpDownloader { url, .. } => Some(url.clone()),
        ArchiveState::ModDBDownloader { url, .. } => Some(url.clone()),
        ArchiveState::GameFileSourceDownloader { metadata } => metadata
            .get("File")
            .and_then(serde_json::Value::as_str)
            .map(|file| format!("game file: {file}")),
        ArchiveState::WabbajackCDNDownloader { metadata } => metadata
            .get("Url")
            .and_then(serde_json::Value::as_str)
            .map(str::to_string),
    }
}

fn archive_state_label(state: Option<&ArchiveState>) -> String {
    match state {
        Some(ArchiveState::NexusDownloader { .. }) => "Nexus".into(),
        Some(ArchiveState::GitHubDownloader { .. }) => "GitHub".into(),
        Some(ArchiveState::GoogleDriveDownloader { .. }) => "GoogleDrive".into(),
        Some(ArchiveState::MegaDownloader { .. }) => "Mega".into(),
        Some(ArchiveState::MediaFireDownloader { .. }) => "MediaFire".into(),
        Some(ArchiveState::ManualDownloader { .. }) => "Manual".into(),
        Some(ArchiveState::HttpDownloader { .. }) => "Http".into(),
        Some(ArchiveState::ModDBDownloader { .. }) => "ModDB".into(),
        Some(ArchiveState::GameFileSourceDownloader { .. }) => "GameFileSource".into(),
        Some(ArchiveState::WabbajackCDNDownloader { .. }) => "WabbajackCDN".into(),
        None => "<none>".into(),
    }
}

fn directive_label(directive: &RawDirective) -> String {
    match directive {
        RawDirective::FromArchive { .. } => "FromArchive",
        RawDirective::InlineFile { .. } => "InlineFile",
        RawDirective::RemappedInlineFile { .. } => "RemappedInlineFile",
        RawDirective::PatchedFromArchive { .. } => "PatchedFromArchive",
        RawDirective::CreateBSA { .. } => "CreateBSA",
        RawDirective::Unknown => "Unknown",
    }
    .into()
}

fn archive_extension(name: &str) -> String {
    Path::new(name)
        .extension()
        .and_then(|ext| ext.to_str())
        .map(str::to_ascii_lowercase)
        .unwrap_or_else(|| "<none>".into())
}

fn count_json_files(path: PathBuf) -> usize {
    std::fs::read_dir(path).map_or(0, |entries| {
        entries
            .filter_map(std::result::Result::ok)
            .filter(|entry| entry.path().extension().and_then(|ext| ext.to_str()) == Some("json"))
            .count()
    })
}

async fn search(
    query: Option<String>,
    game: Option<String>,
    source: String,
    json: bool,
) -> Result<()> {
    let source = parse_source(&source)?;
    let client = reqwest::Client::new();
    let entries = fetch_catalog(&client, source).await?;
    let filtered = filter_entries(
        &entries,
        &CatalogFilter {
            query,
            game,
            include_nsfw: true,
            include_down: true,
            ..Default::default()
        },
    );

    if json {
        println!("{}", serde_json::to_string_pretty(&filtered)?);
        return Ok(());
    }

    for entry in filtered {
        println!(
            "{}{}{}",
            entry.title,
            entry
                .version
                .as_ref()
                .map(|v| format!(" v{v}"))
                .unwrap_or_default(),
            entry
                .game
                .as_ref()
                .map(|g| format!(" [{g}]"))
                .unwrap_or_default()
        );
        if let Some(machine) = &entry.machine_url {
            if let Some(repository) = &entry.repository_name {
                println!("  id: {repository}/{machine}");
            } else {
                println!("  id: {machine}");
            }
        }
        println!("  source: {:?}  official: {}", entry.source, entry.official);
        println!("  download: {}", entry.download_url);
    }
    Ok(())
}

async fn import_archive(manifest_path: PathBuf, archives: Vec<PathBuf>) -> Result<()> {
    if archives.is_empty() {
        anyhow::bail!("at least one archive path is required");
    }
    let manifest = parse_wabbajack_manifest(&manifest_path)?;
    let store = modde_core::paths::store_dir();
    let results = import_archives(&manifest, &store, &archives).await?;

    let mut refused = 0_usize;
    for result in &results {
        match result.status {
            ArchiveImportStatus::Imported => {
                println!(
                    "imported {} -> {} ({})",
                    result.source_path.display(),
                    result
                        .store_path
                        .as_ref()
                        .map_or_else(|| "<missing>".into(), |p| p.display().to_string()),
                    result.matched_archive.as_deref().unwrap_or("<unknown>")
                );
            }
            ArchiveImportStatus::AlreadyPresent => {
                println!(
                    "already-present {} -> {} ({})",
                    result.source_path.display(),
                    result
                        .store_path
                        .as_ref()
                        .map_or_else(|| "<missing>".into(), |p| p.display().to_string()),
                    result.matched_archive.as_deref().unwrap_or("<unknown>")
                );
            }
            ArchiveImportStatus::Mismatched => {
                refused += 1;
                eprintln!(
                    "mismatched {}: filename appears in manifest, but computed xxh64 {:016x} does not match any archive hash",
                    result.source_path.display(),
                    result.computed_xxh64
                );
            }
            ArchiveImportStatus::Unused => {
                refused += 1;
                eprintln!(
                    "unused {}: computed xxh64 {:016x} is not referenced by the manifest",
                    result.source_path.display(),
                    result.computed_xxh64
                );
            }
        }
    }

    if refused > 0 {
        anyhow::bail!("refused {refused} archive import(s)");
    }

    Ok(())
}

pub(crate) async fn acquire_missing(
    manifest_path: PathBuf,
    download_dir: Option<PathBuf>,
    data_dir: Option<PathBuf>,
    browser_profile: Option<PathBuf>,
    include_nexus: bool,
    browser_controller: bool,
    timeout_secs: u64,
    json: bool,
) -> Result<Vec<AcquireResult>> {
    let manifest = parse_wabbajack_manifest(&manifest_path)?;
    let data_dir = data_dir.unwrap_or_else(modde_core::paths::modde_data_dir);
    let store_dir = data_dir.join("store");
    let download_dir = download_dir.unwrap_or_else(|| data_dir.join("downloads"));
    tokio::fs::create_dir_all(&download_dir).await?;
    tokio::fs::create_dir_all(&store_dir).await?;

    if browser_profile.is_some() && !browser_controller && !json {
        eprintln!(
            "browser-profile is recorded for operator context; modde uses the system browser opener"
        );
    }

    let missing = missing_archives(&manifest, &store_dir, include_nexus);
    if browser_controller {
        let results = acquire_missing_with_browser_controller(
            &manifest,
            &store_dir,
            &download_dir,
            &data_dir,
            browser_profile.as_deref(),
            missing,
            Duration::from_secs(timeout_secs),
            json,
        )
        .await?;
        if json {
            println!("{}", serde_json::to_string_pretty(&results)?);
        }
        return Ok(results);
    }

    let mut results = Vec::with_capacity(missing.len());
    for archive in missing {
        let result = match archive.source_kind {
            MissingArchiveSourceKind::Manual => {
                match try_acquire_manual_direct(&manifest, &store_dir, &download_dir, &archive)
                    .await?
                {
                    DirectAcquireOutcome::Resolved(result)
                    | DirectAcquireOutcome::Final(result) => {
                        if !json {
                            print_acquire_result(&result);
                        }
                        results.push(result);
                        continue;
                    }
                    DirectAcquireOutcome::NeedsBrowser {
                        archive: _,
                        message,
                    } => {
                        if !json {
                            eprintln!(
                                "browser-required {:016x} {} message={}",
                                archive.hash, archive.name, message
                            );
                        }
                    }
                    DirectAcquireOutcome::Unsupported => {}
                }
                acquire_manual_archive(
                    &manifest,
                    &store_dir,
                    &download_dir,
                    &archive,
                    browser_profile.as_deref(),
                    Duration::from_secs(timeout_secs),
                    json,
                )
                .await?
            }
            MissingArchiveSourceKind::Nexus => {
                acquire_nexus_archive(&manifest, &store_dir, &download_dir, &archive, json).await?
            }
        };
        if !json {
            print_acquire_result(&result);
        }
        results.push(result);
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&results)?);
    }
    Ok(results)
}

async fn acquire_manual_archive(
    manifest: &WabbajackManifest,
    store_dir: &Path,
    download_dir: &Path,
    archive: &AcquireMissingArchive,
    browser_profile: Option<&Path>,
    timeout: Duration,
    json: bool,
) -> Result<AcquireResult> {
    let Some(url) = archive.url.as_deref() else {
        return Ok(acquire_message(
            archive,
            AcquireStatus::UnsupportedSource,
            "manual archive has no URL",
        ));
    };

    if !json {
        eprintln!(
            "opened-browser {:016x} {} -> {}",
            archive.hash, archive.name, url
        );
        if let Some(profile) = browser_profile {
            eprintln!("browser-profile hint: {}", profile.display());
        }
    }
    if let Err(err) = open::that(url) {
        eprintln!("browser-open-failed {url}: {err:#}");
        eprintln!("open this URL manually, then save the archive into the watched directory");
    }

    if !json {
        eprintln!(
            "waiting-for-download {:016x} {} in {}",
            archive.hash,
            archive.name,
            download_dir.display()
        );
    }

    match wait_for_matching_download(download_dir, archive, timeout).await {
        Ok(found) if found.matched => {
            import_acquired_archive(manifest, store_dir, archive, &found.path).await
        }
        Ok(found) => Ok(AcquireResult {
            archive: archive.clone(),
            status: AcquireStatus::Mismatched,
            path: Some(found.path),
            computed_xxh64: Some(found.computed_xxh64),
            message: Some("downloaded file name matched but hash did not".into()),
        }),
        Err(err) => Ok(AcquireResult {
            archive: archive.clone(),
            status: AcquireStatus::TimedOut,
            path: None,
            computed_xxh64: None,
            message: Some(err.to_string()),
        }),
    }
}

async fn acquire_missing_with_browser_controller(
    manifest: &WabbajackManifest,
    store_dir: &Path,
    download_dir: &Path,
    data_dir: &Path,
    browser_profile: Option<&Path>,
    missing: Vec<AcquireMissingArchive>,
    timeout: Duration,
    json: bool,
) -> Result<Vec<AcquireResult>> {
    let mut results = Vec::with_capacity(missing.len());
    let mut pending = Vec::new();

    for archive in missing {
        match archive.source_kind {
            MissingArchiveSourceKind::Manual => {
                match try_acquire_manual_direct(manifest, store_dir, download_dir, &archive).await?
                {
                    DirectAcquireOutcome::Resolved(result)
                    | DirectAcquireOutcome::Final(result) => {
                        if !json {
                            print_acquire_result(&result);
                        }
                        results.push(result);
                    }
                    DirectAcquireOutcome::NeedsBrowser { archive, message } => {
                        if !json {
                            eprintln!(
                                "browser-required {:016x} {} message={}",
                                archive.hash, archive.name, message
                            );
                        }
                        pending.push(archive);
                    }
                    DirectAcquireOutcome::Unsupported => pending.push(archive),
                }
            }
            MissingArchiveSourceKind::Nexus => {
                let result =
                    acquire_nexus_archive(manifest, store_dir, download_dir, &archive, json)
                        .await?;
                if matches!(
                    result.status,
                    AcquireStatus::Imported | AcquireStatus::AlreadyPresent
                ) {
                    if !json {
                        print_acquire_result(&result);
                    }
                    results.push(result);
                } else if archive.url.is_some() {
                    if !json {
                        eprintln!(
                            "nexus-browser-fallback {:016x} {}: {}",
                            archive.hash,
                            archive.name,
                            result
                                .message
                                .as_deref()
                                .unwrap_or("Nexus API did not resolve")
                        );
                    }
                    pending.push(archive);
                } else {
                    if !json {
                        print_acquire_result(&result);
                    }
                    results.push(result);
                }
            }
        }
    }

    if pending.is_empty() {
        return Ok(results);
    }

    if !json {
        eprintln!("pending browser downloads:");
        for archive in &pending {
            eprintln!(
                "  {:016x} {} {}",
                archive.hash,
                archive.name,
                archive.url.as_deref().unwrap_or("<no url>")
            );
        }
    }

    let urls = pending
        .iter()
        .filter_map(|archive| archive.url.clone())
        .collect::<Vec<_>>();
    let default_browser_profile = data_dir.join("browser-profiles/wabbajack-acquire");
    let browser_profile = browser_profile.unwrap_or(&default_browser_profile);
    let mut browser = match launch_chromium_controller(&urls, download_dir, browser_profile) {
        Ok(child) => Some(child),
        Err(err) => {
            eprintln!("browser-controller-unavailable: {err:#}");
            eprintln!(
                "open the listed URLs manually, then save archives into the watched directory"
            );
            None
        }
    };

    let deadline = std::time::Instant::now() + timeout;
    while !pending.is_empty() {
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            break;
        }

        match wait_for_next_matching_download(download_dir, &pending, remaining).await {
            Ok(found) if found.matched => {
                let Some(hash) = found.matched_hash else {
                    continue;
                };
                let Some(pos) = pending.iter().position(|archive| archive.hash == hash) else {
                    continue;
                };
                let archive = pending.remove(pos);
                let result =
                    import_acquired_archive(manifest, store_dir, &archive, &found.path).await?;
                if !json {
                    print_acquire_result(&result);
                }
                results.push(result);
            }
            Ok(found) => {
                if !json {
                    eprintln!(
                        "mismatched-download path={} computed={:016x}",
                        found.path.display(),
                        found.computed_xxh64
                    );
                }
            }
            Err(err) => {
                if !json {
                    eprintln!("browser-download-wait-ended: {err:#}");
                }
                break;
            }
        }
    }

    if let Some(browser) = &mut browser {
        let _ = browser.kill();
    }
    for archive in pending {
        let result = AcquireResult {
            archive,
            status: AcquireStatus::TimedOut,
            path: None,
            computed_xxh64: None,
            message: Some(
                "browser-controlled acquisition did not observe a matching download".into(),
            ),
        };
        if !json {
            print_acquire_result(&result);
        }
        results.push(result);
    }

    Ok(results)
}

fn launch_chromium_controller(
    urls: &[String],
    download_dir: &Path,
    browser_profile: &Path,
) -> Result<std::process::Child> {
    if urls.is_empty() {
        anyhow::bail!("no URLs to open");
    }
    #[cfg(target_os = "linux")]
    if std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() {
        anyhow::bail!("no graphical display found ($DISPLAY or $WAYLAND_DISPLAY is required)");
    }
    std::fs::create_dir_all(download_dir)?;
    write_chromium_preferences(browser_profile, download_dir)?;
    let chromium = find_chromium().context("no Chromium-compatible browser found in PATH")?;
    let mut command = std::process::Command::new(chromium);
    command
        .arg(format!("--user-data-dir={}", browser_profile.display()))
        .arg("--no-first-run")
        .arg("--new-window");
    for url in urls {
        command.arg(url);
    }
    command
        .spawn()
        .context("failed to launch Chromium browser controller")
}

fn write_chromium_preferences(browser_profile: &Path, download_dir: &Path) -> Result<()> {
    let default_dir = browser_profile.join("Default");
    std::fs::create_dir_all(&default_dir)?;
    let prefs = serde_json::json!({
        "download": {
            "default_directory": download_dir,
            "directory_upgrade": true,
            "prompt_for_download": false
        },
        "profile": {
            "default_content_setting_values": {
                "automatic_downloads": 1
            }
        }
    });
    std::fs::write(
        default_dir.join("Preferences"),
        serde_json::to_vec_pretty(&prefs)?,
    )?;
    Ok(())
}

fn find_chromium() -> Option<String> {
    if let Ok(path) = std::env::var("MODDE_CHROMIUM")
        && std::process::Command::new(&path)
            .arg("--version")
            .output()
            .is_ok()
    {
        return Some(path);
    }
    [
        "chromium",
        "chromium-browser",
        "google-chrome",
        "google-chrome-stable",
        "brave-browser",
        "brave",
    ]
    .into_iter()
    .find(|candidate| {
        std::process::Command::new(candidate)
            .arg("--version")
            .output()
            .is_ok()
    })
    .map(str::to_string)
}

async fn acquire_nexus_archive(
    manifest: &WabbajackManifest,
    store_dir: &Path,
    download_dir: &Path,
    archive: &AcquireMissingArchive,
    json: bool,
) -> Result<AcquireResult> {
    let Some(directive) = manifest
        .download_directives()
        .into_iter()
        .find(|directive| directive.hash() == archive.hash)
    else {
        return Ok(acquire_message(
            archive,
            AcquireStatus::UnsupportedSource,
            "Nexus archive did not produce a download directive",
        ));
    };

    let client = reqwest::Client::new();
    let source = match modde_sources::nexus::NexusSource::new(client) {
        Ok(source) => source,
        Err(err) => {
            return Ok(acquire_message(
                archive,
                AcquireStatus::NexusCredentialsMissing,
                &format!("{err:#}"),
            ));
        }
    };

    if !json {
        eprintln!(
            "resolving-nexus {:016x} {}",
            archive.hash, archive.source_hint
        );
    }
    let handle = match source.resolve(&directive).await {
        Ok(handle) => handle,
        Err(err) => {
            return Ok(acquire_message(
                archive,
                AcquireStatus::NexusCredentialsMissing,
                &format!("{err:#}"),
            ));
        }
    };

    let dest = download_dir.join(safe_archive_file_name(&archive.name));
    let verified = match source.download(handle, &dest).await {
        Ok(verified) => verified,
        Err(err) => {
            return Ok(acquire_message(
                archive,
                AcquireStatus::Mismatched,
                &format!("{err:#}"),
            ));
        }
    };
    import_acquired_archive(manifest, store_dir, archive, &verified.path).await
}

fn safe_archive_file_name(name: &str) -> String {
    Path::new(name)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("archive.download")
        .to_string()
}

fn acquire_message(
    archive: &AcquireMissingArchive,
    status: AcquireStatus,
    message: &str,
) -> AcquireResult {
    AcquireResult {
        archive: archive.clone(),
        status,
        path: None,
        computed_xxh64: None,
        message: Some(message.to_string()),
    }
}

fn print_acquire_result(result: &AcquireResult) {
    let archive = &result.archive;
    let path = result
        .path
        .as_ref()
        .map_or_else(String::new, |path| format!(" path={}", path.display()));
    let hash = result
        .computed_xxh64
        .map_or_else(String::new, |hash| format!(" computed={hash:016x}"));
    let message = result
        .message
        .as_ref()
        .map_or_else(String::new, |message| format!(" message={message}"));
    println!(
        "{} {:016x} {}{}{}{}",
        acquire_status_label(&result.status),
        archive.hash,
        archive.name,
        path,
        hash,
        message
    );
}

pub(crate) fn acquire_status_label(status: &AcquireStatus) -> &'static str {
    match status {
        AcquireStatus::AlreadyPresent => "already-present",
        AcquireStatus::OpenedBrowser => "opened-browser",
        AcquireStatus::WaitingForDownload => "waiting-for-download",
        AcquireStatus::DirectResolved => "direct-resolved",
        AcquireStatus::DirectFailed => "direct-failed",
        AcquireStatus::BrowserRequired => "browser-required",
        AcquireStatus::DnsUnresolved => "dns-unresolved",
        AcquireStatus::LoginRequired => "login-required",
        AcquireStatus::CaptchaRequired => "captcha-required",
        AcquireStatus::Imported => "imported",
        AcquireStatus::Mismatched => "mismatched",
        AcquireStatus::TimedOut => "timed-out",
        AcquireStatus::NexusCredentialsMissing => "nexus-credentials-missing",
        AcquireStatus::UnsupportedSource => "unsupported-source",
    }
}

fn parse_source(source: &str) -> Result<CatalogSource> {
    match source {
        "official" => Ok(CatalogSource::Official),
        "authored" => Ok(CatalogSource::Authored),
        "both" => Ok(CatalogSource::Both),
        other => anyhow::bail!(
            "invalid Wabbajack source '{other}' (expected official, authored, or both)"
        ),
    }
}

async fn download(url_or_machine_url: String, output: Option<PathBuf>) -> Result<()> {
    let client = reqwest::Client::new();
    let url = resolve_download_target(&client, &url_or_machine_url, CatalogSource::Both).await?;
    let output = output.unwrap_or_else(modde_core::paths::downloads_dir);
    let path = download_wabbajack_file(&client, &url, &output).await?;
    println!("{}", path.display());
    Ok(())
}

async fn hm_snippet(
    url_or_file: String,
    profile: String,
    game: String,
    game_dir: Option<PathBuf>,
    output: Option<PathBuf>,
) -> Result<()> {
    let client = reqwest::Client::new();
    let cache_dir = modde_core::paths::downloads_dir().join("wabbajack");
    let source = if std::path::Path::new(&url_or_file).exists()
        || url_or_file.starts_with("http://")
        || url_or_file.starts_with("https://")
    {
        url_or_file
    } else {
        let entries = fetch_catalog(&client, CatalogSource::Both).await?;
        find_entry(&entries, &url_or_file)
            .map(|entry| entry.download_url.clone())
            .with_context(|| format!("no Wabbajack catalog entry matches '{url_or_file}'"))?
    };
    let (snippet, cached_path) = hm_snippet_for_source(
        &client,
        &source,
        &profile,
        &game,
        game_dir.as_deref(),
        &cache_dir,
    )
    .await?;

    if let Some(output) = output {
        if let Some(parent) = output.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(&output, &snippet)
            .await
            .with_context(|| format!("failed to write {}", output.display()))?;
        println!("{}", output.display());
    } else {
        print!("{snippet}");
    }

    if let Some(path) = cached_path {
        eprintln!("hashed: {}", path.display());
    }
    Ok(())
}