momus-cli 0.9.1

Momus API test harness — CLI runner
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
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use momus_core::ast::*;
use momus_core::config::{AuthConfig, MomusConfig};
use momus_core::engine::runner;
use std::path::PathBuf;

#[derive(ValueEnum, Debug, Clone)]
enum OutputFormat {
    Auto,
    Html,
    Junit,
    Json,
    Text,
}

#[derive(ValueEnum, Debug, Clone)]
enum BenchModeCli {
    Steady,
    MaxThroughput,
    Soak,
}

#[derive(Parser)]
#[command(
    name = "momus",
    about = "Generic API test harness with a composable assertion AST",
    version,
    long_about = "Momus is a domain-agnostic test runner for HTTP APIs.\n\
                   Tests are defined as a JSON plan — a tree of steps (requests,\n\
                   sequences, parallel blocks) with composable assertions on responses.\n\n\
                   Configuration is loaded from:\n\
                   1. --config <path> (explicit)\n\
                   2. $MOMUS_CONFIG (env var)\n\
                   3. ./momus.toml\n\
                   4. ./.momus.toml\n\
                   5. ~/.config/momus/config.toml\n\n\
                   CLI flags override config file values."
)]
struct Cli {
    /// Path to config.toml (optional). Searches default locations if not set.
    #[arg(long, global = true, env = "MOMUS_CONFIG")]
    config: Option<String>,

