mrapids 0.1.31

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

#[derive(Parser)]
#[command(name = "mrapids")]
#[command(about = "Your OpenAPI, but executable", long_about = None)]
#[command(version)]
#[command(before_help = crate::core::banner::get_help_header())]
#[command(after_help = get_help_footer())]
#[command(override_help = get_grouped_help())]
pub struct Args {
    #[command(subcommand)]
    pub command: Commands,

    /// Global: Environment name (dev, staging, prod)
    #[arg(long, global = true, value_name = "ENV")]
    pub env: Option<String>,

    /// Global: Output format (json, yaml, table, pretty)
    #[arg(long = "output-format", global = true, value_name = "FORMAT")]
    pub output_format: Option<String>,

    /// Global: Suppress all output except errors
    #[arg(long, short = 'q', global = true)]
    pub quiet: bool,

    /// Global: Enable verbose output
    #[arg(long, short = 'v', global = true)]
    pub verbose: bool,

    /// Global: Enable trace output (includes HTTP requests/responses)
    #[arg(long, global = true)]
    pub trace: bool,

    /// Global: Disable colored output
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Global: Output as JSON (agent-friendly structured output)
    #[arg(long, global = true, help_heading = "Agent Automation")]
    pub json: bool,

    /// Global: Machine-readable mode (no colors, no decorations, structured output)
    #[arg(long, global = true, help_heading = "Agent Automation")]
    pub machine: bool,
}

#[derive(Subcommand)]
pub enum Commands {
    // === GETTING STARTED ===
    /// Initialize a new MicroRapid project from OpenAPI/GraphQL specs
    #[command(display_order = 1)]
    Init(InitCommand),

    /// Discover what operations are available in your API
    #[command(alias = "search", alias = "discover", display_order = 2)]
    Explore(ExploreCommand),

    /// Show detailed information about specific operations
    #[command(display_order = 3)]
    Show(ShowCommand),

    /// Ensure your OpenAPI specification is correct
    #[command(display_order = 4)]
    Validate(ValidateCommand),

    // === EXECUTION & TESTING ===
    /// Execute API operations directly from specifications
    #[command(display_order = 5)]
    Run(RunCommand),

    /// Run automated tests against your API
    #[command(display_order = 6)]
    Test(TestCommand),

    /// List available operations, requests, or resources
    #[command(display_order = 7)]
    List(ListCommand),

    // === CODE GENERATION ===
    /// Generate SDKs, examples, test fixtures, and code
    #[command(alias = "generate", display_order = 8)]
    Gen(GenCommand),

    /// Resolve all $ref references in your specification
    #[command(display_order = 9)]
    Flatten(FlattenCommand),

    // === AUTOMATION & WORKFLOWS ===
    /// Manage and run complex API request collections
    #[command(display_order = 10)]
    Collection(CollectionCommand),

    /// Set up complete test environment automatically
    #[command(alias = "tests-init", display_order = 11)]
    SetupTests(SetupTestsCommand),

    // === CONFIGURATION ===
    /// Comprehensive authentication management (detect, connect, validate, OAuth)
    #[command(display_order = 12)]
    Auth(AuthCommand),

    /// Manage environment configurations
    #[command(display_order = 13)]
    Env(EnvCommand),

    // === UTILITIES ===
    /// Compare specifications for breaking changes
    #[command(display_order = 14)]
    Diff(DiffCommand),

    /// Clean up test artifacts and temporary files
    #[command(display_order = 15)]
    Cleanup(CleanupCommand),

    /// Diagnose configuration, auth, spec, and environment issues with auto-fix
    #[command(display_order = 16)]
    Doctor(DoctorCommand),

    // === ANALYTICS ===
    /// Local analytics database powered by DuckDB
    #[command(display_order = 17)]
    Db(DbCommand),

    /// Query API history with SQL - your requests become a queryable database
    #[command(display_order = 18)]
    Sql(SqlCommand),

    /// Compare two API runs and identify differences (reconciliation)
    #[command(display_order = 19)]
    Compare(CompareCommand),

    /// Show API run history - see all past executions at a glance
    #[command(display_order = 20)]
    History(HistoryCommand),

    /// Export data to Parquet, CSV, or JSON for external analysis
    #[command(display_order = 21)]
    Export(ExportCommand),

    // === AGENT / SEMANTIC SEARCH ===
    /// Build and manage operation index for semantic search
    #[command(display_order = 22)]
    Index(IndexCommand),

    /// Find operations using semantic search
    #[command(display_order = 23)]
    Find(FindCommand),

    // === PLANNING ===
    /// Sketch execution plans from operations or collections (read-only, no execution)
    #[command(display_order = 25)]
    Plan(PlanCommand),

    // === SECURITY & GOVERNANCE ===
    /// Manage agent access policies (init, validate, report)
    #[command(display_order = 24)]
    Policy(PolicyCommand),

    // === MCP SERVER ===
    /// MCP (Model Context Protocol) server for AI agent integration
    #[command(display_order = 26)]
    Mcp(McpCommand),
}

#[derive(Parser)]
pub struct PolicyCommand {
    #[command(subcommand)]
    pub command: PolicySubcommand,
}

#[derive(Subcommand)]
pub enum PolicySubcommand {
    /// Generate a starter policy from your API spec
    Init {
        /// Path to the OpenAPI spec
        #[arg(long)]
        spec: Option<PathBuf>,

        /// Output path (default: .mrapids/policy.yaml)
        #[arg(long, short)]
        output: Option<PathBuf>,

        /// Read-only mode (block all writes)
        #[arg(long)]
        read_only: bool,

        /// Apply a compliance preset (hipaa, pci, sox)
        #[arg(long)]
        preset: Option<String>,
    },

    /// Validate a policy file for errors
    Validate {
        /// Path to policy file (default: auto-detect)
        #[arg(long)]
        policy: Option<PathBuf>,
    },

    /// Show a human-readable policy report
    Report {
        /// Path to policy file (default: auto-detect)
        #[arg(long)]
        policy: Option<PathBuf>,
    },
}

#[derive(Parser)]
pub struct ValidateCommand {
    /// Path to the OpenAPI/Swagger specification file
    pub spec: PathBuf,

    /// Strict mode - treat warnings as errors
    #[arg(long)]
    pub strict: bool,

    /// Enable linting for best practices and style issues
    #[arg(long)]
    pub lint: bool,

    /// Custom linting rules file
    #[arg(long, requires = "lint")]
    pub rules: Option<PathBuf>,

    /// Output format (text or json)
    #[arg(short, long, value_enum, default_value = "text")]
    pub format: ValidateFormat,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ValidateFormat {
    /// Human-readable text format
    Text,
    /// JSON format for tooling
    Json,
}

#[derive(Parser)]
pub struct InitCommand {
    /// Project name (defaults to current directory name)
    #[arg(default_value = "my-api-project")]
    pub name: String,

    /// Project template (minimal, rest, graphql)
    #[arg(short, long, default_value = "rest")]
    pub template: String,

    /// Initialize from a URL (downloads OpenAPI/GraphQL schema)
    #[arg(long, value_name = "URL", conflicts_with = "from_file")]
    pub from_url: Option<String>,