    /// Enable verbose output (sets RUST_LOG=momus=debug).
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Global request timeout in seconds (overrides config file and per-command timeouts).
    #[arg(long, global = true)]
    timeout: Option<u64>,

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

#[derive(Subcommand)]
enum Commands {
    /// Run a test plan from a JSON file.
    Run {
        /// Path to the test plan JSON file (use - for stdin).
        plan: String,
        /// Base URL override.
        #[arg(long)]
        base_url: Option<String>,
        /// Output directory for results.
        #[arg(long, default_value = "./output/run")]
        output: PathBuf,
        /// Output format (auto-detect from --output extension, or force with this flag).
        #[arg(long, value_enum, default_value = "auto")]
        format: OutputFormat,
        /// Parse and validate the plan, resolve templates where statically possible,
        /// and print the resolved request list without sending any requests.
        #[arg(long)]
        dry_run: bool,
    },
    /// Validate a test plan JSON file.
    Validate {
        /// Path to the test plan JSON file (use - for stdin).
        plan: String,
    },
    /// Start a mock server for testing.
    Mock {
        /// Port to listen on (0 = random).
        #[arg(long, default_value = "0")]
        port: u16,
    },
    /// Load test a plan (steady, max-throughput, or soak).
    Bench {
        /// Path to the test plan JSON file.
        plan: PathBuf,
        /// Benchmark mode: steady, max-throughput, soak.
        #[arg(long, value_enum)]
        mode: Option<BenchModeCli>,
        /// Concurrency level (steady, soak).
        #[arg(long)]
        concurrency: Option<usize>,
        /// Duration in seconds (steady, soak; 0 = one-shot).
        #[arg(long)]
        duration: Option<u64>,
        /// Starting concurrency (max-throughput).
        #[arg(long)]
        min_concurrency: Option<usize>,
        /// Maximum concurrency to try (max-throughput).
        #[arg(long)]
        max_concurrency: Option<usize>,
        /// Concurrency increment per step (max-throughput).
        #[arg(long)]
        step: Option<usize>,
        /// Duration per step in seconds (max-throughput).
        #[arg(long)]
        step_duration: Option<u64>,
        /// Error rate threshold 0.0-1.0 (max-throughput).
        #[arg(long)]
        max_error_rate: Option<f64>,
        /// Latency P99 threshold in ms (max-throughput).
        #[arg(long)]
        max_p99_ms: Option<u64>,
        /// Warmup requests before recording (0 = none).
        #[arg(long)]
        warmup: Option<usize>,
        /// Request timeout in seconds.
        #[arg(long)]
        timeout: Option<u64>,
        /// Base URL override.
        #[arg(long)]
        base_url: Option<String>,
        /// Output file for the HTML report (omit for stdout).
        #[arg(long)]
        output: Option<PathBuf>,
        /// Output format (auto-detect from --output extension, or force with this flag).
        #[arg(long, value_enum, default_value = "auto")]
        format: OutputFormat,
    },
    /// Fuzz test a plan with payload mutations.
    Fuzz {
        /// Path to the test plan JSON file.
        plan: PathBuf,
        /// Number of mutations to generate.
        #[arg(long)]
        iterations: Option<usize>,
        /// Base URL override.
        #[arg(long)]
        base_url: Option<String>,
        /// Select specific mutators by name (repeatable, empty = all).
        #[arg(long)]
        mutators: Vec<String>,
        /// Request timeout in seconds.
        #[arg(long)]
        timeout: Option<u64>,
    },
    /// Run chaos experiments against a plan.
    Chaos {
        /// Path to the test plan JSON file.
        plan: PathBuf,
        /// Base URL override.
        #[arg(long)]
        base_url: Option<String>,
        /// Chaos experiments to run (repeatable, JSON format, e.g. '{"NetworkLatency":{"endpoint":"/api","delay_ms":5000,"duration_secs":30}}').
        #[arg(long)]
        experiment: Vec<String>,
        /// Interval between experiments in seconds.
        #[arg(long)]
        interval: Option<u64>,
    },
    /// Convert an API description into a test plan.
    Convert {
        /// Input format: openapi, postman, har, curl, graphql, grpc, fhir
        #[arg(value_parser = clap::builder::PossibleValuesParser::new([
            "openapi", "postman", "har", "curl", "graphql", "grpc", "fhir",
        ]))]
        format: String,
        /// Path to the input file (or curl command string for format=curl).
        input: String,
        /// Output file for the test plan (default: <input_stem>.json in the same directory).
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Generate seed data setup steps to pre-populate the server with resources
        /// so GET/PUT/DELETE tests have data to operate on.
        #[arg(long)]
        seed_data: bool,
    },
    /// Validate API responses against an OpenAPI/GraphQL spec.
    Contract {
        /// Path to the test plan JSON file.
        plan: PathBuf,
        /// Path to the API spec file (OpenAPI YAML/JSON or GraphQL SDL).
        #[arg(long)]
        spec: String,
        /// Base URL override.
        #[arg(long)]
        base_url: Option<String>,
        /// Enable strict mode (fail on undocumented endpoints).
        #[arg(long)]
        strict: Option<bool>,
        /// Request timeout in seconds.
        #[arg(long)]
        timeout: Option<u64>,
    },
    /// Security scan a plan for common vulnerabilities.
    Guard {
        /// Path to the test plan JSON file.
        plan: PathBuf,
        /// Base URL override.
        #[arg(long)]
        base_url: Option<String>,
        /// Check for missing security headers.
        #[arg(long)]
        check_headers: Option<bool>,
        /// Check CORS configuration.
        #[arg(long)]
        check_cors: Option<bool>,
        /// Check for information leakage in error responses.
        #[arg(long)]
        check_leaks: Option<bool>,
        /// Check for exposed internal endpoints.
        #[arg(long)]
        check_exposed: Option<bool>,
        /// Request timeout in seconds.
        #[arg(long)]
        timeout: Option<u64>,
    },
    /// Diff responses between two environments.
    Diff {
        /// Path to the test plan JSON file.
        plan: PathBuf,
        /// Baseline URL (e.g. production).
        #[arg(long)]
        baseline: String,
        /// Target URL (e.g. staging).
        #[arg(long)]
        target: String,
        /// Diff response headers.
        #[arg(long)]
        diff_headers: Option<bool>,
        /// Diff response bodies.
        #[arg(long)]
        diff_bodies: Option<bool>,
        /// Diff status codes.
        #[arg(long)]
        diff_status: Option<bool>,
        /// Request timeout in seconds.
        #[arg(long)]
        timeout: Option<u64>,
    },
    /// Generate a skeleton test plan or config file.
    Init {
        /// What to generate: plan, config
        #[arg(default_value = "plan")]
        template: String,
        /// Output path (default: test-plan.json for plan, momus.toml for config).
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Show a human-readable summary of a test plan.
    Plan {
        /// Path to the test plan JSON file (use - for stdin).
        plan: String,
        /// Output directory for the plan display.
        #[arg(long, default_value = "./output/plan")]
        output: PathBuf,
    },
    /// Generate shell completion scripts (bash, zsh, fish, etc.).
    Completions {
        /// Shell to generate completions for.
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// Open the Momus documentation in your browser.
    Docs,
    /// FHIR-specific operations (mock server, validate, generate).
    #[command(subcommand)]
    Fhir(FhirCommands),
}

/// FHIR-specific subcommands.
#[derive(Subcommand)]
enum FhirCommands {
    /// Start a FHIR mock server with CRUD + search support.
    Mock {
        /// Port to listen on (0 = random).
        #[arg(long, default_value = "0")]
        port: u16,
    },
    /// Validate a JSON resource against a profile from an IG package.
    Validate {
        /// Path to the IG package (.tgz).
        package: String,
        /// Path to the resource JSON file to validate.
        #[arg(short, long)]
        resource: String,
        /// Profile canonical URL to validate against (optional — auto-detect by resource type).
        #[arg(long)]
        profile: Option<String>,
    },
    /// Generate bulk FHIR test data (NDJSON) from an IG package.
    Generate {
        /// Path to the FHIR IG package (.tgz).
        package: String,
        /// Number of resources to generate per type (default: 10).
        #[arg(long, default_value = "10")]
        count: u64,
        /// Output directory for NDJSON files (default: ./output/fhir).
        #[arg(long, default_value = "./output/fhir")]
        output: PathBuf,
    },
    /// Generate an OpenAPI 3.x spec from a FHIR IG package or server metadata.
    #[command(name = "openapi")]
    OpenApi {
        /// Path to the FHIR IG package (.tgz). Omit when using --base-url.
        package: Option<String>,
        /// FHIR server base URL; fetch its CapabilityStatement from /metadata
        /// instead of reading a local package.
        #[arg(long)]
        base_url: Option<String>,
        /// Output format: yaml or json (default: yaml).
        #[arg(long, default_value = "yaml")]
        format: String,
        /// Output file for the spec (default: stdout).
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Upload bulk FHIR NDJSON data to a write endpoint (repository or server).
    Upload {
        /// Directory containing `{ResourceType}.ndjson` files (default: ./output/fhir/data).
        #[arg(long, default_value = "./output/fhir/data")]
        data_dir: PathBuf,
        /// Write endpoint base URL (may differ from the FHIR server under test).
        #[arg(long)]
        endpoint: String,
        /// Upload method: PUT or POST (default: PUT).
        #[arg(long, default_value = "PUT")]
        method: String,
        /// Basic-auth username for repository endpoints.
        #[arg(long)]
        username: Option<String>,
        /// Basic-auth password for repository endpoints.
        #[arg(long)]
        password: Option<String>,
        /// Concurrent uploads (default: 8).
        #[arg(long, default_value = "8")]
        concurrency: usize,
    },
    /// Delete FHIR resources previously uploaded from a data directory.
    Delete {
        /// Directory containing `{ResourceType}.ndjson` files (default: ./output/fhir/data).
        #[arg(long, default_value = "./output/fhir/data")]
        data_dir: PathBuf,
        /// Write endpoint base URL (may differ from the FHIR server under test).
        #[arg(long)]
        endpoint: String,
        /// Basic-auth username for repository endpoints.
        #[arg(long)]
        username: Option<String>,
        /// Basic-auth password for repository endpoints.
        #[arg(long)]
        password: Option<String>,
        /// Concurrent deletes (default: 8).
        #[arg(long, default_value = "8")]
        concurrency: usize,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Set up tracing: verbose flag enables debug for the momus crates if RUST_LOG
    // is not already set. The upload/convert logic lives in momus_convert, so it
    // must be included explicitly (a bare `momus=debug` would not match it).
    if cli.verbose && std::env::var("RUST_LOG").is_err() {
        // SAFETY: Setting RUST_LOG before tracing is initialized is safe — no other
        // thread is reading it yet, and we're at the start of main.
        unsafe {
            std::env::set_var(
                "RUST_LOG",
                "momus=debug,momus_convert=debug,momus_core=debug,momus_mock=debug",
            );
        }
    }
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing::Level::INFO.into()),
        )
        .init();

    // Load optional config file — search default locations if not specified
    let mut cfg = load_config(cli.config.as_deref())?;

    // Apply global --timeout override if provided
    if let Some(timeout) = cli.timeout {
        cfg.global.timeout_secs = timeout;
    }

    match cli.command {
        Commands::Run {
            plan,
            base_url,
            output,
            format,
            dry_run,
        } => {
            let content = read_plan_content(&plan)?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{plan}'"))?;

            // Config precedence: CLI > [run] section > [global] section
            if let Some(url) = base_url.or(cfg.run.base_url).or(cfg.global.base_url) {
                test_plan.base_url = url;
            }

            // Dry-run: parse + validate the plan, resolve templates statically where
            // possible, and print the resolved request list without sending anything.
            if dry_run {
                return dry_run_plan(&test_plan);
            }

            // CLI --output overrides config file output
            let output = if output.to_str() != Some("./output/run") {
                output
            } else if cfg.run.output != *"./output/run" {
                cfg.run.output
            } else if let Some(global_output) = &cfg.global.output {
                global_output.clone()
            } else {
                PathBuf::from("./output/run")
            };

            // Apply global headers and timeout from config
            if !cfg.global.headers.is_empty() {
                for (k, v) in &cfg.global.headers {
                    test_plan
                        .default_headers
                        .entry(k.clone())
                        .or_insert_with(|| v.clone());
                }
            }

            // Apply run-specific headers (override global)
            if !cfg.run.headers.is_empty() {
                for (k, v) in &cfg.run.headers {
                    test_plan
                        .default_headers
                        .entry(k.clone())
                        .or_insert_with(|| v.clone());
                }
            }

            // Apply auth as an Authorization header (run overrides global).
            // An explicit Authorization header set above still takes precedence.
            let auth = if cfg.run.auth.is_empty() {
                &cfg.global.auth
            } else {
                &cfg.run.auth
            };
            apply_auth_to_plan(&mut test_plan, auth)?;

            // Use run-specific timeout, falling back to global
            let timeout_secs = if cfg.run.timeout_secs != 30 {
                cfg.run.timeout_secs
            } else if cfg.global.timeout_secs != 30 {
                cfg.global.timeout_secs
            } else {
                30
            };

            tracing::info!(
                "Running test plan '{}' with {} test(s) against {}",
                test_plan.name,
                test_plan.total_tests(),
                test_plan.base_url
            );

            // Resolve the plan's directory so relative dataset paths work.
            let plan_dir = if plan == "-" {
                std::path::PathBuf::from(".")
            } else {
                std::path::Path::new(&plan)
                    .parent()
                    .map(|p| p.to_path_buf())
                    .unwrap_or_else(|| std::path::PathBuf::from("."))
            };

            let report =
                runner::execute_plan_with_timeout_and_dir(&test_plan, timeout_secs, &plan_dir)
                    .await?;

            // Config output_format overrides auto-detection when the CLI didn't force a format
            let format = if matches!(format, OutputFormat::Auto) {
                match cfg.global.output_format.as_deref() {
                    Some("html") => OutputFormat::Html,
                    Some("junit") => OutputFormat::Junit,
                    Some("text") => OutputFormat::Text,
                    _ => format,
                }
            } else {
                format
            };

            let want_junit = match format {
                OutputFormat::Junit => true,
                OutputFormat::Html => false,
                OutputFormat::Json => false,
                OutputFormat::Text => false,
                OutputFormat::Auto => output
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|e| e == "xml")
                    .unwrap_or(false),
            };

            let want_html = if want_junit {
                false
            } else {
                match format {
                    OutputFormat::Html => true,
                    OutputFormat::Json => false,
                    OutputFormat::Text => false,
                    OutputFormat::Auto => output
                        .extension()
                        .and_then(|e| e.to_str())
                        .map(|e| e == "html")
                        .unwrap_or(false),
                    OutputFormat::Junit => false,
                }
            };

            if want_junit {
                std::fs::create_dir_all(&output)?;
                report.write_junit_xml(&output)?;
                let junit_path = output.join("junit.xml");
                println!("JUnit XML report written to: {}", junit_path.display());
            } else if want_html {
                let html = report.to_html();
                if output.extension().and_then(|e| e.to_str()) == Some("html") {
                    // --output is a file path
                    std::fs::create_dir_all(output.parent().unwrap_or(&output))?;
                    std::fs::write(&output, &html)?;
                    println!("HTML report written to: {}", output.display());
                } else {
                    // --output is a directory — write report.html inside it
                    std::fs::create_dir_all(&output)?;
                    let html_path = output.join("report.html");
                    std::fs::write(&html_path, &html)?;
                    println!("HTML report written to: {}", html_path.display());
                }
            } else {
                println!("{report}");
            }

            // Write per-group results to output/results/. When --output is a file
            // path (e.g. report.html), results go alongside it in the parent dir.
            let (results_base, results_print) =
                if output.extension().and_then(|e| e.to_str()).is_some() {
                    let parent = output.parent().unwrap_or(std::path::Path::new("."));
                    (parent.to_path_buf(), parent.to_path_buf())
                } else {
                    (output.clone(), output.clone())
                };
            let results_dir = results_base.join("results");
            std::fs::create_dir_all(&results_dir)?;
            report.write_results(&results_base)?;
            println!("\nResults written to: {}/results/", results_print.display());

            if report.failed > 0 {
                std::process::exit(1);
            }

            Ok(())
        }
        Commands::Validate { plan } => {
            let content = read_plan_content(&plan)?;
            let test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{plan}'"))?;
            println!("✓ Valid test plan: '{}'", test_plan.name);
            println!("  Total tests: {}", test_plan.total_tests());
            println!("  Steps: {}", test_plan.steps.len());
            if !test_plan.setup.is_empty() {
                println!("  Setup steps: {}", test_plan.setup.len());
            }
            if !test_plan.teardown.is_empty() {
                println!("  Teardown steps: {}", test_plan.teardown.len());
            }
            Ok(())
        }
        Commands::Mock { port } => {
            let addr = if port > 0 {
                format!("0.0.0.0:{port}")
            } else {
                "0.0.0.0:0".into()
            };
            let listener = tokio::net::TcpListener::bind(&addr).await?;
            let local_addr = listener.local_addr()?;
            println!("Momus mock server listening on http://{local_addr}");
            println!("All requests return 200 with 'status: ok'");
            println!("Press Ctrl+C to stop.");

            use axum::{Json, Router, routing::any};
            let app = Router::new().route(
                "/{*path}",
                any(|| async {
                    (
                        axum::http::StatusCode::OK,
                        Json(serde_json::json!({"status": "ok"})),
                    )
                }),
            );
            axum::serve(listener, app).await?;
            Ok(())
        }
        Commands::Convert {
            format,
            input,
            output,
            seed_data,
        } => {
            let plan = momus_convert::convert(&format, &input, seed_data)?;
            let json = serde_json::to_string_pretty(&plan)?;
            let path = match output {
                Some(p) => p,
                None => {
                    // Derive output filename from input (except curl, which is a raw command)
                    if format == "curl" {
                        println!("{json}");
                        return Ok(());
                    }
                    let input_path = std::path::Path::new(&input);
                    let stem = input_path
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("test_plan");
                    let parent = std::path::Path::new(".");
                    parent.join(format!("{stem}.momus.json"))
                }
            };
            std::fs::write(&path, json)?;
            println!("Test plan written to: {}", path.display());
            Ok(())
        }
        Commands::Bench {
            plan,
            mode,
            concurrency,
            duration,
            min_concurrency,
            max_concurrency,
            step,
            step_duration,
            max_error_rate,
            max_p99_ms,
            warmup,
            timeout,
            base_url,
            output,
            format,
        } => {
            let content = std::fs::read_to_string(&plan)
                .with_context(|| format!("Failed to read plan file '{}'", plan.display()))?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{}'", plan.display()))?;
            apply_auth_to_plan(&mut test_plan, &cfg.global.auth)?;

            // Config precedence: CLI > [bench] section > [global] section
            let base_url = base_url.or(cfg.bench.base_url).or(cfg.global.base_url);

            // Config precedence: CLI > [bench] section > [global] section > default
            let warmup_requests = warmup.unwrap_or(cfg.bench.warmup_requests);
            let timeout_secs = timeout
                .or(Some(cfg.bench.timeout_secs))
                .or(Some(cfg.global.timeout_secs))
                .unwrap_or(30);

            // Config precedence: CLI > [bench] section > hardcoded defaults
            let bench_mode = match mode.unwrap_or({
                // If no CLI mode, try config file, then default to Steady
                match &cfg.bench.mode {
                    momus_bench::BenchMode::Steady { .. } => BenchModeCli::Steady,
                    momus_bench::BenchMode::MaxThroughput { .. } => BenchModeCli::MaxThroughput,
                    momus_bench::BenchMode::Soak { .. } => BenchModeCli::Soak,
                }
            }) {
                BenchModeCli::Steady => {
                    let concurrency = concurrency
                        .or(match &cfg.bench.mode {
                            momus_bench::BenchMode::Steady { concurrency, .. } => {
                                Some(*concurrency)
                            }
                            _ => None,
                        })
                        .unwrap_or(10);
                    let duration_secs = duration
                        .or(match &cfg.bench.mode {
                            momus_bench::BenchMode::Steady { duration_secs, .. } => {
                                Some(*duration_secs)
                            }
                            _ => None,
                        })
                        .unwrap_or(30);
                    momus_bench::BenchMode::Steady {
                        concurrency,
                        duration_secs,
                    }
                }
                BenchModeCli::MaxThroughput => momus_bench::BenchMode::MaxThroughput {
                    min_concurrency: min_concurrency.unwrap_or(10),
                    max_concurrency: max_concurrency.unwrap_or(200),
                    step: step.unwrap_or(10),
                    step_duration_secs: step_duration.unwrap_or(10),
                    max_error_rate: max_error_rate.unwrap_or(0.05),
                    max_p99_ms: max_p99_ms.unwrap_or(2000),
                },
                BenchModeCli::Soak => {
                    let concurrency = concurrency
                        .or(match &cfg.bench.mode {
                            momus_bench::BenchMode::Soak { concurrency, .. } => Some(*concurrency),
                            _ => None,
                        })
                        .unwrap_or(10);
                    let duration_secs = duration
                        .or(match &cfg.bench.mode {
                            momus_bench::BenchMode::Soak { duration_secs, .. } => {
                                Some(*duration_secs)
                            }
                            _ => None,
                        })
                        .unwrap_or(30);
                    momus_bench::BenchMode::Soak {
                        concurrency,
                        duration_secs,
                    }
                }
            };

            let config = momus_bench::BenchConfig {
                mode: bench_mode,
                base_url,
                warmup_requests,
                timeout_secs,
                output: output.clone().unwrap_or(cfg.bench.output),
            };

            // Graceful shutdown: on Ctrl+C, cancel the benchmark and still
            // report partial results. Exit code 0 if the run completed or was
            // cancelled cleanly; the report reflects whatever was collected.
            let cancel = tokio_util::sync::CancellationToken::new();
            let cancel_handle = cancel.clone();
            let bench_fut = momus_bench::run_bench_with_cancel(&test_plan, &config, &cancel_handle);
            tokio::pin!(bench_fut);

            let report = tokio::select! {
                r = &mut bench_fut => r?,
                _ = tokio::signal::ctrl_c() => {
                    cancel.cancel();
                    tracing::info!("Ctrl+C received — stopping benchmark and reporting partial results");
                    bench_fut.await?
                }
            };

            let want_html = match format {
                OutputFormat::Html => true,
                OutputFormat::Junit => false,
                OutputFormat::Json => false,
                OutputFormat::Text => false,
                OutputFormat::Auto => output
                    .as_ref()
                    .and_then(|p| p.extension())
                    .and_then(|e| e.to_str())
                    .map(|e| e == "html")
                    .unwrap_or(false),
            };

            let want_json = match format {
                OutputFormat::Json => true,
                OutputFormat::Html => false,
                OutputFormat::Junit => false,
                OutputFormat::Text => false,
                OutputFormat::Auto => output
                    .as_ref()
                    .and_then(|p| p.extension())
                    .and_then(|e| e.to_str())
                    .map(|e| e == "json")
                    .unwrap_or(false),
            };

            if want_json {
                let json = report.to_json()?;
                if let Some(path) = &output {
                    std::fs::create_dir_all(path.parent().unwrap_or(path))?;
                    std::fs::write(path, &json)?;
                    println!("JSON report written to: {}", path.display());
                } else {
                    println!("{json}");
                }
            } else if want_html {
                let html = report.to_html();
                if let Some(path) = &output {
                    std::fs::create_dir_all(path.parent().unwrap_or(path))?;
                    std::fs::write(path, &html)?;
                    println!("HTML report written to: {}", path.display());
                } else {
                    // stdout — just print the HTML
                    println!("{html}");
                }
            } else {
                println!("{report}");
            }

            Ok(())
        }
        Commands::Fuzz {
            plan,
            iterations,
            base_url,
            mutators: _mutators,
            timeout: _timeout,
        } => {
            let content = std::fs::read_to_string(&plan)
                .with_context(|| format!("Failed to read plan file '{}'", plan.display()))?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{}'", plan.display()))?;
            apply_auth_to_plan(&mut test_plan, &cfg.global.auth)?;

            let base_url = base_url.or(cfg.fuzz.base_url).or(cfg.global.base_url);
            let fuzz_output = cfg.fuzz.output.clone();

            let config = momus_fuzz::FuzzConfig {
                iterations: iterations.unwrap_or(cfg.fuzz.iterations),
                base_url,
                output: fuzz_output.clone(),
                ..Default::default()
            };
            let report = momus_fuzz::run_fuzz(&test_plan, &config).await?;
            println!("{report}");

            // Write report to output directory
            std::fs::create_dir_all(&fuzz_output)?;
            let report_json = serde_json::to_string_pretty(&report)?;
            std::fs::write(fuzz_output.join("fuzz-report.json"), &report_json)?;
            println!(
                "\nReport written to: {}/fuzz-report.json",
                fuzz_output.display()
            );
            Ok(())
        }
        Commands::Chaos {
            plan,
            base_url,
            experiment,
            interval,
        } => {
            let content = std::fs::read_to_string(&plan)
                .with_context(|| format!("Failed to read plan file '{}'", plan.display()))?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{}'", plan.display()))?;
            apply_auth_to_plan(&mut test_plan, &cfg.global.auth)?;

            let base_url = base_url.or(cfg.chaos.base_url).or(cfg.global.base_url);
            let interval_secs = interval.unwrap_or(cfg.chaos.interval_secs);

            // Parse experiments from CLI JSON strings, or fall back to config
            let experiments = if experiment.is_empty() {
                cfg.chaos.experiments.clone()
            } else {
                experiment
                    .iter()
                    .map(|s| {
                        serde_json::from_str::<momus_chaos::ChaosExperiment>(s)
                            .with_context(|| format!("Failed to parse chaos experiment JSON: {s}"))
                    })
                    .collect::<Result<Vec<_>>>()?
            };
            let chaos_output = cfg.chaos.output.clone();

            let config = momus_chaos::ChaosConfig {
                experiments,
                base_url,
                interval_secs,
                timeout_secs: cfg.chaos.timeout_secs,
                output: chaos_output.clone(),
            };
            let reports = momus_chaos::run_chaos(&test_plan, &config).await?;
            for report in &reports {
                println!("{report}");
            }

            // Write reports to output directory
            std::fs::create_dir_all(&chaos_output)?;
            let report_json = serde_json::to_string_pretty(&reports)?;
            std::fs::write(chaos_output.join("chaos-report.json"), &report_json)?;
            println!(
                "\nReport written to: {}/chaos-report.json",
                chaos_output.display()
            );
            Ok(())
        }
        Commands::Contract {
            plan,
            spec,
            base_url,
            strict,
            timeout,
        } => {
            let content = std::fs::read_to_string(&plan)
                .with_context(|| format!("Failed to read plan file '{}'", plan.display()))?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{}'", plan.display()))?;
            apply_auth_to_plan(&mut test_plan, &cfg.global.auth)?;

            let base_url = base_url.or(cfg.contract.base_url).or(cfg.global.base_url);
            let strict = strict.unwrap_or(cfg.contract.strict);
            let timeout_secs = timeout
                .or(Some(cfg.contract.timeout_secs))
                .or(Some(cfg.global.timeout_secs))
                .unwrap_or(30);
            let contract_output = cfg.contract.output.clone();

            let config = momus_contract::ContractConfig {
                spec_path: spec,
                base_url,
                strict,
                timeout_secs,
                output: contract_output.clone(),
            };
            let report = momus_contract::run_contract(&test_plan, &config).await?;
            println!("{report}");

            // Write report to output directory
            std::fs::create_dir_all(&contract_output)?;
            let report_json = serde_json::to_string_pretty(&report)?;
            std::fs::write(contract_output.join("contract-report.json"), &report_json)?;
            println!(
                "\nReport written to: {}/contract-report.json",
                contract_output.display()
            );
            Ok(())
        }
        Commands::Guard {
            plan,
            base_url,
            check_headers,
            check_cors,
            check_leaks,
            check_exposed,
            timeout,
        } => {
            let content = std::fs::read_to_string(&plan)
                .with_context(|| format!("Failed to read plan file '{}'", plan.display()))?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{}'", plan.display()))?;
            apply_auth_to_plan(&mut test_plan, &cfg.global.auth)?;

            let base_url = base_url.or(cfg.guard.base_url).or(cfg.global.base_url);
            let timeout_secs = timeout
                .or(Some(cfg.guard.timeout_secs))
                .or(Some(cfg.global.timeout_secs))
                .unwrap_or(30);
            let guard_output = cfg.guard.output.clone();

            let config = momus_guard::GuardConfig {
                base_url,
                check_headers: check_headers.unwrap_or(cfg.guard.check_headers),
                check_cors: check_cors.unwrap_or(cfg.guard.check_cors),
                check_leaks: check_leaks.unwrap_or(cfg.guard.check_leaks),
                check_exposed: check_exposed.unwrap_or(cfg.guard.check_exposed),
                timeout_secs,
                output: guard_output.clone(),
            };
            let report = momus_guard::run_guard(&test_plan, &config).await?;
            println!("{report}");

            // Write report to output directory
            std::fs::create_dir_all(&guard_output)?;
            let report_json = serde_json::to_string_pretty(&report)?;
            std::fs::write(guard_output.join("guard-report.json"), &report_json)?;
            println!(
                "\nReport written to: {}/guard-report.json",
                guard_output.display()
            );
            Ok(())
        }
        Commands::Diff {
            plan,
            baseline,
            target,
            diff_headers,
            diff_bodies,
            diff_status,
            timeout,
        } => {
            let content = std::fs::read_to_string(&plan)
                .with_context(|| format!("Failed to read plan file '{}'", plan.display()))?;
            let mut test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{}'", plan.display()))?;
            apply_auth_to_plan(&mut test_plan, &cfg.global.auth)?;

            let timeout_secs = timeout
                .or(Some(cfg.diff.timeout_secs))
                .or(Some(cfg.global.timeout_secs))
                .unwrap_or(30);
            let diff_output = cfg.diff.output.clone();

            let config = momus_diff::DiffConfig {
                baseline_url: baseline,
                target_url: target,
                diff_headers: diff_headers.unwrap_or(cfg.diff.diff_headers),
                diff_bodies: diff_bodies.unwrap_or(cfg.diff.diff_bodies),
                diff_status: diff_status.unwrap_or(cfg.diff.diff_status),
                timeout_secs,
                output: diff_output.clone(),
            };
            let report = momus_diff::run_diff(&test_plan, &config).await?;
            println!("{report}");

            // Write report to output directory
            std::fs::create_dir_all(&diff_output)?;
            let report_json = serde_json::to_string_pretty(&report)?;
            std::fs::write(diff_output.join("diff-report.json"), &report_json)?;
            println!(
                "\nReport written to: {}/diff-report.json",
                diff_output.display()
            );
            Ok(())
        }
        Commands::Plan { plan, output } => {
            let content = read_plan_content(&plan)?;
            let test_plan: TestPlan = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse test plan '{plan}'"))?;

            // CLI --output overrides config file output
            let output = if output.to_str() != Some("./output/plan") {
                output
            } else {
                cfg.plan.output
            };

            let display = test_plan.display_plan();
            let output_path = output.join("plan.txt");
            std::fs::create_dir_all(&output)?;
            std::fs::write(&output_path, &display)?;
            println!("Plan written to: {}", output_path.display());
            Ok(())
        }
        Commands::Completions { shell } => {
            use clap::CommandFactory;
            let mut cmd = Cli::command();
            let name = cmd.get_name().to_string();
            clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
            Ok(())
        }
        Commands::Docs => {
            let url = "https://docs.rs/momus";
            println!("Documentation: {url}");
            if std::env::var("MOMUS_OPEN_DOCS").as_deref() == Ok("1")
                && let Err(e) = open::that(url)
            {
                eprintln!("Could not open browser ({e}); docs are available at {url}");
            }
            Ok(())
        }
        Commands::Init { template, output } => {
            match template.as_str() {
                "plan" => {
                    let path = output.unwrap_or_else(|| PathBuf::from("test-plan.json"));
                    let skeleton = serde_json::json!({
                        "name": "my test plan",
                        "base_url": "http://localhost:8080",
                        "default_headers": {
                            "Accept": "application/json"
                        },
                        "steps": [
                            {
                                "type": "request",
                                "name": "health",
                                "method": "GET",
                                "url": "/health",
                                "assert": [
                                    { "status": 200 },
                                    { "valid_json": null }
                                ]
                            }
                        ]
                    });
                    let json = serde_json::to_string_pretty(&skeleton)?;
                    std::fs::write(&path, json)?;
                    println!("✓ Skeleton test plan written to: {}", path.display());
                }
                "config" => {
                    let path = output.unwrap_or_else(|| PathBuf::from("momus.toml"));
                    let content = r#"# Momus Configuration
# CLI flags override these values.

[global]
# Base URL for all requests (overrides the plan's base_url).
# base_url = "http://localhost:8080"

# Default headers sent with every request.
# [global.headers]
# Authorization = "Bearer your-token-here"

# Authentication applied as an `Authorization` header on every request.
# Set at most one of `bearer` or `basic`. Values support $ENV_VAR interpolation.
# All commands fall back to this unless they provide their own auth
# (e.g. `[run.auth]` or `momus fhir upload --username`).
# [global.auth]
# bearer = "$API_TOKEN"
# [global.auth.basic]
# username = "admin"
# password = "$API_PASSWORD"

# Request timeout in seconds (default: 30).
# timeout_secs = 60

[run]
# Output directory for results (default: ./output).
# output = "./results"

# Per-command auth overrides [global.auth].
# [run.auth]
# bearer = "$API_TOKEN"

[bench]
# Output directory for results (default: ./output).
# output = "./bench-results"

# Execution mode: Steady, MaxThroughput, or Soak.
# [bench.mode]
# type = "Steady"
# concurrency = 20
# duration_secs = 60

[fuzz]
# Output directory for results (default: ./output).
# output = "./fuzz-results"

# Number of mutations to generate per input (default: 1000).
# iterations = 5000

# Select specific mutators (empty = all).
# mutators = ["null_injection", "boundary"]

# Request timeout in seconds (default: 30).
# timeout_secs = 60

[chaos]
# Output directory for results (default: ./output).
# output = "./chaos-results"

# How long to wait between experiments in seconds (default: 5).
# interval_secs = 10

[contract]
# Output directory for results (default: ./output).
# output = "./contract-results"

# Path to the API spec file (OpenAPI YAML/JSON or GraphQL SDL).
# spec_path = "./api-spec.yaml"
# strict = true

# Request timeout in seconds (default: 30).
# timeout_secs = 60

[guard]
# Output directory for results (default: ./output).
# output = "./guard-results"

# Check for missing security headers (default: true).
# check_headers = true
# check_cors = true
# check_leaks = true
# check_exposed = true

# Request timeout in seconds (default: 30).
# timeout_secs = 60

[plan]
# Output directory for the plan display (default: ./output).
# output = "./plan-output"

[diff]
# Output directory for results (default: ./output).
# output = "./diff-results"

# Baseline environment URL (e.g. production).
# baseline_url = "https://prod.example.com"
# Target environment URL (e.g. staging).
# target_url = "https://staging.example.com"

# Diff response headers (default: true).
# diff_headers = true
# Diff response bodies (default: true).
# diff_bodies = true
# Diff status codes (default: true).
# diff_status = true

# Request timeout in seconds (default: 30).
# timeout_secs = 60
"#;
                    std::fs::write(&path, content)?;
                    println!("✓ Skeleton config written to: {}", path.display());
                }
                other => {
                    anyhow::bail!("Unknown template '{other}'. Available: plan, config");
                }
            }
            Ok(())
        }
        Commands::Fhir(cmd) => match cmd {
            FhirCommands::Mock { port } => {
                let addr = momus_mock::fhir::start_fhir_mock_server(port).await?;
                println!("FHIR mock server listening on http://{addr}");
                println!("Endpoints:");
                println!("  POST   /fhir/{{type}}        — create resource");
                println!("  GET    /fhir/{{type}}        — search resources");
                println!("  GET    /fhir/{{type}}/{{id}}  — read resource");
                println!("  PUT    /fhir/{{type}}/{{id}}  — update resource");
                println!("  DELETE /fhir/{{type}}/{{id}}  — delete resource");
                println!("Press Ctrl+C to stop.");
                // Keep the server running
                tokio::signal::ctrl_c().await?;
                Ok(())
            }
            FhirCommands::Validate {
                package,
                resource,
                profile,
            } => {
                // Profile resolution uses a blocking HTTP client; run it in a
                // blocking context so the client isn't dropped inside the async
                // runtime (which would panic).
                tokio::task::block_in_place(|| {
                    momus_convert::fhir_validate_resource(&package, &resource, profile.as_deref())
                })?;
                Ok(())
            }
            FhirCommands::Generate {
                package,
                count,
                output,
            } => {
                std::fs::create_dir_all(&output)?;
                // Profile resolution uses a blocking HTTP client; run it in a
                // blocking context so the client isn't dropped inside the async
                // runtime (which would panic).
                tokio::task::block_in_place(|| {
                    momus_convert::generate_fhir_bulk_test_data(&package, count, &output)
                })?;
                println!(
                    "✓ FHIR bulk test data written to {}/data/",
                    output.display()
                );
                Ok(())
            }
            FhirCommands::OpenApi {
                package,
                base_url,
                format,
                output,
            } => {
                let spec = match base_url {
                    Some(base_url) => {
                        momus_convert::fhir_server_to_openapi(&base_url, &format).await?
                    }
                    None => {
                        let package = package.as_deref().ok_or_else(|| {
                            anyhow::anyhow!(
                                "Provide a local IG package path or --base-url <FHIR server URL>"
                            )
                        })?;
                        momus_convert::fhir_ig_to_openapi(package, &format)?
                    }
                };
                match output {
                    Some(path) => {
                        std::fs::write(&path, &spec)?;
                        println!("OpenAPI spec written to: {}", path.display());
                    }
                    None => println!("{spec}"),
                }
                Ok(())
            }
            FhirCommands::Upload {
                data_dir,
                endpoint,
                method,
                username,
                password,
                concurrency,
            } => {
                let write_endpoint = write_endpoint_from_cli(
                    endpoint,
                    method,
                    username,
                    password,
                    concurrency,
                    &cfg.global.auth,
                )?;
                println!(
                    "Uploading FHIR NDJSON data from {} to {} ({})",
                    data_dir.display(),
                    write_endpoint.base_url(),
                    write_endpoint.upload_method(),
                );
                let ids = momus_convert::upload_fhir_bulk_data(&data_dir, &write_endpoint).await?;
                let total: usize = ids.values().map(|v| v.len()).sum();
                println!("✓ Uploaded {total} resources");
                for (rtype, type_ids) in &ids {
                    println!("  {rtype}: {} resources", type_ids.len());
                }
                println!(
                    "Run `momus fhir delete --endpoint {}` to clean up.",
                    write_endpoint.base_url()
                );
                Ok(())
            }
            FhirCommands::Delete {
                data_dir,
                endpoint,
                username,
                password,
                concurrency,
            } => {
                let write_endpoint = write_endpoint_from_cli(
                    endpoint,
                    "DELETE".to_string(),
                    username,
                    password,
                    concurrency,
                    &cfg.global.auth,
                )?;
                println!("Deleting FHIR resources from {}", write_endpoint.base_url());
                momus_convert::delete_fhir_bulk_data(&data_dir, &write_endpoint).await?;
                println!("✓ Cleanup complete");
                Ok(())
            }
        },
    }
}

/// Apply an [`AuthConfig`] as an `Authorization` header on a plan's default
/// headers. An `Authorization` header already present on the plan (or set via
/// `[global.headers]`) takes precedence and is never overwritten.
fn apply_auth_to_plan(test_plan: &mut TestPlan, auth: &AuthConfig) -> anyhow::Result<()> {
    if let Some(value) = auth.authorization_header()? {
        test_plan
            .default_headers
            .entry("Authorization".to_string())
            .or_insert(value);
    }
    Ok(())
}

/// Build a [`WriteEndpoint`] from CLI flags, falling back to `[global.auth]`.
///
/// If a username is supplied the endpoint is treated as a repository with
/// basic auth (its own auth); otherwise it falls back to the global auth
/// config, applied as an `Authorization` header.
fn write_endpoint_from_cli(
    endpoint: String,
    method: String,
    username: Option<String>,
    password: Option<String>,
    concurrency: usize,
    global_auth: &AuthConfig,
) -> anyhow::Result<momus_convert::WriteEndpoint> {
    match username {
        Some(user) => Ok(momus_convert::WriteEndpoint::Repository {
            base_url: endpoint,
            username: user,
            password: password.unwrap_or_default(),
            upload_method: method,
            concurrency,
        }),
        None => {
            // No explicit credentials — fall back to [global.auth].
            let mut headers = std::collections::HashMap::new();
            if let Some(value) = global_auth.authorization_header()? {
                headers.insert("Authorization".to_string(), value);
            }
            Ok(momus_convert::WriteEndpoint::Server {
                base_url: endpoint,
                headers,
                upload_method: method,
                concurrency,
            })
        }
    }
}