    /// Initialize from a local file (OpenAPI/GraphQL schema)
    #[arg(long, value_name = "FILE", conflicts_with = "from_url")]
    pub from_file: Option<String>,

    /// Force overwrite if directory exists
    #[arg(short, long)]
    pub force: bool,

    /// Allow insecure HTTP connections when downloading specs (not recommended)
    #[arg(long)]
    pub allow_insecure: bool,
}

#[derive(Parser, Clone)]
#[command(
    args_override_self = true,
    after_help = "AGENT/AUTOMATION:
    --json-output     Structured JSON with run_id, metadata, request/response
    --machine         No colors, no decorations
    Exit codes:       0=success  2=args  3=auth  4=network  5=rate-limit  7=validation

WORKFLOW:
    mrapids run <operation> -Q                   # See parameters + copy-ready command
    mrapids run <operation> --param key=value    # Execute with parameters
    mrapids run <operation> --json-output        # JSON for scripts/agents

COPY-READY EXAMPLES:
    # 1. Discover what parameters an operation needs
    mrapids run getPetById -Q

    # 2. Execute GET with path/query parameters
    mrapids run getPetById --param petId=1

    # 3. Execute POST with JSON body
    mrapids run createUser --data '{\"name\": \"john\", \"email\": \"john@example.com\"}'

    # 4. Use saved auth profile
    mrapids run getProfile --profile github

    # 5. JSON output for scripts/agents
    mrapids run listUsers --param limit=10 --json-output

    # 6. Preview as curl (don't send)
    mrapids run getUser --param id=123 --as-curl

    # 7. Dry run (preview request without sending)
    mrapids run createOrder --data @order.json --dry-run

TIPS:
    • Parameters are auto URL-encoded - pass plain text
    • Use quotes for spaces: --param q=\"status:active type:user\"
    • Read body from file: --data @request.json or --file request.json
    • Save response: --save response.json"
)]
pub struct RunCommand {
    /// Operation ID (e.g., users/get, repos/create) or path to request config file
    #[arg(required_unless_present_any = ["list_queries", "load_query"])]
    pub operation: Option<String>,

    /// Path to OpenAPI/Swagger specification file (auto-detected if not provided)
    #[arg(
        short = 's',
        long,
        value_name = "FILE",
        help_heading = "Spec Selection"
    )]
    pub spec: Option<PathBuf>,

    // === DATA INPUT ===
    /// Request body as JSON string or @file.json
    #[arg(short, long, conflicts_with = "file", help_heading = "Data Input")]
    pub data: Option<String>,

    /// Read request body from file
    #[arg(short, long, conflicts_with = "data", help_heading = "Data Input")]
    pub file: Option<PathBuf>,

    // === COMMON PARAMETERS ===
    /// Resource ID (auto-mapped to path/query parameters)
    #[arg(long, help_heading = "Common Parameters")]
    pub id: Option<String>,

    /// Resource name
    #[arg(long, help_heading = "Common Parameters")]
    pub name: Option<String>,

    /// Filter by status
    #[arg(long, help_heading = "Common Parameters")]
    pub status: Option<String>,

    /// Limit number of results
    #[arg(long, help_heading = "Common Parameters")]
    pub limit: Option<u32>,

    /// Offset for pagination
    #[arg(long, help_heading = "Common Parameters")]
    pub offset: Option<u32>,

    /// Sort order
    #[arg(long, help_heading = "Common Parameters")]
    pub sort: Option<String>,

    // === REQUEST PARAMETERS ===
    /// Set any parameter: --param key=value (can be used multiple times)
    #[arg(
        long = "param",
        value_name = "KEY=VALUE",
        help_heading = "Request Parameters"
    )]
    pub params: Vec<String>,

    /// Force query parameters: --query key=value (can be used multiple times)
    #[arg(
        long = "query",
        value_name = "KEY=VALUE",
        help_heading = "Request Parameters"
    )]
    pub query_params: Vec<String>,

    /// Add HTTP headers: --header "Key: Value" (can be used multiple times)
    #[arg(
        short = 'H',
        long = "header",
        value_name = "KEY: VALUE",
        help_heading = "Request Parameters"
    )]
    pub headers: Vec<String>,

    // === AUTHENTICATION ===
    /// Bearer token or Basic auth (e.g., "Bearer token123" or "Basic base64")
    #[arg(long, conflicts_with = "auth_profile", help_heading = "Authentication")]
    pub auth: Option<String>,

    /// API key for X-API-Key header
    #[arg(long, conflicts_with = "auth_profile", help_heading = "Authentication")]
    pub api_key: Option<String>,

    /// Use saved OAuth/auth profile
    #[arg(long = "profile", value_name = "PROFILE", conflicts_with_all = &["auth", "api_key"], help_heading = "Authentication")]
    pub auth_profile: Option<String>,

    /// Environment to use (dev, staging, prod)
    #[arg(short, long)]
    pub env: Option<String>,

    /// Base URL to override default
    #[arg(short, long)]
    pub url: Option<String>,

    /// Output format (json, yaml, table, pretty)
    #[arg(short, long, default_value = "pretty")]
    pub output: String,

    /// Save response to file
    #[arg(long)]
    pub save: Option<PathBuf>,

    /// Use template file
    #[arg(long)]
    pub template: Option<String>,

    /// Set template variables: --set key=value (can be used multiple times)
    #[arg(long = "set", value_name = "KEY=VALUE")]
    pub template_vars: Vec<String>,

    // === OUTPUT & DEBUGGING ===
    /// Use only required fields in requests
    #[arg(long, help_heading = "Testing & Debugging")]
    pub required_only: bool,

    /// Show detailed request/response info
    #[arg(short, long, help_heading = "Testing & Debugging")]
    pub verbose: bool,

    /// Preview request without sending
    #[arg(long, help_heading = "Testing & Debugging")]
    pub dry_run: bool,

    /// Show equivalent curl command
    #[arg(long, help_heading = "Testing & Debugging")]
    pub as_curl: bool,

    /// Log decision records for debugging agent behavior
    /// Saves to ~/.mrapids/decisions.jsonl
    #[arg(long, help_heading = "Testing & Debugging")]
    pub log_decisions: bool,

    /// Edit generated data before sending
    #[arg(long, help_heading = "Data Input")]
    pub edit: bool,

    /// Read request body from stdin
    #[arg(long, help_heading = "Data Input")]
    pub stdin: bool,

    // === REQUEST OPTIONS ===
    /// Number of retries for failed requests
    #[arg(long, default_value = "0", help_heading = "Request Options")]
    pub retry: u32,

    /// Request timeout in seconds
    #[arg(long, default_value = "30", help_heading = "Request Options")]
    pub timeout: u32,

    /// Allow insecure HTTPS connections (skip certificate validation)
    #[arg(long, help_heading = "Security")]
    pub allow_insecure: bool,

    /// Allow connections to localhost and private IPs (for development)
    #[arg(long, help_heading = "Security")]
    pub allow_localhost: bool,

    /// Suppress warnings about sensitive data in requests
    #[arg(long, help_heading = "Security")]
    pub no_warnings: bool,

    /// Redact sensitive data (passwords, tokens, SSN, cards) from responses
    #[arg(long, help_heading = "Security")]
    pub redact: bool,

    // === INTERACTIVE MODE ===
    /// Generate interactive template (saves to file for editing)
    #[arg(short = 'i', long, conflicts_with_all = &["data", "file", "stdin"], help_heading = "Interactive Mode")]
    pub interactive: bool,

    /// Save template with custom filename (used with -i)
    #[arg(
        long,
        requires = "interactive",
        value_name = "FILE",
        help_heading = "Interactive Mode"
    )]
    pub save_as: Option<PathBuf>,

    /// Include only required fields in template
    #[arg(long, requires = "interactive", help_heading = "Interactive Mode")]
    pub minimal: bool,

    // === QUERY ASSISTANCE ===
    /// Show query syntax help for filter parameters
    #[arg(long, help_heading = "Query Assistance")]
    pub help_query: bool,

    /// Show parameters and ready-to-copy command for an operation (spec-driven)
    #[arg(short = 'Q', long, conflicts_with_all = &["data", "file", "stdin", "interactive"], help_heading = "Query Assistance")]
    pub build_query: bool,

    /// Load query from file
    #[arg(long, value_name = "FILE", help_heading = "Query Assistance")]
    pub query_file: Option<PathBuf>,

    /// Replay last successful query for this operation
    #[arg(long, help_heading = "Query Assistance")]
    pub replay_last: bool,

    /// Save current query parameters for reuse (e.g., --save-query active-users)
    #[arg(long, value_name = "NAME", help_heading = "Query Assistance")]
    pub save_query: Option<String>,

    /// Load and run a previously saved query (e.g., --load-query active-users)
    #[arg(long, value_name = "NAME", help_heading = "Query Assistance")]
    pub load_query: Option<String>,

    /// List all saved queries
    #[arg(long, help_heading = "Query Assistance")]
    pub list_queries: bool,

    // === COLLECTION SAVE ===
    /// Save successful request to a collection
    #[arg(long, help_heading = "Collection Management")]
    pub save_to_collection: bool,

    /// Collection name to save to (default: daily-YYYY-MM-DD)
    #[arg(long, value_name = "NAME", help_heading = "Collection Management")]
    pub collection: Option<String>,

    /// Custom name for the saved request
    #[arg(
        long,
        value_name = "NAME",
        requires = "save_to_collection",
        help_heading = "Collection Management"
    )]
    pub save_as_request: Option<String>,

    // === AGENT AUTOMATION ===
    /// Output as JSON (agent-friendly structured output with run_id, metadata)
    #[arg(long, help_heading = "Agent Automation")]
    pub json_output: bool,
}