/// Print a dry-run summary of a test plan without sending any requests.
///
/// Resolves `{base_url}` and `{env.*}` templates statically where possible,
/// prints the resolved request list (method, URL, headers, body size, assertion
/// count), and exits non-zero on validation errors. Sensitive header values are
/// redacted, and request bodies are shown as a byte count only so no payload
/// data leaks to the console.
fn dry_run_plan(plan: &TestPlan) -> Result<()> {
    use std::collections::HashMap;

    println!("Dry-run of plan: '{}'", plan.name);
    if !plan.base_url.is_empty() {
        println!("Base URL: {}", plan.base_url);
    }

    let empty: HashMap<String, serde_json::Value> = HashMap::new();
    let mut total = 0usize;
    let mut validation_errors = Vec::new();

    for req in plan.request_steps() {
        let method = req.method;
        // Statically resolve {base_url} and {env.*} templates; step and random
        // templates cannot be resolved without executing, so leave them intact.
        let url = momus_core::engine::templates::resolve_url(&req.url, &plan.base_url, &empty);

        // Redact known secret-ish headers.
        let headers: Vec<String> = req
            .headers
            .iter()
            .map(|(k, v)| {
                let val = if is_sensitive_header(k) {
                    "[REDACTED]".to_string()
                } else {
                    v.clone()
                };
                format!("{k}: {val}")
            })
            .collect();

        let body_size = req
            .body
            .as_ref()
            .map(|b| serde_json::to_string(b).map(|s| s.len()).unwrap_or(0));

        println!(
            "  {method} {url}  [{}]",
            match body_size {
                Some(n) => format!("body={n} bytes"),
                None => "no body".to_string(),
            }
        );
        if !headers.is_empty() {
            for h in &headers {
                println!("      {h}");
            }
        }
        if !req.assert.is_empty() {
            println!("      assertions: {}", req.assert.len());
        }
        if !req.save_as.is_empty() {
            println!("      save_as: {}", req.save_as);
        }
        total += 1;

        if plan.base_url.is_empty() && !req.url.starts_with("http") {
            validation_errors.push(format!(
                "request '{}' has a relative URL '{}' but no base_url is set",
                req.name, req.url
            ));
        }
    }

    println!("\nTotal requests: {total}");
    if !validation_errors.is_empty() {
        for e in &validation_errors {
            eprintln!("  error: {e}");
        }
        anyhow::bail!(
            "plan failed dry-run validation: {} error(s)",
            validation_errors.len()
        );
    }
    println!("Dry-run OK: {} request(s) would be sent", total);
    Ok(())
}