#[derive(Parser)]
pub struct TestCommand {
    /// Path to the OpenAPI specification file
    pub spec: PathBuf,

    /// Test all operations
    #[arg(long)]
    pub all: bool,

    /// Specific operation to test
    #[arg(short, long)]
    pub operation: Option<String>,

    /// Automatically clean up test artifacts after completion
    #[arg(long, default_value = "true")]
    pub cleanup: bool,

    /// Keep test artifacts even after cleanup (for debugging)
    #[arg(long)]
    pub keep_artifacts: bool,

    /// Allow insecure HTTP connections (not recommended)
    #[arg(long)]
    pub allow_insecure: bool,

    /// Suppress security warnings about request content
    #[arg(long)]
    pub no_warnings: bool,
}

// Still used internally by gen snippets
#[derive(Parser)]
pub struct AnalyzeCommand {
    /// Path to the OpenAPI/Swagger specification file
    pub spec: Option<PathBuf>,

    /// Analyze specific operation only
    #[arg(short, long)]
    pub operation: Option<String>,

    /// Output directory for generated examples (defaults to current directory)
    #[arg(short = 'd', long, default_value = ".")]
    pub output: PathBuf,

    /// Generate examples for all operations
    #[arg(long)]
    pub all: bool,

    /// Skip generating data files for request bodies
    #[arg(long)]
    pub skip_data: bool,

    /// Skip OpenAPI validation
    #[arg(long)]
    pub skip_validate: bool,

    /// Overwrite existing files
    #[arg(short, long)]
    pub force: bool,

    /// Clean up old backup directories after analysis
    #[arg(long, default_value = "true")]
    pub cleanup_backups: bool,
}

#[derive(Parser)]
pub struct ListCommand {
    /// What to list: operations, requests, or all
    #[arg(value_enum, default_value = "operations")]
    pub resource: ListResource,

    /// Path to OpenAPI specification file (optional)
    pub spec: Option<PathBuf>,

    /// Filter results by text
    #[arg(short, long)]
    pub filter: Option<String>,

    /// Filter by HTTP method
    #[arg(short, long)]
    pub method: Option<String>,