/// Heuristic check for headers whose values should never be printed.
fn is_sensitive_header(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower.contains("authorization")
        || lower.contains("cookie")
        || lower.contains("token")
        || lower.contains("secret")
        || lower.contains("api-key")
        || lower.contains("apikey")
}

/// Read plan content from a file path or stdin.
fn read_plan_content(plan: &str) -> Result<String> {
    if plan == "-" {
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf)?;
        Ok(buf)
    } else {
        std::fs::read_to_string(plan).with_context(|| format!("Failed to read plan file '{plan}'"))
    }
}

/// Load config from explicit path, env var, or search default locations.
fn load_config(explicit: Option<&str>) -> Result<MomusConfig> {
    let path = match explicit {
        Some(p) => Some(p.to_string()),
        None => {
            // Search default locations
            let candidates = [
                "momus.toml",
                ".momus.toml",
                &dirs::config_dir()
                    .map(|d| d.join("momus").join("config.toml"))
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_default(),
            ];
            candidates
                .iter()
                .find(|p| !p.is_empty() && std::path::Path::new(p).exists())
                .map(|s| s.to_string())
        }
    };

    match path {
        Some(p) => {
            tracing::debug!("Loading config from: {}", p);
            let mut cfg = MomusConfig::load(&p)
                .with_context(|| format!("Failed to load config file '{p}'"))?;
            // Apply an environment profile selected via MOMUS_ENV (e.g. `[env.staging]`).
            if let Ok(env) = std::env::var("MOMUS_ENV") {
                cfg.apply_env(&env)?;
            }
            Ok(cfg)
        }
        None => Ok(MomusConfig::default()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use momus_core::config::BasicAuth;

    fn plan() -> TestPlan {
        TestPlan {
            name: "t".into(),
            base_url: "http://localhost".into(),
            default_headers: std::collections::HashMap::new(),
            steps: vec![],
            setup: vec![],
            teardown: vec![],
        }
    }

    #[test]
    fn apply_auth_to_plan_adds_bearer_header() {
        let mut p = plan();
        let auth = AuthConfig {
            bearer: Some("tok".into()),
            basic: None,
        };
        apply_auth_to_plan(&mut p, &auth).unwrap();
        assert_eq!(
            p.default_headers.get("Authorization").map(String::as_str),
            Some("Bearer tok")
        );
    }

    #[test]
    fn apply_auth_to_plan_adds_basic_header() {
        let mut p = plan();
        let auth = AuthConfig {
            bearer: None,
            basic: Some(BasicAuth {
                username: "u".into(),
                password: "p".into(),
            }),
        };
        apply_auth_to_plan(&mut p, &auth).unwrap();
        assert_eq!(
            p.default_headers.get("Authorization").map(String::as_str),
            Some("Basic dTpw")
        );
    }

    #[test]
    fn apply_auth_to_plan_keeps_existing_authorization() {
        let mut p = plan();
        p.default_headers
            .insert("Authorization".into(), "Bearer own".into());
        let auth = AuthConfig {
            bearer: Some("global".into()),
            basic: None,
        };
        apply_auth_to_plan(&mut p, &auth).unwrap();
        assert_eq!(
            p.default_headers.get("Authorization").map(String::as_str),
            Some("Bearer own")
        );
    }

    #[test]
    fn apply_auth_to_plan_empty_auth_is_noop() {
        let mut p = plan();
        apply_auth_to_plan(&mut p, &AuthConfig::default()).unwrap();
        assert!(p.default_headers.is_empty());
    }

    #[test]
    fn write_endpoint_uses_own_credentials_when_provided() {
        let ep = write_endpoint_from_cli(
            "http://srv".into(),
            "PUT".into(),
            Some("user".into()),
            Some("pass".into()),
            4,
            &AuthConfig::default(),
        )
        .unwrap();
        match ep {
            momus_convert::WriteEndpoint::Repository {
                username,
                password,
                upload_method,
                concurrency,
                ..
            } => {
                assert_eq!(username, "user");
                assert_eq!(password, "pass");
                assert_eq!(upload_method, "PUT");
                assert_eq!(concurrency, 4);
            }
            other => panic!("expected Repository, got {other:?}"),
        }
    }

    #[test]
    fn write_endpoint_falls_back_to_global_bearer() {
        let auth = AuthConfig {
            bearer: Some("tok".into()),
            basic: None,
        };
        let ep = write_endpoint_from_cli("http://srv".into(), "PUT".into(), None, None, 4, &auth)
            .unwrap();
        match ep {
            momus_convert::WriteEndpoint::Server { headers, .. } => {
                assert_eq!(
                    headers.get("Authorization").map(String::as_str),
                    Some("Bearer tok")
                );
            }
            other => panic!("expected Server, got {other:?}"),
        }
    }

    #[test]
    fn write_endpoint_falls_back_to_global_basic() {
        let auth = AuthConfig {
            bearer: None,
            basic: Some(BasicAuth {
                username: "u".into(),
                password: "p".into(),
            }),
        };
        let ep = write_endpoint_from_cli("http://srv".into(), "PUT".into(), None, None, 4, &auth)
            .unwrap();
        match ep {
            momus_convert::WriteEndpoint::Server { headers, .. } => {
                assert_eq!(
                    headers.get("Authorization").map(String::as_str),
                    Some("Basic dTpw")
                );
            }
            other => panic!("expected Server, got {other:?}"),
        }
    }

    #[test]
    fn write_endpoint_no_auth_yields_empty_headers() {
        let ep = write_endpoint_from_cli(
            "http://srv".into(),
            "PUT".into(),
            None,
            None,
            4,
            &AuthConfig::default(),
        )
        .unwrap();
        match ep {
            momus_convert::WriteEndpoint::Server { headers, .. } => assert!(headers.is_empty()),
            other => panic!("expected Server, got {other:?}"),
        }
    }
}