    /// Filter by tag (for operations)
    #[arg(short, long)]
    pub tag: Option<String>,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: ListFormat,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ListResource {
    /// List operations from API spec
    Operations,
    /// List saved request configurations
    Requests,
    /// List all resources
    All,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ListFormat {
    /// Table format with borders
    Table,
    /// Simple list format
    Simple,
    /// JSON output
    Json,
    /// YAML output
    Yaml,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum GenerateTarget {
    /// TypeScript/JavaScript with Fetch API
    Typescript,
    /// Python with Requests
    Python,
    /// Go with net/http
    Go,
    /// Rust with reqwest
    Rust,
    /// Java with OkHttp
    Java,
    /// C# with HttpClient
    Csharp,
    /// Ruby with Net::HTTP
    Ruby,
    /// PHP with Guzzle
    Php,
    /// Swift with URLSession
    Swift,
    /// Kotlin with Ktor
    Kotlin,
    /// cURL commands
    Curl,
    /// Postman collection
    Postman,
}

#[derive(Parser)]
pub struct SetupTestsCommand {
    /// Path to the OpenAPI/Swagger specification file
    pub spec: PathBuf,

    /// Output format for test setup
    #[arg(short, long, value_enum, default_value = "npm")]
    pub format: TestSetupFormat,

    /// Output directory or file
    #[arg(short, long, default_value = ".")]
    pub output: PathBuf,

    /// Overwrite existing files
    #[arg(long)]
    pub force: bool,

    /// Show what would be generated without creating files
    #[arg(long)]
    pub dry_run: bool,

    /// Include example usage in generated files
    #[arg(long)]
    pub with_examples: bool,

    /// Generate .env.example file
    #[arg(long)]
    pub with_env: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum TestSetupFormat {
    /// NPM package.json with scripts (cross-platform)
    Npm,
    /// Makefile for Unix/Mac
    Make,
    /// Shell script for automation
    Shell,
    /// Docker Compose for containers
    Compose,
    /// Direct cURL commands (no mrapids needed)
    Curl,
    /// Generate all formats
    All,
}

#[derive(Parser)]
pub struct CleanupCommand {
    /// Clean all test artifacts in current directory
    #[arg(long, default_value = "true")]
    pub test_artifacts: bool,

    /// Clean empty directories
    #[arg(long, default_value = "true")]
    pub empty_dirs: bool,

    /// Clean backup directories (.backup, .old, etc)
    #[arg(long, default_value = "true")]
    pub backups: bool,

    /// Preserve directories containing spec files
    #[arg(long, default_value = "true")]
    pub preserve_specs: bool,

    /// Target directory to clean (defaults to current directory)
    #[arg(short, long, default_value = ".")]
    pub path: PathBuf,

    /// Dry run - show what would be deleted without actually deleting
    #[arg(long)]
    pub dry_run: bool,
}

#[derive(Parser)]
pub struct DoctorCommand {
    /// Automatically fix issues where possible
    #[arg(long)]
    pub fix: bool,

    /// Check specific aspect (all, config, auth, spec, env)
    #[arg(long, default_value = "all")]
    pub check: String,

    /// Path to project directory (defaults to current directory)
    #[arg(short, long, default_value = ".")]
    pub path: PathBuf,

    /// Output format (text, json)
    #[arg(short, long, default_value = "text")]
    pub format: String,

    /// Verbose output with more details
    #[arg(short, long)]
    pub verbose: bool,
}

#[derive(Parser)]
pub struct ShowCommand {
    /// Operation to show details for (e.g., create-customer, list-users)
    pub operation: String,

    /// Path to the API specification file
    pub spec: Option<PathBuf>,

    /// Show examples for the operation
    #[arg(long)]
    pub examples: bool,

    /// Generate and display JSON template for the operation
    #[arg(long)]
    pub template: bool,

    /// Output format
    #[arg(short, long, value_enum, default_value = "pretty")]
    pub format: ShowFormat,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ShowFormat {
    /// Human-readable format with colors
    Pretty,
    /// JSON output
    Json,
    /// YAML output
    Yaml,
}

#[derive(Parser)]
pub struct ExploreCommand {
    /// Keyword to search for in operations, paths, and descriptions
    pub keyword: String,

    /// Path to the API specification file (defaults to specs/api.yaml)
    #[arg(short, long)]
    pub spec: Option<PathBuf>,

    /// Maximum number of results to show per category
    #[arg(short, long, default_value = "5")]
    pub limit: usize,

    /// Show detailed results including descriptions
    #[arg(long)]
    pub detailed: bool,

    /// Output format
    #[arg(short, long, value_enum, default_value = "pretty")]
    pub format: ExploreFormat,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ExploreFormat {
    /// Human-readable format with colors and grouping
    Pretty,
    /// Simple list format
    Simple,
    /// JSON output for machine processing
    Json,
}

#[derive(Parser)]
pub struct AuthCommand {
    #[command(subcommand)]
    pub command: AuthCommands,
}

#[derive(Parser)]
pub struct EnvCommand {
    #[command(subcommand)]
    pub command: EnvCommands,
}

#[derive(Subcommand)]
pub enum EnvCommands {
    /// List all available environments
    List {
        /// Show detailed information including config files and env files
        #[arg(short, long)]
        verbose: bool,
    },

    /// Show details about a specific environment
    Show {
        /// Environment name
        environment: String,

        /// Show full configuration (including resolved variables)
        #[arg(short, long)]
        full: bool,
    },

    /// Create a new environment configuration
    Create {
        /// Environment name
        name: String,

        /// Copy from existing environment
        #[arg(long)]
        from: Option<String>,

        /// Base URL for the environment
        #[arg(long)]
        base_url: Option<String>,
    },

    /// Validate environment configurations
    Validate {
        /// Specific environment to validate (or all if not specified)
        environment: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum AuthCommands {
    /// Login to an OAuth provider
    Login {
        /// Provider name (github, google, microsoft, etc.) or 'custom' for custom provider
        provider: String,

        /// Client ID (required for custom providers)
        #[arg(long)]
        client_id: Option<String>,

        /// Client Secret (for custom providers)
        #[arg(long)]
        client_secret: Option<String>,

        /// Authorization URL (required for custom providers)
        #[arg(long)]
        auth_url: Option<String>,

        /// Token URL (required for custom providers)
        #[arg(long)]
        token_url: Option<String>,

        /// OAuth scopes to request (space-separated)
        #[arg(long, value_delimiter = ' ')]
        scopes: Vec<String>,

        /// Profile name (defaults to provider name)
        #[arg(long)]
        profile: Option<String>,

        /// Show provider-specific setup instructions
        #[arg(long)]
        setup_help: bool,
    },

    /// List stored auth profiles
    List {
        /// Show detailed information
        #[arg(long)]
        detailed: bool,
    },

    /// Show auth profile details
    Show {
        /// Profile name to show
        profile: String,

        /// Show decrypted tokens (security warning)
        #[arg(long)]
        show_tokens: bool,
    },

    /// Refresh tokens for a profile
    Refresh {
        /// Profile name to refresh
        profile: String,
    },

    /// Remove auth profile
    Logout {
        /// Profile name to remove
        profile: String,

        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,
    },

    /// Test authentication by making a simple API call
    Test {
        /// Profile name to test
        profile: String,
    },

    /// Show setup instructions for a provider
    Setup {
        /// Provider name (github, google, microsoft, etc.)
        provider: String,
    },

    /// Detect and analyze authentication requirements from OpenAPI spec
    Detect {
        /// Path to OpenAPI specification file
        #[arg(short, long)]
        spec: Option<String>,

        /// Output format
        #[arg(short, long, value_enum, default_value = "table")]
        format: DetectOutputFormat,

        /// Show detailed operation-level requirements
        #[arg(long)]
        operations: bool,

        /// Show only summary without scheme details
        #[arg(long)]
        summary_only: bool,
    },

    /// Connect and configure authentication credentials
    Connect {
        /// Authentication scheme name from OpenAPI spec
        scheme: String,

        /// Auth type (api-key, bearer, basic, oauth2, oidc, mtls)
        #[arg(short = 't', long)]
        auth_type: Option<String>,

        /// API key value (for api-key type)
        #[arg(long, conflicts_with_all = &["token", "username"])]
        api_key: Option<String>,

        /// Bearer token (for bearer type)
        #[arg(long, conflicts_with_all = &["api_key", "username"])]
        token: Option<String>,

        /// Username (for basic auth)
        #[arg(long, requires = "password", conflicts_with_all = &["api_key", "token"])]
        username: Option<String>,

        /// Password (for basic auth)
        #[arg(long, requires = "username")]
        password: Option<String>,

        /// OAuth2 flow type
        #[arg(long, value_enum)]
        flow: Option<OAuth2FlowType>,

        /// Client ID (for OAuth2)
        #[arg(long)]
        client_id: Option<String>,

        /// Client secret (for OAuth2)
        #[arg(long)]
        client_secret: Option<String>,

        /// Scopes to request (for OAuth2)
        #[arg(long)]
        scopes: Option<String>,

        /// Non-interactive mode (fail if input needed)
        #[arg(long)]
        non_interactive: bool,

        /// Force overwrite existing configuration
        #[arg(short, long)]
        force: bool,

        /// Environment to save credentials to (default: local)
        #[arg(short, long, default_value = "local")]
        env: String,
    },

    /// Validate configured authentication credentials
    Validate {
        /// Specific scheme to validate (validates all if not specified)
        #[arg(short, long)]
        scheme: Option<String>,

        /// OpenAPI specification file
        #[arg(long)]
        spec: Option<String>,

        /// Test endpoint to validate against
        #[arg(short = 'e', long)]
        endpoint: Option<String>,

        /// Show detailed validation output
        #[arg(short, long)]
        verbose: bool,

        /// Enable debug mode for troubleshooting
        #[arg(long)]
        debug: bool,

        /// Perform quick validation (skip endpoint tests)
        #[arg(short, long)]
        quick: bool,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum DetectOutputFormat {
    /// Human-readable table format
    Table,
    /// JSON format for programmatic consumption
    Json,
    /// YAML format for configuration files
    Yaml,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum OAuth2FlowType {
    /// Client credentials flow
    ClientCredentials,
    /// Authorization code flow
    AuthorizationCode,
    /// Device code flow
    DeviceCode,
    /// Password flow (deprecated)
    Password,
}

#[derive(Parser)]
pub struct FlattenCommand {
    /// Path to the OpenAPI/Swagger specification file
    pub spec: PathBuf,

    /// Output file path (defaults to stdout if not specified)
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Output format (json or yaml)
    #[arg(short, long, value_enum, default_value = "yaml")]
    pub format: FlattenFormat,

    /// Include schemas that are not referenced
    #[arg(long)]
    pub include_unused: bool,

    /// Resolve external references (http:// or file paths)
    #[arg(long)]
    pub resolve_external: bool,

    /// Allow insecure HTTP connections when resolving external references (not recommended)
    #[arg(long)]
    pub allow_insecure: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum FlattenFormat {
    /// YAML format
    Yaml,
    /// JSON format  
    Json,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum SdkLanguage {
    /// TypeScript (fetch-based)
    Typescript,
    /// Python (httpx-based)
    Python,
    /// Go (net/http-based)
    Go,
    /// Rust (reqwest-based)
    Rust,
}

#[derive(Parser)]
pub struct DiffCommand {
    /// Path to the old OpenAPI/Swagger specification file
    pub old_spec: PathBuf,

    /// Path to the new OpenAPI/Swagger specification file  
    pub new_spec: PathBuf,

    /// Only show breaking changes
    #[arg(long, alias = "breaking")]
    pub breaking_only: bool,

    /// Output format (text, json, markdown)
    #[arg(short, long, value_enum, default_value = "text")]
    pub format: DiffFormat,

    /// Exit with non-zero code if breaking changes found
    #[arg(long)]
    pub fail_on_breaking: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum DiffFormat {
    /// Human-readable text format
    Text,
    /// JSON format for tooling
    Json,
    /// Markdown format for PRs
    Markdown,
}

#[derive(Parser)]
pub struct GenCommand {
    #[command(subcommand)]
    pub target: GenTarget,
}

#[derive(Subcommand)]
pub enum GenTarget {
    /// Generate example requests and responses (replaces 'analyze')
    Snippets(GenSnippetsCommand),

    /// Generate SDK client library (replaces 'sdk')
    Sdk(GenSdkCommand),

    /// Generate server stubs (replaces 'generate')
    Stubs(GenStubsCommand),

    /// Generate test fixtures and sample data
    Fixtures(GenFixturesCommand),
}

#[derive(Parser)]
pub struct GenSnippetsCommand {
    /// Path to the OpenAPI specification
    pub spec: Option<PathBuf>,

    /// Output directory for examples
    #[arg(short, long, default_value = "./examples")]
    pub output: PathBuf,

    /// Operation ID to generate examples for (all if not specified)
    #[arg(long)]
    pub operation: Option<String>,

    /// Example format
    #[arg(long, value_enum, default_value = "json")]
    pub format: SnippetFormat,

    /// Include curl examples
    #[arg(long)]
    pub curl: bool,

    /// Include HTTPie examples
    #[arg(long)]
    pub httpie: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum SnippetFormat {
    Json,
    Yaml,
    Curl,
    Httpie,
    All,
}

#[derive(Parser)]
pub struct GenSdkCommand {
    /// Path to the OpenAPI specification
    pub spec: Option<PathBuf>,

    /// Target language
    #[arg(short, long, value_enum)]
    pub language: SdkLanguage,

    /// Output directory
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Package name
    #[arg(long)]
    pub package: Option<String>,

    /// Include documentation
    #[arg(long, default_value = "true")]
    pub docs: bool,

    /// Include examples
    #[arg(long, default_value = "true")]
    pub examples: bool,
}

#[derive(Parser)]
pub struct GenStubsCommand {
    /// Path to the OpenAPI specification
    pub spec: Option<PathBuf>,

    /// Target framework
    #[arg(short, long)]
    pub framework: String,

    /// Output directory
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Include tests
    #[arg(long)]
    pub with_tests: bool,

    /// Include validation
    #[arg(long)]
    pub with_validation: bool,
}

#[derive(Parser)]
pub struct GenFixturesCommand {
    /// Path to the OpenAPI specification
    pub spec: Option<PathBuf>,

    /// Output directory
    #[arg(short, long, default_value = "./fixtures")]
    pub output: PathBuf,

    /// Number of samples per schema
    #[arg(long, default_value = "10")]
    pub count: u32,

    /// Specific schemas to generate (all if not specified)
    #[arg(long)]
    pub schema: Vec<String>,

    /// Random seed for deterministic output
    #[arg(long)]
    pub seed: Option<u64>,

    /// Output format
    #[arg(long, value_enum, default_value = "json")]
    pub format: FixtureFormat,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum FixtureFormat {
    Json,
    Yaml,
    Csv,
}

#[derive(Parser)]
pub struct CollectionCommand {
    #[command(subcommand)]
    pub command: CollectionSubcommand,
}

#[derive(Parser)]
pub struct DbCommand {
    #[command(subcommand)]
    pub command: DbSubcommand,
}

#[derive(Subcommand)]
pub enum DbSubcommand {
    /// Show database status and statistics
    Status {
        /// Show detailed information
        #[arg(short, long)]
        verbose: bool,
    },

    /// Display the database schema (tables and columns)
    Schema {
        /// Show specific table only
        #[arg(short, long)]
        table: Option<String>,

        /// Output format (table, json, sql)
        #[arg(short, long, value_enum, default_value = "table")]
        format: DbSchemaFormat,
    },

    /// Run a SQL query against the analytics database
    Query {
        /// SQL query to execute
        sql: String,

        /// Output format (json, table)
        #[arg(short, long, value_enum, default_value = "table")]
        format: DbOutputFormat,
    },

    /// Show API request statistics
    Stats {
        /// Filter by spec file
        #[arg(long)]
        spec: Option<String>,

        /// Filter by operation ID
        #[arg(long)]
        operation: Option<String>,

        /// Time range (today, week, month, all)
        #[arg(long, default_value = "all")]
        range: String,
    },

    /// List recent API runs
    Runs {
        /// Number of runs to show
        #[arg(short, long, default_value = "10")]
        limit: usize,

        /// Output format (json, table)
        #[arg(short, long, value_enum, default_value = "table")]
        format: DbOutputFormat,
    },

    /// Show details of a specific run
    Run {
        /// Run ID to show details for
        run_id: String,

        /// Output format (json, table)
        #[arg(short, long, value_enum, default_value = "table")]
        format: DbOutputFormat,
    },

    /// Show details of a specific request
    Request {
        /// Request ID to show details for
        request_id: String,

        /// Output format (json, table)
        #[arg(short, long, value_enum, default_value = "json")]
        format: DbOutputFormat,
    },

    /// Reset/clear the analytics database
    Reset {
        /// Skip confirmation prompt
        #[arg(short, long)]
        force: bool,
    },

    /// Run health checks on the database
    Check {
        /// Output format (text, json)
        #[arg(short, long, value_enum, default_value = "text")]
        format: DbCheckFormat,

        /// Fix issues automatically if possible
        #[arg(long)]
        fix: bool,
    },

    /// Show migration history and current schema version
    Migrations,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum DbCheckFormat {
    /// Human-readable text output
    Text,
    /// JSON output for automation
    Json,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum DbOutputFormat {
    /// JSON output
    Json,
    /// Table format
    Table,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum DbSchemaFormat {
    /// Table format with columns
    Table,
    /// JSON output
    Json,
    /// SQL CREATE statements
    Sql,
}

/// SQL command for querying API history
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
    # Run inline SQL query
    mrapids sql \"SELECT count(*) FROM responses\"
    mrapids sql \"SELECT * FROM runs\" --json

    # Save a query for reuse
    mrapids sql save slow-requests \"SELECT * FROM responses WHERE duration_ms > 1000\"

    # Run a saved query
    mrapids sql run slow-requests
    mrapids sql run slow-requests --csv

    # List saved queries
    mrapids sql list

AVAILABLE TABLES:
    runs       - API execution sessions (run_id, timestamp, status, duration_ms)
    requests   - Request details (request_id, method, endpoint, url, headers)
    responses  - Response details (status_code, body, duration_ms, success)")]
pub struct SqlCommand {
    #[command(subcommand)]
    pub command: Option<SqlSubcommand>,

    /// SQL query to execute (when not using subcommand)
    pub query: Option<String>,

    /// Output as JSON
    #[arg(long, conflicts_with_all = &["csv", "table"])]
    pub json: bool,

    /// Output as CSV
    #[arg(long, conflicts_with_all = &["json", "table"])]
    pub csv: bool,

    /// Output as table (default)
    #[arg(long, conflicts_with_all = &["json", "csv"])]
    pub table: bool,

    /// Don't print column headers
    #[arg(long)]
    pub no_header: bool,
}

#[derive(Subcommand)]
pub enum SqlSubcommand {
    /// Save a query for later use
    Save {
        /// Name for the saved query (without .sql extension)
        name: String,

        /// SQL query to save
        query: String,

        /// Description of what this query does
        #[arg(short, long)]
        description: Option<String>,
    },

    /// Run a saved query
    Run {
        /// Name of the saved query
        name: String,

        /// Output as JSON
        #[arg(long, conflicts_with_all = &["csv", "table"])]
        json: bool,

        /// Output as CSV
        #[arg(long, conflicts_with_all = &["json", "table"])]
        csv: bool,

        /// Output as table (default)
        #[arg(long, conflicts_with_all = &["json", "csv"])]
        table: bool,

        /// Don't print column headers
        #[arg(long)]
        no_header: bool,
    },

    /// List all saved queries
    List,

    /// Delete a saved query
    Delete {
        /// Name of the query to delete
        name: String,

        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },
}

/// Compare two API runs for differences (reconciliation)
#[derive(Parser)]
#[command(
    about = "Compare two API runs and identify differences",
    long_about = r#"Compare two API runs side-by-side to identify differences.

This is useful for:
- Comparing legacy vs new API implementations
- Detecting regressions between deployments
- Validating API migrations

The comparison identifies:
- Status code differences
- Response body changes
- Missing/new endpoints
- Performance variations

Examples:
  mrapids compare --left abc123 --right def456
  mrapids compare --left abc123 --right def456 --json
  mrapids compare --left abc123 --right def456 --ignore-headers"#
)]
pub struct CompareCommand {
    /// Left (baseline) run ID
    #[arg(long)]
    pub left: String,

    /// Right (comparison) run ID
    #[arg(long)]
    pub right: String,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Ignore header differences
    #[arg(long)]
    pub ignore_headers: bool,

    /// Ignore timing differences
    #[arg(long)]
    pub ignore_timing: bool,

    /// Only show breaking changes (status code changes, missing fields)
    #[arg(long)]
    pub breaking_only: bool,
}

/// Show API run history
#[derive(Parser)]
#[command(
    about = "Show API run history",
    long_about = r#"Display a history of all API runs stored in the local database.

Shows run ID, timestamp, spec file, request counts, duration, and status.

Examples:
  mrapids history
  mrapids history --limit 20
  mrapids history --json"#
)]
pub struct HistoryCommand {
    /// Maximum number of runs to display
    #[arg(short, long, default_value = "10")]
    pub limit: usize,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Show only runs from a specific spec file
    #[arg(long)]
    pub spec: Option<String>,

    /// Show only failed runs
    #[arg(long)]
    pub failed: bool,
}

/// Export format options
#[derive(Clone, Debug, clap::ValueEnum)]
pub enum ExportFormat {
    Parquet,
    Csv,
    Json,
}

/// Export data to various formats
#[derive(Parser)]
#[command(
    about = "Export data to Parquet, CSV, or JSON",
    long_about = r#"Export DuckDB tables to external file formats for analysis in other tools.

Supported formats:
- parquet: Columnar format, ideal for analytics (Spark, DuckDB, Pandas)
- csv: Universal format for spreadsheets and data tools
- json: JSON array format for web applications

Examples:
  mrapids export --table responses --format parquet
  mrapids export --table runs --format csv --output runs.csv
  mrapids export --query "SELECT * FROM responses WHERE status_code >= 400" --format json"#
)]
pub struct ExportCommand {
    /// Table to export (runs, requests, responses, comparisons, comparison_diffs)
    #[arg(long, conflicts_with = "query")]
    pub table: Option<String>,

    /// Custom SQL query to export
    #[arg(long, conflicts_with = "table")]
    pub query: Option<String>,

    /// Output format
    #[arg(long, short, value_enum, default_value = "parquet")]
    pub format: ExportFormat,

    /// Output file path (auto-generated if not specified)
    #[arg(long, short)]
    pub output: Option<PathBuf>,
}

#[derive(Subcommand)]
pub enum CollectionSubcommand {
    /// List available collections
    List {
        /// Directory containing collections
        #[arg(long, default_value = "collections")]
        dir: PathBuf,
    },

    /// Show details of a collection
    Show {
        /// Collection name
        name: String,

        /// Directory containing collections
        #[arg(long, default_value = "collections")]
        dir: PathBuf,
    },

    /// Validate collection syntax and operations
    Validate {
        /// Collection name
        name: String,

        /// Directory containing collections
        #[arg(long, default_value = "collections")]
        dir: PathBuf,

        /// Path to API specification
        #[arg(long)]
        spec: Option<PathBuf>,
    },

    /// Run a collection
    Run {
        /// Collection name
        name: String,

        /// Directory containing collections
        #[arg(long, default_value = "collections")]
        dir: PathBuf,

        /// Output format (json, yaml, pretty)
        #[arg(long, default_value = "pretty")]
        output: String,

        /// Save all responses to directory
        #[arg(long)]
        save_all: Option<PathBuf>,

        /// Save execution summary
        #[arg(long)]
        save_summary: Option<PathBuf>,

        /// Override variables (key=value)
        #[arg(long = "var", value_parser = parse_key_val::<String, String>)]
        variables: Vec<(String, String)>,

        /// Authentication profile to use
        #[arg(long = "profile", value_name = "PROFILE")]
        auth_profile: Option<String>,

        /// Continue execution on errors
        #[arg(long)]
        continue_on_error: bool,

        /// Run specific request(s)
        #[arg(long = "request")]
        requests: Vec<String>,

        /// Skip specific request(s)
        #[arg(long = "skip")]
        skip_requests: Vec<String>,

        /// Use environment variables
        #[arg(long)]
        use_env: bool,

        /// Path to .env file
        #[arg(long)]
        env_file: Option<PathBuf>,

        /// Path to API specification
        #[arg(long)]
        spec: Option<PathBuf>,

        /// Environment name
        #[arg(long)]
        env: Option<String>,
    },

    /// Run collection as tests
    Test {
        /// Collection name
        name: String,

        /// Directory containing collections
        #[arg(long, default_value = "collections")]
        dir: PathBuf,

        /// Path to API specification
        #[arg(long)]
        spec: Option<PathBuf>,

        /// Authentication profile to use
        #[arg(long = "profile", value_name = "PROFILE")]
        auth_profile: Option<String>,

        /// Output format (pretty, json, junit)
        #[arg(long, default_value = "pretty")]
        output: String,

        /// Continue on test failures
        #[arg(long)]
        continue_on_error: bool,
    },
}

// === PLAN COMMAND ===

/// Plan command for sketching execution plans
#[derive(Parser)]
#[command(
    about = "Sketch execution plans from operations or collections",
    long_about = r#"Generate read-only execution plan sketches showing how operations
would compose into a workflow. No side effects, no tokens, no execution.

Examples:
  mrapids plan sketch getPetById updatePet deletePet
  mrapids plan sketch --from my-collection
  mrapids plan sketch --from my-collection --format json"#
)]
pub struct PlanCommand {
    #[command(subcommand)]
    pub command: PlanSubcommand,
}

#[derive(Subcommand)]
pub enum PlanSubcommand {
    /// Generate a sketch of an execution plan (read-only, no side effects)
    Sketch {
        /// Operation IDs to include in the plan
        #[arg(required_unless_present = "from")]
        operations: Vec<String>,

        /// Build plan from a collection YAML file
        #[arg(long, value_name = "COLLECTION", conflicts_with = "operations")]
        from: Option<String>,

        /// Directory containing collections (used with --from)
        #[arg(long, default_value = "collections")]
        dir: PathBuf,

        /// Path to API specification (auto-detected if not provided)
        #[arg(long)]
        spec: Option<PathBuf>,

        /// Output format
        #[arg(long, value_enum, default_value = "text")]
        format: PlanFormat,

        /// Show execution readiness gaps (missing required params, body, auth)
        #[arg(long)]
        show_gaps: bool,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum PlanFormat {
    /// Human-readable text format with colors
    Text,
    /// JSON format for tooling
    Json,
}

// === INDEX COMMAND ===

/// Index command for building and managing operation cards
#[derive(Parser)]
#[command(
    about = "Build and manage operation index for semantic search",
    long_about = r#"Build and manage an index of API operations for semantic search.

The index stores operation cards - structured representations of API operations
that enable fast keyword and semantic search across multiple specs.

Examples:
  mrapids index build                    # Build index from current project spec
  mrapids index add ./other-api.yaml     # Add another spec to the index
  mrapids index list                     # List all indexed specs
  mrapids index status                   # Show index health and stats
  mrapids index rebuild                  # Rebuild entire index"#
)]
pub struct IndexCommand {
    #[command(subcommand)]
    pub command: IndexSubcommand,
}

#[derive(Subcommand)]
pub enum IndexSubcommand {
    /// Build index from current project spec
    Build {
        /// Path to OpenAPI spec (auto-detected if not provided)
        #[arg(long)]
        spec: Option<PathBuf>,

        /// Custom spec ID (defaults to filename)
        #[arg(long)]
        id: Option<String>,

        /// Force rebuild even if spec unchanged
        #[arg(short, long)]
        force: bool,

        /// Embedding provider (none, local, openai)
        #[arg(long, default_value = "none")]
        embed: String,
    },

    /// Add an external spec to the index
    Add {
        /// Path to OpenAPI spec file
        spec: PathBuf,

        /// Custom spec ID (defaults to filename)
        #[arg(long)]
        id: Option<String>,

        /// Force re-index even if already indexed
        #[arg(short, long)]
        force: bool,

        /// Embedding provider (none, local, openai)
        #[arg(long, default_value = "none")]
        embed: String,
    },

    /// List all indexed specs
    List {
        /// Output format
        #[arg(long, value_enum, default_value = "table")]
        format: IndexOutputFormat,
    },

    /// Show index status and health
    Status {
        /// Output format
        #[arg(long, value_enum, default_value = "table")]
        format: IndexOutputFormat,
    },

    /// Rebuild entire index
    Rebuild {
        /// Only rebuild specific spec
        #[arg(long)]
        spec: Option<String>,

        /// Embedding provider (none, local, openai)
        #[arg(long, default_value = "none")]
        embed: String,
    },

    /// Remove a spec from the index
    Remove {
        /// Spec ID to remove
        spec_id: String,

        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum IndexOutputFormat {
    /// Table format
    Table,
    /// JSON format
    Json,
}

// === FIND COMMAND ===

/// Find command for semantic search across operations
#[derive(Parser)]
#[command(
    about = "Find operations using semantic search",
    long_about = r#"Search for API operations using natural language queries.

Uses the operation index to find relevant operations based on:
- Operation IDs and paths
- Summaries and descriptions
- Parameter names and types
- Request/response schemas

Examples:
  mrapids find "create user"             # Find operations related to user creation
  mrapids find "list products" --limit 5 # Limit results
  mrapids find "auth" --spec users-api   # Search within specific spec
  mrapids find "POST" --method POST      # Filter by HTTP method
  mrapids find "update" --risk write     # Filter by risk level"#
)]
pub struct FindCommand {
    /// Search query (natural language or keywords)
    pub query: String,

    /// Maximum number of results
    #[arg(short, long, default_value = "10")]
    pub limit: usize,

    /// Filter by spec ID
    #[arg(long)]
    pub spec: Option<String>,

    /// Filter by HTTP method (GET, POST, PUT, DELETE, etc.)
    #[arg(long)]
    pub method: Option<String>,

    /// Filter by risk level (read, write)
    #[arg(long)]
    pub risk: Option<String>,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: FindOutputFormat,

    /// Use semantic search with embeddings (requires indexed embeddings)
    #[arg(long)]
    pub semantic: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum FindOutputFormat {
    /// Human-readable table
    Table,
    /// JSON format for automation
    Json,
    /// Just operation IDs (one per line)
    Ids,
}

// === MCP COMMAND ===

/// MCP (Model Context Protocol) command for AI agent integration
#[derive(Parser)]
#[command(
    about = "MCP server for AI agent integration",
    long_about = r#"Run an MCP (Model Context Protocol) server that provides AI agents
with secure access to API operations.

SECURITY FEATURES:
  - Zero Trust: Every request validated against policies
  - Credential Isolation: AI never sees raw tokens
  - Audit Logging: Complete logging of all AI actions
  - Policy-based Access Control: Define what operations AI can perform

TOOLS PROVIDED:
  api_find      - Search for API operations using natural language
  api_run       - Execute API operations with credential injection
  api_auth      - Check authentication status

Examples:
  # Start MCP server (stdio transport for Claude Desktop)
  mrapids mcp serve

  # Start with specific policy file
  mrapids mcp serve --policy ./policy.yaml

  # Show available tools
  mrapids mcp tools

  # Test a tool locally
  mrapids mcp test api_find --query "create user""#
)]
pub struct McpCommand {
    #[command(subcommand)]
    pub command: McpSubcommand,
}

#[derive(Subcommand)]
pub enum McpSubcommand {
    /// Start the MCP server (stdio transport)
    Serve {
        /// Policy file for access control
        #[arg(long)]
        policy: Option<std::path::PathBuf>,

        /// Path to OpenAPI spec (auto-detected if not provided)
        #[arg(long)]
        spec: Option<std::path::PathBuf>,

        /// Allow connections to localhost/loopback (for local development)
        #[arg(long)]
        allow_localhost: bool,

        /// Enable debug logging to stderr
        #[arg(long)]
        debug: bool,

        /// Enable decision logging for debugging agent behavior
        /// Saves to ~/.mrapids/decisions.jsonl (or custom path)
        #[arg(long)]
        log_decisions: Option<Option<std::path::PathBuf>>,
    },

    /// Start HTTP REST server for trusted callers (Agent API)
    Http {
        /// Port to bind to
        #[arg(long, default_value = "8420")]
        port: u16,

        /// Bind address
        #[arg(long, default_value = "127.0.0.1")]
        bind: String,

        /// API key for authenticating callers (set MRAPIDS_HTTP_API_KEY env var)
        #[arg(long)]
        api_key: Option<String>,

        /// Policy file for access control
        #[arg(long)]
        policy: Option<std::path::PathBuf>,

        /// Path to OpenAPI spec
        #[arg(long)]
        spec: Option<std::path::PathBuf>,

        /// Base URL of the target API (e.g., http://localhost:8000)
        #[arg(long)]
        base_url: Option<String>,

        /// Allow connections to localhost/loopback targets
        #[arg(long)]
        allow_localhost: bool,

        /// Enable debug logging
        #[arg(long)]
        debug: bool,
    },

    /// List available MCP tools
    Tools,

    /// Test a tool locally without starting server
    Test {
        /// Tool name to test (api_find, api_run, api_auth)
        tool: String,

        /// Query for api_find
        #[arg(long)]
        query: Option<String>,

        /// Operation ID for api_run
        #[arg(long)]
        operation: Option<String>,

        /// Parameters as JSON for api_run
        #[arg(long)]
        params: Option<String>,
    },

    /// Show server status
    Status,
}

/// Parse key=value pairs
fn parse_key_val<T, U>(
    s: &str,
) -> Result<(T, U), Box<dyn std::error::Error + Send + Sync + 'static>>
where
    T: std::str::FromStr,
    T::Err: std::error::Error + Send + Sync + 'static,
    U: std::str::FromStr,
    U::Err: std::error::Error + Send + Sync + 'static,
{
    let pos = s
        .find('=')
        .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
    Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}

/// Get the grouped help display with section headers
fn get_grouped_help() -> &'static str {
    r#"mrapids - Your OpenAPI, but executable

Usage: mrapids [OPTIONS] <COMMAND>

QUICK START (your first 5 minutes):
  mrapids init my-api --from-url https://api.example.com/openapi.json
  mrapids explore "user"                     # Find operations
  mrapids run <operation> -Q                 # See parameters + copy-ready command
  mrapids run <operation> --param id=123     # Execute
  mrapids history                            # See past runs
  mrapids compare --left <run1> --right <run2>   # Diff two runs

AGENT/AUTOMATION MODE:
  --json        Structured JSON output (run_id, metadata, errors)
  --machine     No colors, no decorations, parseable output
  Exit codes:   0=success  2=args  3=auth  4=network  5=rate-limit  7=validation

COMMANDS

Getting Started:
  init          Create project from OpenAPI/GraphQL spec
  explore       Search operations by keyword (aliases: search, discover)
  show          Display operation details, parameters, examples
  validate      Check spec correctness + linting
  doctor        Diagnose issues with auto-fix (--fix)

Execution:
  run           Execute API operations
                  -Q            Show parameters + copy-ready command
                  --as-curl     Output as curl command
                  --dry-run     Preview without sending
                  --json        Structured output for agents
  test          Run automated tests against your API
  list          List operations, requests, or resources

Authentication:
  auth detect   Auto-detect auth requirements from spec
  auth connect  Configure credentials (API key, Bearer, OAuth)
  auth login    OAuth flow (GitHub, Google, custom)
  auth validate Test configured credentials
  auth list     Show all auth profiles

Analytics (DuckDB-powered):
  history       Show recent API runs
  sql           Query history: mrapids sql "SELECT * FROM responses"
  compare       Diff two runs (regression/migration testing)
  export        Export to Parquet, CSV, JSON
  db status     Database stats and health

Workflows:
  collection run   Execute request sequences with dependencies
  collection test  Run collections as test suites
  setup-tests      Auto-generate test harness

Code Generation:
  gen snippets     Generate request/response examples
  gen sdk          [BETA] Generate SDK (TypeScript, Python, Go, Rust)
  gen stubs        [BETA] Generate server stubs
  gen fixtures     Generate test data from schemas
  flatten          Resolve all $ref references

Configuration:
  env list/show/create   Manage environments (dev, staging, prod)

Utilities:
  diff          Compare specs for breaking changes
  cleanup       Remove test artifacts
  help          Show help for any command

OPTIONS
      --env <ENV>               Environment (dev, staging, prod)
      --output-format <FORMAT>  Output format (json, yaml, table, pretty)
  -q, --quiet                   Suppress output except errors
  -v, --verbose                 Verbose output
      --trace                   Trace HTTP requests/responses
      --no-color                Disable colors
  -h, --help                    Print help
  -V, --version                 Print version

COPY-READY EXAMPLES:
  # 1. Initialize from remote spec
  mrapids init my-api --from-url https://petstore.swagger.io/v2/swagger.json

  # 2. Find operations
  mrapids explore "pet"

  # 3. See what parameters an operation needs
  mrapids run getPetById -Q

  # 4. Execute with parameters (JSON output for scripts)
  mrapids run getPetById --param petId=1 --json

  # 5. Query your API history
  mrapids sql "SELECT operation_id, status_code, duration_ms FROM responses LIMIT 10"

  # 6. Compare two runs (migration/regression testing)
  mrapids compare --left abc123 --right def456

More help:
  mrapids <command> --help
  mrapids auth --help
  mrapids db --help

https://microrapid.io"#
}

/// Get the help footer with examples and additional information
fn get_help_footer() -> &'static str {
    r#"
More help:  mrapids <command> --help
Docs:       https://microrapid.io"#
}