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
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
// Simplified run command implementation
// Supports: direct operations, request configs, templates, and complex files

use crate::cli::RunCommand;
use crate::core::analytics_engine::AnalyticsEngine;
use crate::core::api::ApiError;
use crate::core::config::{AuthScheme, ConfigLoader};
use crate::core::examples::generate_smart_example;
use crate::core::output::{
    error_response, exit_codes, is_json_mode, RequestDetails, ResponseEnvelope, RunResponse,
};
use crate::core::query_intelligence::{
    generate_parameter_example, save_query_to_history, show_query_help, QueryBuilder,
};
use crate::core::simple_query_builder;
use anyhow::Result;
use colored::*;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Execute the simplified run command
pub fn execute(cmd: RunCommand) -> Result<()> {
    // Check for query help
    if cmd.help_query {
        show_query_help();
        return Ok(());
    }

    // Check for list queries (doesn't require operation)
    if cmd.list_queries {
        return crate::core::saved_queries::display_saved_queries();
    }

    // Check for load query (doesn't require operation)
    if let Some(query_name) = &cmd.load_query {
        return load_saved_query(query_name);
    }

    // From this point on, operation is required
    let operation = cmd.operation.as_ref().ok_or_else(|| {
        ApiError::ValidationError(
            "Operation is required. Use --list-queries or --load-query for saved queries."
                .to_string(),
        )
    })?;

    // Check for query builder mode
    if cmd.build_query {
        // If user explicitly provided --spec, fail if it doesn't exist
        if cmd.spec.is_some() {
            let spec_path = get_spec_path(&cmd)?; // Will error if file doesn't exist
            let spec_content = fs::read_to_string(&spec_path)?;
            let spec = crate::core::parser::parse_spec(&spec_content)?;

            match simple_query_builder::run_query_builder(&spec, operation) {
                Ok(_) => return Ok(()),
                Err(e) => {
                    return Err(ApiError::OperationNotFound(format!(
                        "Operation '{}' not found in spec: {}\n\nUse 'mrapids list operations --spec {}' to see available operations.",
                        operation,
                        e,
                        spec_path.display()
                    )).into());
                }
            }
        }

        // Try auto-detected spec
        if let Ok(spec_path) = get_spec_path(&cmd) {
            if let Ok(spec_content) = fs::read_to_string(&spec_path) {
                if let Ok(spec) = crate::core::parser::parse_spec(&spec_content) {
                    // Try to use the simple spec-aware builder
                    match simple_query_builder::run_query_builder(&spec, operation) {
                        Ok(_) => return Ok(()),
                        Err(_) => {
                            // Fall back to basic builder if operation not found
                            println!(
                                "⚠️  Operation '{}' not found in spec, using basic query builder",
                                operation
                            );
                        }
                    }
                }
            }
        }

        // Fall back to basic query builder
        let mut builder = QueryBuilder::new(operation.clone());
        builder.interactive_build()?;
        return Ok(());
    }

    // Check for replay last
    if cmd.replay_last {
        return replay_last_query(&cmd);
    }

    // Check for query file
    if let Some(query_file) = &cmd.query_file {
        return load_query_from_file(&cmd, query_file);
    }

    // Check if interactive mode is requested
    if cmd.interactive {
        return generate_template_interactive(&cmd);
    }

    // Check for save query (save only, don't execute)
    if let Some(query_name) = &cmd.save_query {
        return save_current_query(&cmd, query_name);
    }

    // Determine what type of operation this is
    let operation_path = PathBuf::from(operation);

    // Check if it's a file path (request config, template, or spec)
    if operation_path.exists() {
        execute_from_file(&operation_path, &cmd)
    } else if cmd.template.is_some() {
        // Using a template
        execute_from_template(&cmd)
    } else {
        // Direct operation name (e.g., GetCharges, CreateCustomer)
        execute_direct_operation(&cmd)
    }
}

/// Execute a direct operation by name
fn execute_direct_operation(cmd: &RunCommand) -> Result<()> {
    let op_name = cmd
        .operation
        .as_ref()
        .ok_or_else(|| ApiError::ValidationError("Operation is required".to_string()))?;

    // Skip decorative output in JSON mode (check both per-command and global flag)
    let quiet = cmd.json_output || is_json_mode();
    if !quiet {
        println!("⚡ Executing operation: {}", op_name.bright_cyan());
    }

    // Find the API spec - use provided path or auto-detect
    let spec_path = get_spec_path(cmd)?;
    if !quiet {
        println!(
            "📋 Using spec: {}",
            spec_path.display().to_string().dimmed()
        );
    }

    // Load and parse the spec
    let spec_content = fs::read_to_string(&spec_path)?;
    let spec = crate::core::parser::parse_spec(&spec_content)?;

    // Use partial matching to find the operation
    let operation = crate::core::show::find_operation_with_spec(&spec, op_name)?;

    // Build the request
    let mut request = build_request_from_operation(operation, cmd, &spec.base_url)?;

    // Apply environment settings
    apply_environment(&mut request, cmd.env.as_deref(), Some(&spec_path))?;

    // Env var fallback: if base_url is still empty/localhost after config,
    // check API_BASE_URL / MRAPIDS_BASE_URL directly.
    // This covers the case where ConfigLoader fails (no config/ directory).
    if request.base_url.is_empty() || request.base_url == "http://localhost" {
        if let Ok(url) =
            std::env::var("API_BASE_URL").or_else(|_| std::env::var("MRAPIDS_BASE_URL"))
        {
            if !url.is_empty() {
                request.base_url = url;
            }
        }
    }

    // Apply OpenAPI spec Content-Type with higher priority than config
    // The spec knows what the API expects, so it should override generic config
    if request.body.is_some() {
        if let Some(spec_ct) = &request.spec_content_type {
            // Spec Content-Type overrides config (but not command-line)
            request
                .headers
                .insert("Content-Type".to_string(), spec_ct.clone());
            if cmd.verbose {
                println!("  Using Content-Type from spec: {}", spec_ct);
            }
        } else if !request.headers.contains_key("Content-Type") {
            // Fallback: default to application/json when body exists but no Content-Type set
            // This prevents 415 Unsupported Media Type errors
            request
                .headers
                .insert("Content-Type".to_string(), "application/json".to_string());
            if cmd.verbose {
                println!("  Using default Content-Type: application/json");
            }
        }
    }

    // Apply command-line overrides LAST (highest priority)
    apply_command_line_overrides(&mut request, cmd)?;

    // Execute the request
    execute_request(&mut request, cmd, op_name)
}

/// Execute from a file (request config, spec, etc.)
fn execute_from_file(path: &Path, cmd: &RunCommand) -> Result<()> {
    let quiet = cmd.json_output || is_json_mode();

    // Check if it's a request config
    if crate::core::request_runner::is_request_config(path) {
        if !quiet {
            println!(
                "📄 Loading request config from: {}",
                path.display().to_string().cyan()
            );
        }
        let mut config = crate::core::request_runner::load_request_config(path)?;

        // Override with command line options
        if let Some(url) = &cmd.url {
            config.base_url = Some(url.clone());
        }

        // Handle data override
        let data = if let Some(file) = &cmd.file {
            Some(format!("@{}", file.display()))
        } else {
            cmd.data.clone()
        };

        return crate::core::request_runner::execute_request_config_with_options(
            config,
            cmd.url.clone(),
            data,
            &cmd.output,
            cmd.allow_localhost,
        );
    }

    // Otherwise treat as API spec (backward compatibility)
    if !quiet {
        println!(
            "📄 Loading spec from: {}",
            path.display().to_string().cyan()
        );
    }

    // This is the old behavior - we can keep it for backward compatibility
    // but encourage users to use the new direct operation approach
    Err(ApiError::ValidationError(
        "Direct spec execution is deprecated. Use:\n\
         mrapids run <operation-name> [options]\n\
         Example: mrapids run get-user --id 123"
            .to_string(),
    )
    .into())
}

/// Execute from a template
fn execute_from_template(cmd: &RunCommand) -> Result<()> {
    let template_name = cmd.template.as_ref().unwrap();
    if !cmd.json_output && !is_json_mode() {
        println!("📋 Loading template: {}", template_name.bright_cyan());
    }

    // Find template file
    let template_path = find_template(template_name)?;
    let template_content = fs::read_to_string(&template_path)?;

    // Parse template variables
    let mut vars = HashMap::new();
    for var in &cmd.template_vars {
        if let Some((key, value)) = var.split_once('=') {
            vars.insert(key.to_string(), value.to_string());
        }
    }

    // Apply common parameters as variables too
    if let Some(id) = &cmd.id {
        vars.insert("ID".to_string(), id.clone());
    }
    if let Some(name) = &cmd.name {
        vars.insert("NAME".to_string(), name.clone());
    }

    // Substitute variables in template
    let processed = substitute_variables(&template_content, &vars)?;

    // Parse and execute the processed template
    let config: crate::core::request_runner::RequestConfig = serde_yaml::from_str(&processed)?;

    crate::core::request_runner::execute_request_config_with_options(
        config,
        cmd.url.clone(),
        cmd.data.clone(),
        &cmd.output,
        cmd.allow_localhost,
    )
}

/// Build a request from an operation and command options
fn build_request_from_operation(
    operation: &crate::core::parser::UnifiedOperation,
    cmd: &RunCommand,
    base_url: &str,
) -> Result<Request> {
    if cmd.verbose {
        println!(
            "\n  Building request for operation: {}",
            operation.operation_id
        );
        println!("  Operation path: {}", operation.path);
        println!("  Command params: {:?}", cmd.params);
    }

    let mut request = Request {
        method: operation.method.clone(),
        path: operation.path.clone(),
        base_url: base_url.to_string(),
        headers: HashMap::new(),
        query_params: HashMap::new(),
        path_params: HashMap::new(),
        body: None,
        spec_content_type: None,
    };

    // Add common parameters
    if let Some(id) = &cmd.id {
        // Smart detection: map to appropriate path parameter
        // Look for any parameter containing "id" or "Id"
        if operation.path.contains("{id}") {
            request.path_params.insert("id".to_string(), json!(id));
        } else if operation.path.contains("{petId}") {
            request.path_params.insert("petId".to_string(), json!(id));
        } else if operation.path.contains("{userId}") {
            request.path_params.insert("userId".to_string(), json!(id));
        } else if operation.path.contains("{productId}") {
            request
                .path_params
                .insert("productId".to_string(), json!(id));
        } else if operation.path.contains("{orderId}") {
            request.path_params.insert("orderId".to_string(), json!(id));
        } else if operation.path.contains("{customerId}") {
            request
                .path_params
                .insert("customerId".to_string(), json!(id));
        } else {
            // Check for any path param ending with "id" or "Id"
            let id_pattern = regex::Regex::new(r"\{(\w*[iI]d)\}").unwrap();
            if let Some(captures) = id_pattern.captures(&operation.path) {
                if let Some(param_name) = captures.get(1) {
                    request
                        .path_params
                        .insert(param_name.as_str().to_string(), json!(id));
                }
            } else {
                // Fallback to query parameter
                request.query_params.insert("id".to_string(), id.clone());
            }
        }
    }

    // Add other common parameters
    if let Some(name) = &cmd.name {
        request
            .query_params
            .insert("name".to_string(), name.clone());
    }
    if let Some(status) = &cmd.status {
        request
            .query_params
            .insert("status".to_string(), status.clone());
    }
    if let Some(limit) = &cmd.limit {
        request
            .query_params
            .insert("limit".to_string(), limit.to_string());
    }
    if let Some(offset) = &cmd.offset {
        request
            .query_params
            .insert("offset".to_string(), offset.to_string());
    }
    if let Some(sort) = &cmd.sort {
        request
            .query_params
            .insert("sort".to_string(), sort.clone());
    }

    // Add generic parameters - smart detection of path vs query params
    if cmd.verbose {
        println!("  Processing {} generic parameters", cmd.params.len());
    }
    for param in &cmd.params {
        if let Some((key, value)) = param.split_once('=') {
            // Check if this parameter is in the path
            let path_param_pattern = format!("{{{}}}", key);
            if cmd.verbose {
                println!(
                    "  Checking if '{}' is in path '{}' (pattern: '{}')",
                    key, operation.path, path_param_pattern
                );
            }
            if operation.path.contains(&path_param_pattern) {
                // It's a path parameter
                request.path_params.insert(key.to_string(), json!(value));
                if cmd.verbose {
                    println!("  Adding path parameter: {} = {}", key, value);
                }
            } else {
                // Check if it's defined as a path parameter in the operation
                let is_path_param = operation.parameters.iter().any(|p| {
                    p.name == key && p.location == crate::core::parser::ParameterLocation::Path
                });

                if is_path_param {
                    request.path_params.insert(key.to_string(), json!(value));
                    if cmd.verbose {
                        println!("  Adding path parameter (from spec): {} = {}", key, value);
                    }
                } else {
                    // Default to query parameter - smart decode if URL-encoded
                    let decoded_value = smart_decode_param(value);
                    request
                        .query_params
                        .insert(key.to_string(), decoded_value.clone());
                    if cmd.verbose {
                        println!("  Adding query parameter: {} = {}", key, decoded_value);
                        if decoded_value != value {
                            println!("    (decoded from: {})", value);
                        }
                    }
                }
            }
        }
    }

    // Add query parameters
    for param in &cmd.query_params {
        if let Some((key, value)) = param.split_once('=') {
            let decoded_value = smart_decode_param(value);
            request.query_params.insert(key.to_string(), decoded_value);
        }
    }

    // Add headers
    request
        .headers
        .insert("Accept".to_string(), "application/json".to_string());
    request
        .headers
        .insert("User-Agent".to_string(), "MicroRapid/0.1.0".to_string());

    // Note: Headers and auth are now applied in apply_command_line_overrides
    // to ensure they have highest priority

    // Handle body data
    if needs_body(&operation.method) {
        request.body = if let Some(file) = &cmd.file {
            // Load from file
            let content = fs::read_to_string(file)?;
            Some(content)
        } else if let Some(data) = &cmd.data {
            // Use provided data
            if data.starts_with('@') {
                // Load from file
                let file_path = &data[1..];
                let content = fs::read_to_string(file_path)?;
                Some(content)
            } else {
                Some(data.clone())
            }
        } else if cmd.stdin {
            // Read from stdin
            use std::io::Read;
            let mut buffer = String::new();
            std::io::stdin().read_to_string(&mut buffer)?;
            Some(buffer)
        } else if cmd.required_only {
            // Generate minimal payload with only required fields
            generate_required_only_body(operation)?
        } else {
            // Try to load default example
            load_default_example(&operation.operation_id).ok()
        };

        // Store Content-Type from OpenAPI spec if available (don't apply yet)
        if let Some(request_body) = &operation.request_body {
            // Get the first (or preferred) content type from the spec
            // Common preference order: form-encoded > json > others
            let content_type = if request_body
                .content
                .contains_key("application/x-www-form-urlencoded")
            {
                Some("application/x-www-form-urlencoded")
            } else if request_body.content.contains_key("application/json") {
                Some("application/json")
            } else if request_body.content.contains_key("multipart/form-data") {
                Some("multipart/form-data")
            } else {
                // Use the first available content type
                request_body.content.keys().next().map(|s| s.as_str())
            };

            if let Some(ct) = content_type {
                // Store for later use (after config, before CLI overrides)
                request.spec_content_type = Some(ct.to_string());
                if cmd.verbose {
                    println!("  Found Content-Type in spec: {}", ct);
                }
            }
        }
    }

    Ok(request)
}

/// Internal request structure
struct Request {
    method: String,
    path: String,
    base_url: String,
    headers: HashMap<String, String>,
    query_params: HashMap<String, String>,
    path_params: HashMap<String, Value>,
    body: Option<String>,
    spec_content_type: Option<String>, // Store Content-Type from OpenAPI spec
}

/// Execute the built request
fn execute_request(request: &mut Request, cmd: &RunCommand, operation_id: &str) -> Result<()> {
    // Generate run and request IDs for tracking
    let run_id = AnalyticsEngine::generate_run_id();
    let request_id = AnalyticsEngine::generate_request_id();
    let run_start = std::time::Instant::now();
    let json_mode = cmd.json_output || is_json_mode();

    // Initialize DuckDB and create run (ignore errors - logging is optional)
    let db = AnalyticsEngine::open().ok();
    if let Some(ref engine) = db {
        let spec_path = get_spec_path(cmd).ok().map(|p| p.display().to_string());
        let env_json = cmd.env.as_ref().map(|e| json!({"environment": e}));
        let _ = engine.create_run(&run_id, spec_path.as_deref(), env_json.as_ref());
    }

    // Show run ID (skip in JSON mode)
    if !json_mode {
        println!("🔖 Run ID: {}", run_id.bright_magenta());
    }

    // Check if we have a valid base URL
    if request.base_url.is_empty() || request.base_url == "http://localhost" {
        return create_no_url_error(cmd, request);
    }

    // Set default Content-Type if we have a body but no Content-Type header
    // This is the lowest priority - only used if not set by:
    // 1. Command-line --header (highest priority)
    // 2. Config file headers
    // 3. OpenAPI spec requestBody content type
    if request.body.is_some() && !request.headers.contains_key("Content-Type") {
        request
            .headers
            .insert("Content-Type".to_string(), "application/json".to_string());
        if cmd.verbose {
            println!("  No Content-Type specified, defaulting to application/json");
        }
    }

    // Validate URL for security and enforce HTTPS
    use crate::utils::request_warnings::RequestAnalyzer;
    use crate::utils::security::enforce_https_with_options;
    let full_url = format!("{}{}", request.base_url, request.path);
    enforce_https_with_options(&full_url, cmd.allow_insecure, cmd.allow_localhost)?;

    // Analyze request for security warnings
    let mut analyzer = RequestAnalyzer::new(cmd.no_warnings);

    // Analyze headers
    let headers_vec: Vec<(String, String)> = request
        .headers
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    analyzer.analyze_headers(&headers_vec);

    // Analyze query parameters
    let query_params_vec: Vec<(String, String)> = request
        .query_params
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    analyzer.analyze_url_params(&query_params_vec);

    // Analyze path parameters
    let path_params_vec: Vec<(String, String)> = request
        .path_params
        .iter()
        .filter_map(|(k, v)| {
            if let Value::String(s) = v {
                Some((k.clone(), s.clone()))
            } else {
                Some((k.clone(), v.to_string()))
            }
        })
        .collect();
    analyzer.analyze_url_params(&path_params_vec);

    // Analyze body if present
    if let Some(body) = &request.body {
        analyzer.analyze_json_body(body);
    }

    // Block requests with HIGH severity security warnings (unless --no-warnings)
    if !cmd.no_warnings && analyzer.has_high_severity_warnings() {
        let high_warnings = analyzer.get_high_severity_warnings();
        let warning_details: Vec<String> = high_warnings
            .iter()
            .map(|w| format!("{}: {}", w.location, w.message))
            .collect();

        if json_mode {
            // Return structured error for API/MCP consumers
            let error_response = serde_json::json!({
                "success": false,
                "error": "Security check failed: potential injection detected",
                "security_warnings": warning_details,
                "hint": "Use --no-warnings to bypass (not recommended)"
            });
            println!("{}", serde_json::to_string_pretty(&error_response)?);
            return Ok(());
        } else {
            // Return error for CLI users
            return Err(ApiError::ValidationError(format!(
                "Security check failed: potential injection detected\n  {}\n\nUse --no-warnings to bypass (not recommended)",
                warning_details.join("\n  ")
            )).into());
        }
    }

    // Display warnings (skip in JSON mode)
    if !json_mode {
        analyzer.display_warnings();

        // Show warning if localhost access is enabled
        if cmd.allow_localhost {
            use colored::*;
            println!(
                "\n{} {}",
                "⚠️".yellow(),
                "LOCALHOST ACCESS ENABLED".yellow().bold()
            );
            println!(
                "   {} Allowing connections to localhost and private IPs",
                "".dimmed()
            );
            println!(
                "   {} This should only be used for local development",
                "".dimmed()
            );
            println!(
                "   {} Do not use in production or CI/CD pipelines\n",
                "".dimmed()
            );
        }
    }

    // Show verbose info if requested (skip in JSON mode)
    if cmd.verbose && !json_mode {
        println!("\n{} Request Details:", "📋".bright_blue());
        println!("  Method: {}", request.method.bright_green());
        println!("  Path: {}", request.path.bright_cyan());
        println!("  Base URL: {}", request.base_url.dimmed());
        if !request.headers.is_empty() {
            println!("  Headers:");
            // Use the same redaction policy as DB storage (single policy for all surfaces)
            let headers_json = serde_json::json!(&request.headers);
            let redacted = crate::utils::redaction::sanitize_headers_for_storage(&headers_json);
            if let Some(map) = redacted.as_object() {
                for (key, val) in map {
                    let display_value = val.as_str().unwrap_or_default();
                    let styled = if display_value == "[REDACTED]" {
                        display_value.bright_black()
                    } else {
                        display_value.normal()
                    };
                    println!("    {}: {}", key.yellow(), styled);
                }
            }
        }
        if !request.query_params.is_empty() {
            println!("  Query Parameters:");
            for (key, value) in &request.query_params {
                println!("    {}: {}", key.yellow(), value);
            }
        }
        if let Some(body) = &request.body {
            println!("  Body: {}", body.dimmed());
        }
        println!(); // Add spacing
    }

    // Show as curl if requested
    if cmd.as_curl {
        print_as_curl(request)?;
        if cmd.dry_run {
            return Ok(());
        }
    }

    // Dry run - don't actually send
    if cmd.dry_run {
        println!("\n{} Dry run complete (request not sent)", "".green());
        return Ok(());
    }

    // Validate required path parameters are provided before making the HTTP call
    let path_placeholders: Vec<String> = request
        .path
        .split('/')
        .filter(|s| s.starts_with('{') && s.ends_with('}'))
        .map(|s| s[1..s.len() - 1].to_string())
        .collect();

    let missing_path_params: Vec<&String> = path_placeholders
        .iter()
        .filter(|p| !request.path_params.contains_key(p.as_str()))
        .collect();

    if !missing_path_params.is_empty() {
        let missing_names: Vec<&str> = missing_path_params.iter().map(|s| s.as_str()).collect();
        if json_mode {
            let error_json = serde_json::json!({
                "success": false,
                "command": "run",
                "error": "Missing required path parameter(s)",
                "missing_params": missing_names,
                "message": format!("Required path parameter(s) not provided: {}. Use --param {}=<value>",
                    missing_names.join(", "),
                    missing_names[0]),
            });
            println!("{}", serde_json::to_string_pretty(&error_json)?);
            return Ok(());
        } else {
            return Err(ApiError::ValidationError(format!(
                "Missing required path parameter(s): {}.\nProvide with: --param {}=<value>",
                missing_names.join(", "),
                missing_names[0],
            ))
            .into());
        }
    }

    // Build URL with path params substituted
    let mut url_path = request.path.clone();
    for (param_name, param_value) in &request.path_params {
        let placeholder = format!("{{{}}}", param_name);
        let value_str = match param_value {
            Value::String(s) => s.clone(),
            Value::Number(n) => n.to_string(),
            _ => param_value.to_string(),
        };
        url_path = url_path.replace(&placeholder, &value_str);
    }

    let full_url = format!("{}{}", request.base_url.trim_end_matches('/'), url_path);

    if !json_mode {
        println!("🌐 Request URL: {}", full_url.bright_blue());
        println!("🚀 Sending request...");
    }

    // Log request to DuckDB before sending
    if let Some(ref engine) = db {
        let headers_json = json!(request.headers);
        let query_json = json!(request.query_params);
        let path_json = json!(request.path_params);
        let _ = engine.log_request_v2(
            &run_id,
            &request_id,
            Some(operation_id),
            &request.path,
            &request.method,
            Some(&full_url),
            Some(&headers_json),
            Some(&query_json),
            Some(&path_json),
            request.body.as_deref(),
        );
    }

    // Execute with retries if specified
    let mut attempts = 0;
    let max_attempts = cmd.retry + 1;
    let final_success;

    loop {
        attempts += 1;

        // Create HTTP client and request
        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(cmd.timeout as u64))
            .build()?;

        let mut http_request = match request.method.to_uppercase().as_str() {
            "GET" => client.get(&full_url),
            "POST" => client.post(&full_url),
            "PUT" => client.put(&full_url),
            "DELETE" => client.delete(&full_url),
            "PATCH" => client.patch(&full_url),
            _ => {
                return Err(ApiError::ValidationError(format!(
                    "Unsupported method: {}",
                    request.method
                ))
                .into())
            }
        };

        // Add headers
        for (key, value) in &request.headers {
            http_request = http_request.header(key, value);
        }

        // Add query params
        if !request.query_params.is_empty() {
            http_request = http_request.query(&request.query_params);
        }

        // Add body
        if let Some(body) = &request.body {
            http_request = http_request.body(body.clone());
        }

        // Send request
        let start_time = std::time::Instant::now();
        match http_request.send() {
            Ok(response) => {
                let status = response.status().as_u16();
                let response_time = start_time.elapsed();
                final_success = (200..300).contains(&status);

                // Get response headers and body for logging
                let response_headers = response.headers().clone();
                let status_text = response.status().canonical_reason().map(|s| s.to_string());

                // Read response body
                let body_text = response.text()?;
                let body_size = body_text.len();

                // Log response to DuckDB
                if let Some(ref engine) = db {
                    let headers_map: HashMap<String, String> = response_headers
                        .iter()
                        .filter_map(|(k, v)| {
                            v.to_str()
                                .ok()
                                .map(|v| (k.as_str().to_string(), v.to_string()))
                        })
                        .collect();
                    let headers_json = json!(headers_map);
                    let _ = engine.log_response(
                        &request_id,
                        status as i32,
                        status_text.as_deref(),
                        Some(&headers_json),
                        Some(&body_text),
                        response_time.as_secs_f64() * 1000.0,
                        final_success,
                        None,
                    );
                }

                // Handle output based on mode (JSON vs human-readable)
                if json_mode {
                    // Build JSON response envelope
                    let response_body_json: Option<serde_json::Value> =
                        serde_json::from_str(&body_text).ok();

                    // Apply redaction if enabled
                    let response_body_json = if cmd.redact {
                        response_body_json.map(|v| {
                            use crate::utils::redaction::redact_response;
                            redact_response(&v, true)
                        })
                    } else {
                        response_body_json
                    };

                    let response_headers_map: HashMap<String, String> = response_headers
                        .iter()
                        .filter_map(|(k, v)| {
                            v.to_str()
                                .ok()
                                .map(|v| (k.as_str().to_string(), v.to_string()))
                        })
                        .collect();

                    let run_response = RunResponse {
                        operation: operation_id.to_string(),
                        method: request.method.clone(),
                        url: full_url.clone(),
                        status_code: status,
                        status_text: status_text.clone(),
                        headers: Some(json!(response_headers_map)),
                        body: response_body_json.clone(),
                        body_raw: if response_body_json.is_none() {
                            Some(body_text.clone())
                        } else {
                            None
                        },
                        body_size_bytes: Some(body_size),
                        request: Some(RequestDetails {
                            headers: Some(json!(request.headers)),
                            query_params: Some(json!(request.query_params)),
                            path_params: Some(json!(request.path_params)),
                            body: request
                                .body
                                .as_ref()
                                .and_then(|b| serde_json::from_str(b).ok()),
                        }),
                    };

                    let duration_ms = response_time.as_secs_f64() * 1000.0;
                    let envelope = ResponseEnvelope::success_with_run(
                        "run",
                        run_response,
                        run_id.clone(),
                        Some(request_id.clone()),
                        duration_ms,
                    );

                    println!("{}", envelope.to_json());
                } else {
                    // Display human-readable response (with optional redaction)
                    let display_body = if cmd.redact {
                        // Try to parse as JSON for proper redaction
                        if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(&body_text)
                        {
                            use crate::utils::redaction::redact_response;
                            let redacted = redact_response(&json_val, true);
                            serde_json::to_string_pretty(&redacted).unwrap_or(body_text.clone())
                        } else {
                            body_text.clone() // Non-JSON, can't redact structure
                        }
                    } else {
                        body_text.clone()
                    };

                    display_response_from_parts(
                        status,
                        &response_headers,
                        &display_body,
                        &cmd.output,
                        cmd.save.as_deref(),
                    )?;
                }

                // Save to collection if requested and successful
                if cmd.save_to_collection && final_success {
                    if let Err(e) = save_to_collection(&request, status, cmd, operation_id) {
                        if !json_mode {
                            eprintln!("⚠️  Failed to save to collection: {}", e);
                        }
                    }
                }

                // Save query history for successful requests
                if final_success {
                    let mut params = HashMap::new();

                    // Collect all parameters for history
                    for (k, v) in &request.query_params {
                        params.insert(k.clone(), v.clone());
                    }

                    // Save using the simplified function
                    if let Err(e) = save_query_to_history(
                        operation_id.to_string(),
                        params,
                        Some(response_time.as_millis() as u64),
                        Some(status),
                        true,
                    ) {
                        if cmd.verbose && !json_mode {
                            eprintln!("⚠️  Failed to save query history: {}", e);
                        }
                    }
                }

                // Show run summary (skip in JSON mode - already included in envelope)
                if !json_mode {
                    println!(
                        "📊 Run {} completed: {} {}",
                        run_id.bright_magenta(),
                        if final_success {
                            "".green()
                        } else {
                            "".red()
                        },
                        format!("{} {}", status, status_text.unwrap_or_default()).dimmed()
                    );
                }

                break;
            }
            Err(e) => {
                if attempts < max_attempts {
                    if !json_mode {
                        println!(
                            "⚠️  Request failed: {}. Retrying ({}/{})...",
                            e, attempts, max_attempts
                        );
                    }
                    std::thread::sleep(std::time::Duration::from_secs(2));
                } else {
                    // Log failed response to DuckDB
                    if let Some(ref engine) = db {
                        let _ = engine.log_response(
                            &request_id,
                            0,
                            None,
                            None,
                            None,
                            0.0,
                            false,
                            Some(&e.to_string()),
                        );
                    }

                    // Complete run as failed
                    let run_duration = run_start.elapsed().as_secs_f64() * 1000.0;
                    if let Some(ref engine) = db {
                        let _ = engine.complete_run(&run_id, 1, 0, 1, run_duration, "failed");
                    }

                    // Output JSON error if in JSON mode
                    if json_mode {
                        let error_envelope = error_response(
                            "run",
                            "NETWORK_ERROR",
                            &format!("Request failed after {} attempts: {}", max_attempts, e),
                            exit_codes::NETWORK_ERROR,
                        );
                        println!("{}", error_envelope.to_json());
                        std::process::exit(exit_codes::NETWORK_ERROR);
                    }

                    return Err(ApiError::NetworkError(format!(
                        "Request failed after {} attempts: {}",
                        max_attempts, e
                    ))
                    .into());
                }
            }
        }
    }

    // Complete the run with final statistics
    let run_duration = run_start.elapsed().as_secs_f64() * 1000.0;
    if let Some(ref engine) = db {
        let status = if final_success { "completed" } else { "failed" };
        let successful = if final_success { 1 } else { 0 };
        let failed = if final_success { 0 } else { 1 };
        let _ = engine.complete_run(&run_id, 1, successful, failed, run_duration, status);
    }

    Ok(())
}

/// Display the response from pre-extracted parts (used when we need to log before displaying)
fn display_response_from_parts(
    status_code: u16,
    headers: &reqwest::header::HeaderMap,
    body: &str,
    format: &str,
    save_path: Option<&Path>,
) -> Result<()> {
    // Show status
    let status_text = reqwest::StatusCode::from_u16(status_code)
        .map(|s| s.canonical_reason().unwrap_or(""))
        .unwrap_or("");

    if (200..300).contains(&status_code) {
        println!(
            "✅ Status: {} {}",
            status_code.to_string().green(),
            status_text
        );
    } else {
        println!(
            "❌ Status: {} {}",
            status_code.to_string().red(),
            status_text
        );
    }

    // Save to file if requested
    if let Some(path) = save_path {
        fs::write(path, body)?;
        println!(
            "💾 Response saved to: {}",
            path.display().to_string().green()
        );
    }

    // Display based on format
    let content_type = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("text/plain");

    if content_type.contains("json") {
        if let Ok(json) = serde_json::from_str::<Value>(body) {
            match format {
                "json" => println!("{}", serde_json::to_string_pretty(&json)?),
                "yaml" => println!("{}", serde_yaml::to_string(&json)?),
                "table" => print_as_table(&json),
                _ => crate::core::request_runner::print_json_pretty(&json, 0),
            }
        } else {
            println!("{}", body);
        }
    } else {
        println!("{}", body);
    }

    Ok(())
}

// Helper functions

/// Get spec path - uses provided --spec or falls back to auto-detection
fn get_spec_path(cmd: &RunCommand) -> Result<PathBuf> {
    // If user provided a spec path, use it
    if let Some(spec_path) = &cmd.spec {
        if spec_path.exists() {
            return Ok(spec_path.canonicalize()?);
        } else {
            return Err(ApiError::ValidationError(format!(
                "Spec file not found: {}\n\nProvide a valid path or omit --spec for auto-detection.",
                spec_path.display()
            )).into());
        }
    }

    // Fall back to auto-detection
    find_api_spec()
}

fn find_api_spec() -> Result<PathBuf> {
    // Look for spec files in common locations
    let spec_locations = [
        "specs/api.yaml",
        "specs/api.json",
        "specs/openapi.yaml",
        "specs/openapi.json",
        "specs/swagger.yaml",
        "specs/swagger.json",
        "api.yaml",
        "api.json",
        "openapi.yaml",
        "openapi.json",
    ];

    for location in &spec_locations {
        let path = PathBuf::from(location);
        if path.exists() {
            // Convert to absolute path
            return Ok(path.canonicalize()?);
        }
    }

    // Look for any spec file in specs directory
    if let Ok(entries) = fs::read_dir("specs") {
        for entry in entries {
            let entry = entry?;
            let path = entry.path();
            if let Some(ext) = path.extension() {
                if ext == "yaml" || ext == "yml" || ext == "json" {
                    // Convert to absolute path
                    return Ok(path.canonicalize()?);
                }
            }
        }
    }

    Err(ApiError::ValidationError(
        "No API specification found. Please run 'mrapids init' or place your spec in specs/api.yaml".to_string()
    ).into())
}

fn find_template(name: &str) -> Result<PathBuf> {
    let template_paths = [
        format!("templates/{}.yaml", name),
        format!("templates/{}.yml", name),
        format!("templates/{}.json", name),
        format!(".mrapids/templates/{}.yaml", name),
        format!("{}.yaml", name),
        format!("{}.yml", name),
    ];

    for path in &template_paths {
        let path = PathBuf::from(path);
        if path.exists() {
            return Ok(path);
        }
    }

    Err(ApiError::ValidationError(format!("Template '{}' not found", name)).into())
}

/// Save a successful request to a collection
fn save_to_collection(
    request: &Request,
    _response_status: u16,
    cmd: &RunCommand,
    operation_id: &str,
) -> Result<()> {
    use crate::collections::models::{Collection, CollectionRequest};
    use chrono::Local;
    use std::fs::OpenOptions;
    use std::io::Write;

    // Determine collection name
    let collection_name = if let Some(name) = &cmd.collection {
        name.clone()
    } else {
        // Default to daily collection
        format!("daily-{}", Local::now().format("%Y-%m-%d"))
    };

    // Create collections directory if it doesn't exist
    let collections_dir = PathBuf::from("collections");
    fs::create_dir_all(&collections_dir)?;

    // Collection file path
    let collection_file = collections_dir.join(format!("{}.yaml", collection_name));

    // Create parent directories if the collection name contains paths
    if let Some(parent) = collection_file.parent() {
        fs::create_dir_all(parent)?;
    }

    // Check if collection exists or create new one
    let mut collection = if collection_file.exists() {
        // Load existing collection
        let content = fs::read_to_string(&collection_file)?;
        match serde_yaml::from_str::<Collection>(&content) {
            Ok(col) => col,
            Err(e) => {
                eprintln!(
                    "⚠️  Warning: Failed to parse existing collection '{}': {}",
                    collection_name, e
                );
                eprintln!("   Creating backup at {}.backup", collection_file.display());

                // Create backup of corrupted file
                let backup_path = collection_file.with_extension("yaml.backup");
                fs::copy(&collection_file, &backup_path)?;

                // Create new collection
                Collection {
                    name: collection_name.clone(),
                    description: Some(format!(
                        "Auto-saved requests from {}",
                        Local::now().format("%Y-%m-%d")
                    )),
                    requests: Vec::new(),
                    variables: HashMap::new(),
                    auth_profile: None,
                }
            }
        }
    } else {
        // Create new collection
        Collection {
            name: collection_name.clone(),
            description: Some(format!(
                "Auto-saved requests from {}",
                Local::now().format("%Y-%m-%d")
            )),
            requests: Vec::new(),
            variables: HashMap::new(),
            auth_profile: None,
        }
    };

    // Determine request name
    let request_name = if let Some(name) = &cmd.save_as_request {
        name.clone()
    } else {
        // Generate name from operation and timestamp
        format!(
            "{}_{}",
            operation_id.replace('/', "_"),
            Local::now().format("%H%M%S")
        )
    };

    // Build collection request
    let mut collection_request = CollectionRequest {
        name: request_name,
        operation: operation_id.to_string(),
        params: None,
        body: None,
        save_as: None,
        expect: None,
        depends_on: None,
        if_condition: None,
        skip: None,
        run_always: false,
        critical: false,
        retry: None,
    };

    // Add parameters if any
    let mut params = HashMap::new();

    // Add path parameters
    for (key, value) in &request.path_params {
        params.insert(key.clone(), value.clone());
    }

    // Add query parameters
    for (key, value) in &request.query_params {
        params.insert(key.clone(), json!(value));
    }

    if !params.is_empty() {
        collection_request.params = Some(params);
    }

    // Add body if present
    if let Some(body) = &request.body {
        collection_request.body = serde_json::from_str(body).ok();
    }

    // Add to collection
    collection.requests.push(collection_request);

    // Save collection
    let yaml = serde_yaml::to_string(&collection)?;
    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&collection_file)?;
    file.write_all(yaml.as_bytes())?;

    println!(
        "💾 Request saved to collection: {}",
        collection_name.bright_cyan()
    );

    Ok(())
}

/// Create a helpful error message when no URL is found
fn create_no_url_error(cmd: &RunCommand, request: &Request) -> Result<()> {
    let mut attempted = vec![];
    let mut msg = String::new();

    msg.push_str(&format!(
        "{}\n\n",
        "Error: No API server URL configured".red().bold()
    ));
    msg.push_str("I looked for a base URL in this order and couldn't find one:\n");

    // Check what was attempted
    attempted.push(("--url flag", cmd.url.clone()));
    attempted.push(("--env flag", cmd.env.clone()));
    attempted.push((
        "config file",
        cmd.env.as_ref().map(|e| format!("config/{}.yaml", e)),
    ));
    attempted.push(("$API_BASE_URL", std::env::var("API_BASE_URL").ok()));
    attempted.push(("$MRAPIDS_BASE_URL", std::env::var("MRAPIDS_BASE_URL").ok()));
    attempted.push((
        "OpenAPI spec servers[]",
        if request.base_url == "http://localhost" {
            Some("localhost only (blocked)".to_string())
        } else if request.base_url.is_empty() {
            Some("empty".to_string())
        } else {
            Some(request.base_url.clone())
        },
    ));

    // Show attempted sources
    for (source, value) in &attempted {
        let status = if value.is_some()
            && !value.as_ref().unwrap().is_empty()
            && !value.as_ref().unwrap().contains("localhost")
        {
            "".green()
        } else {
            "".red()
        };
        let info = value.clone().unwrap_or_else(|| "not provided".to_string());
        msg.push_str(&format!("  {} {}: {}\n", status, source, info.dimmed()));
    }

    msg.push_str(&format!(
        "\n{}\n\n",
        "Quick fixes (try these in order):".yellow().bold()
    ));

    // Platform-specific instructions
    msg.push_str(&format!("{}\n", "1) Provide URL directly:".bold()));
    msg.push_str(&format!(
        "   mrapids run {} --url https://api.example.com\n\n",
        cmd.operation.as_deref().unwrap_or("<operation>")
    ));

    msg.push_str(&format!("{}\n", "2) Set environment variable:".bold()));

    #[cfg(target_os = "windows")]
    {
        msg.push_str("   # Windows CMD:\n");
        msg.push_str("   set API_BASE_URL=https://api.example.com\n\n");
        msg.push_str("   # Windows PowerShell (session):\n");
        msg.push_str("   $env:API_BASE_URL = \"https://api.example.com\"\n\n");
        msg.push_str("   # Windows PowerShell (permanent):\n");
        msg.push_str("   [System.Environment]::SetEnvironmentVariable(\"API_BASE_URL\", \"https://api.example.com\", \"User\")\n\n");
    }

    #[cfg(not(target_os = "windows"))]
    {
        msg.push_str("   # macOS/Linux:\n");
        msg.push_str("   export API_BASE_URL=https://api.example.com\n\n");
        msg.push_str("   # Add to ~/.bashrc or ~/.zshrc to persist:\n");
        msg.push_str("   echo 'export API_BASE_URL=https://api.example.com' >> ~/.bashrc\n\n");
    }

    msg.push_str(&format!("{}\n", "3) Create default config:".bold()));
    let env_name = cmd.env.as_deref().unwrap_or("development");
    msg.push_str(&format!(
        "   echo \"base_url: https://api.example.com\" > config/{}.yaml\n\n",
        if env_name == "development" {
            "default"
        } else {
            env_name
        }
    ));

    msg.push_str(&format!(
        "{}\n",
        "4) Re-initialize to extract from spec:".bold()
    ));
    msg.push_str("   mrapids init --from-url https://api.example.com/openapi.json\n\n");

    msg.push_str(&format!("{}\n", "5) Run diagnostics:".bold()));
    msg.push_str("   mrapids doctor  # Check your setup\n");

    Err(ApiError::ValidationError(msg).into())
}

fn load_default_example(operation_id: &str) -> Result<String> {
    let example_paths = [
        format!("data/examples/{}.json", operation_id),
        format!("data/examples/{}.json", operation_id.replace('_', "-")),
        format!("examples/{}.json", operation_id),
    ];

    for path in &example_paths {
        if let Ok(content) = fs::read_to_string(path) {
            // Strip comments
            let cleaned: String = content
                .lines()
                .filter(|line| !line.trim().starts_with("//"))
                .collect::<Vec<_>>()
                .join("\n");
            return Ok(cleaned);
        }
    }

    Err(ApiError::ValidationError(format!(
        "No example data found for operation '{}'",
        operation_id
    ))
    .into())
}

fn needs_body(method: &str) -> bool {
    matches!(method.to_uppercase().as_str(), "POST" | "PUT" | "PATCH")
}

fn apply_environment(
    request: &mut Request,
    env: Option<&str>,
    _spec_path: Option<&Path>,
) -> Result<()> {
    // Use the new ConfigLoader
    let loader = match ConfigLoader::load(env) {
        Ok(loader) => loader,
        Err(e) => {
            if std::env::var("MRAPIDS_DEBUG").is_ok() {
                eprintln!("Debug: Failed to load config: {}", e);
            }
            // Continue without config
            return Ok(());
        }
    };

    // Debug: Show what's loaded
    if std::env::var("MRAPIDS_DEBUG").is_ok() {
        eprintln!("Debug: Config loaded for env '{}'", loader.environment());
        eprintln!("Debug: Has headers: {}", !loader.headers().is_empty());
        eprintln!("Debug: Has auth: {}", loader.auth().is_some());
    }

    // Apply base URL if available
    // Config base_url should ALWAYS override spec base_url (except when using --url flag)
    if let Some(base_url) = loader.base_url() {
        // Always apply config base_url - it has higher priority than spec
        let old_url = request.base_url.clone();
        request.base_url = base_url.to_string();

        if std::env::var("MRAPIDS_DEBUG").is_ok() && old_url != request.base_url {
            eprintln!(
                "Debug: Overriding base_url from '{}' to '{}'",
                old_url, request.base_url
            );
        }
    }

    // Apply headers from config (these can override defaults but will be overridden by CLI)
    for (key, value) in loader.headers() {
        // Config headers should override defaults (like Accept, User-Agent)
        // But will be overridden by command-line later
        request.headers.insert(key.clone(), value.clone());
    }

    // Apply authentication
    if let Some(auth_config) = loader.auth() {
        // Use preferred scheme if specified
        if let Some(preferred) = &auth_config.preferred {
            if let Some(scheme) = auth_config.schemes.get(preferred) {
                apply_auth_scheme_to_request(request, scheme);
            }
        } else if let Some((_, scheme)) = auth_config.schemes.iter().next() {
            // Use first available scheme
            apply_auth_scheme_to_request(request, scheme);
        }
    }

    // Apply timeout
    request.headers.insert(
        "X-MRapids-Timeout".to_string(),
        loader.timeout_ms().to_string(),
    );

    Ok(())
}

/// Apply command-line overrides (highest priority)
fn apply_command_line_overrides(request: &mut Request, cmd: &RunCommand) -> Result<()> {
    // Override URL if specified
    if let Some(url) = &cmd.url {
        request.base_url = url.clone();
        if cmd.verbose {
            println!("  Overriding base URL with: {}", url);
        }
    }

    // Override auth headers (highest priority)
    if let Some(auth) = &cmd.auth {
        request
            .headers
            .insert("Authorization".to_string(), auth.clone());
        if cmd.verbose {
            println!("  Using command-line auth");
        }
    } else if let Some(api_key) = &cmd.api_key {
        request
            .headers
            .insert("X-API-Key".to_string(), api_key.clone());
        if cmd.verbose {
            println!("  Using command-line API key");
        }
    } else if let Some(profile) = &cmd.auth_profile {
        // Use OAuth profile
        apply_oauth_profile_auth(request, profile)?;
        if cmd.verbose {
            println!("  Using OAuth profile: {}", profile);
        }
    }

    // Override any headers specified on command line
    for header in &cmd.headers {
        if let Some((key, value)) = header.split_once(':') {
            request
                .headers
                .insert(key.trim().to_string(), value.trim().to_string());
        }
    }

    Ok(())
}

fn apply_auth_scheme_to_request(request: &mut Request, scheme: &AuthScheme) {
    match scheme {
        AuthScheme::ApiKey {
            location,
            name,
            value,
        } => match location.as_str() {
            "header" => {
                request.headers.insert(name.clone(), value.clone());
            }
            "query" => {
                request.query_params.insert(name.clone(), value.clone());
            }
            _ => {}
        },
        AuthScheme::Bearer { token, .. } => {
            request
                .headers
                .insert("Authorization".to_string(), format!("Bearer {}", token));
        }
        AuthScheme::Basic { username, password } => {
            use base64::Engine;
            let credentials = base64::engine::general_purpose::STANDARD
                .encode(format!("{}:{}", username, password));
            request.headers.insert(
                "Authorization".to_string(),
                format!("Basic {}", credentials),
            );
        }
        AuthScheme::OAuth2 { .. } => {
            // OAuth2 would need token exchange logic
        }
    }
}

fn apply_oauth_profile_auth(request: &mut Request, profile: &str) -> Result<()> {
    use crate::core::auth;

    // Load tokens for the profile
    let mut tokens = auth::load_tokens(profile)?;

    // Check if token is expired and refresh if needed
    if tokens.is_expired() {
        println!("🔄 Token expired, refreshing...");
        // Use the existing tokio runtime handle instead of creating a new one
        // (creating a new runtime inside an async context causes a panic)
        tokens = tokio::runtime::Handle::current().block_on(auth::refresh_tokens(profile))?;
    }

    // Apply the authorization header
    request
        .headers
        .insert("Authorization".to_string(), tokens.auth_header());

    Ok(())
}

fn substitute_variables(template: &str, vars: &HashMap<String, String>) -> Result<String> {
    let mut result = template.to_string();

    for (key, value) in vars {
        let pattern = format!("${{{}}}", key);
        result = result.replace(&pattern, value);

        // Also handle with default values ${KEY:default}
        let pattern_with_default = format!("${{{}:", key);
        if result.contains(&pattern_with_default) {
            // This is simplified - full implementation would parse defaults properly
            let re = regex::Regex::new(&format!(r"\$\{{{}\:([^}}]+)\}}", regex::escape(key)))?;
            result = re.replace_all(&result, value).to_string();
        }
    }

    Ok(result)
}

/// Find which environment variable contains the given value
fn find_env_var_with_value(target_value: &str) -> Option<String> {
    use std::env;

    // Check common token environment variables first
    let common_vars = [
        "DEV_API_TOKEN",
        "STAGING_API_TOKEN",
        "PROD_API_TOKEN",
        "API_TOKEN",
        "GITHUB_TOKEN",
        "GH_TOKEN",
        "DEV_BASIC_AUTH",
        "STAGING_BASIC_AUTH",
        "PROD_BASIC_AUTH",
        "BASIC_AUTH",
        "DEV_API_KEY",
        "STAGING_API_KEY",
        "PROD_API_KEY",
        "API_KEY",
    ];

    // Check common vars first for performance
    for var_name in &common_vars {
        if let Ok(value) = env::var(var_name) {
            if value == target_value {
                return Some(var_name.to_string());
            }
        }
    }

    // If not found in common vars, search all environment variables
    for (key, value) in env::vars() {
        if value == target_value {
            return Some(key);
        }
    }

    None
}

fn print_as_curl(request: &Request) -> Result<()> {
    use std::env;

    let mut curl_cmd = format!("curl -X {}", request.method);

    // Add headers (check for Authorization header to show as env var)
    for (key, value) in &request.headers {
        if key == "Authorization" {
            // Check if this is a Bearer token that might come from env
            if value.starts_with("Bearer ") {
                let token = value.trim_start_matches("Bearer ");
                // Try to find which environment variable contains this token
                let env_var_name = find_env_var_with_value(token).unwrap_or_else(|| {
                    // Check common patterns
                    if env::var("DEV_API_TOKEN").is_ok() {
                        "DEV_API_TOKEN".to_string()
                    } else if env::var("STAGING_API_TOKEN").is_ok() {
                        "STAGING_API_TOKEN".to_string()
                    } else if env::var("PROD_API_TOKEN").is_ok() {
                        "PROD_API_TOKEN".to_string()
                    } else if env::var("API_TOKEN").is_ok() {
                        "API_TOKEN".to_string()
                    } else {
                        "API_TOKEN".to_string() // fallback
                    }
                });
                curl_cmd.push_str(&format!(" -H '{}: Bearer ${}'", key, env_var_name));
            } else if value.starts_with("Basic ") {
                // For Basic auth, show placeholder
                let basic_value = value.trim_start_matches("Basic ");
                let env_var_name =
                    find_env_var_with_value(basic_value).unwrap_or("BASIC_AUTH".to_string());
                curl_cmd.push_str(&format!(" -H '{}: Basic ${}'", key, env_var_name));
            } else {
                curl_cmd.push_str(&format!(" -H '{}: {}'", key, value));
            }
        } else if key.to_lowercase().contains("api") && key.to_lowercase().contains("key") {
            // API key headers - try to find the env var
            let env_var_name = find_env_var_with_value(value).unwrap_or("API_KEY".to_string());
            curl_cmd.push_str(&format!(" -H '{}: ${}'", key, env_var_name));
        } else {
            curl_cmd.push_str(&format!(" -H '{}: {}'", key, value));
        }
    }

    // Add data
    if let Some(body) = &request.body {
        curl_cmd.push_str(&format!(" -d '{}'", body));
    }

    // Build URL with path params substituted
    let mut url_path = request.path.clone();
    for (param_name, param_value) in &request.path_params {
        let placeholder = format!("{{{}}}", param_name);
        let value_str = match param_value {
            Value::String(s) => s.clone(),
            Value::Number(n) => n.to_string(),
            _ => param_value.to_string(),
        };
        url_path = url_path.replace(&placeholder, &value_str);
    }

    let mut url = format!("{}{}", request.base_url.trim_end_matches('/'), url_path);
    if !request.query_params.is_empty() {
        let query: Vec<String> = request
            .query_params
            .iter()
            .map(|(k, v)| {
                // Check if this is an API key parameter
                if k.to_lowercase().contains("api") && k.to_lowercase().contains("key") {
                    format!("{}=$API_KEY", k)
                } else if k.to_lowercase() == "token" || k.to_lowercase() == "access_token" {
                    format!("{}=$API_TOKEN", k)
                } else {
                    format!("{}={}", k, v)
                }
            })
            .collect();
        url.push_str(&format!("?{}", query.join("&")));
    }

    curl_cmd.push_str(&format!(" '{}'", url));

    println!("\n{} Equivalent curl command:", "🐚".bright_blue());
    println!("{}", curl_cmd.bright_cyan());

    // Check if we used any environment variable placeholders
    if curl_cmd.contains("$API_TOKEN")
        || curl_cmd.contains("$API_KEY")
        || curl_cmd.contains("$BASIC_AUTH")
    {
        println!(
            "\n{} Set environment variables before running:",
            "💡".bright_yellow()
        );
        if curl_cmd.contains("$API_TOKEN") {
            println!("  export API_TOKEN=\"your-token-here\"");
        }
        if curl_cmd.contains("$API_KEY") {
            println!("  export API_KEY=\"your-api-key-here\"");
        }
        if curl_cmd.contains("$BASIC_AUTH") {
            println!("  export BASIC_AUTH=\"$(echo -n 'username:password' | base64)\"");
        }
    }

    Ok(())
}

fn print_as_table(json: &Value) {
    // Simple table output for arrays
    if let Some(array) = json.as_array() {
        if !array.is_empty() {
            // Get headers from first object
            if let Some(first) = array.first().and_then(|v| v.as_object()) {
                let headers: Vec<&str> = first.keys().map(|s| s.as_str()).collect();

                // Print headers
                println!("{}", headers.join("\t").bright_blue());

                // Print rows
                for item in array {
                    if let Some(obj) = item.as_object() {
                        let values: Vec<String> = headers
                            .iter()
                            .map(|h| obj.get(*h).map(|v| format!("{}", v)).unwrap_or_default())
                            .collect();
                        println!("{}", values.join("\t"));
                    }
                }
            }
        }
    } else {
        // For non-arrays, just print as JSON
        println!("{}", serde_json::to_string_pretty(json).unwrap());
    }
}

/// Generate minimal body with only required fields
fn generate_required_only_body(
    operation: &crate::core::parser::UnifiedOperation,
) -> Result<Option<String>> {
    if let Some(request_body) = &operation.request_body {
        if let Some((_, media_type)) = request_body.content.iter().next() {
            let schema = &media_type.schema;

            // Generate minimal object with only required fields
            if let crate::core::parser::SchemaType::Object = schema.schema_type {
                let mut obj = serde_json::Map::new();

                if let Some(properties) = &schema.properties {
                    if let Some(required) = &schema.required {
                        // Only include required fields
                        for field_name in required {
                            if let Some(field_schema) = properties.get(field_name) {
                                let value = generate_smart_example(field_name, field_schema);
                                obj.insert(field_name.clone(), value);
                            }
                        }
                    }

                    // If no required fields, include a helpful message
                    if obj.is_empty() {
                        obj.insert(
                            "_note".to_string(),
                            json!("No required fields - add your data here"),
                        );
                    }
                }

                let json_value = json!(obj);
                println!("📝 Generated minimal payload with required fields only:");
                println!(
                    "{}",
                    serde_json::to_string_pretty(&json_value)?.bright_black()
                );

                return Ok(Some(serde_json::to_string(&json_value)?));
            }
        }
    }

    Ok(None)
}

/// Intelligently decode URL-encoded parameters if they appear to be encoded
fn smart_decode_param(value: &str) -> String {
    // Check if the value contains % and looks like it might be URL-encoded
    if value.contains('%') && looks_like_url_encoded(value) {
        // Try to decode it
        match urlencoding::decode(value) {
            Ok(decoded) => {
                // Successfully decoded - return the decoded value
                decoded.to_string()
            }
            Err(_) => {
                // Decode failed - return original value
                value.to_string()
            }
        }
    } else {
        // Doesn't look URL-encoded - return as-is
        value.to_string()
    }
}

/// Check if a string looks like it contains URL encoding
fn looks_like_url_encoded(s: &str) -> bool {
    // Look for %XX patterns where X is a hex digit
    let encoded_pattern = regex::Regex::new(r"%[0-9A-Fa-f]{2}").unwrap();
    encoded_pattern.is_match(s)
}

// ============================================================================
// INTERACTIVE TEMPLATE GENERATION
// ============================================================================

/// Load query parameters from a file
fn load_query_from_file(cmd: &RunCommand, query_file: &PathBuf) -> Result<()> {
    if !query_file.exists() {
        return Err(ApiError::ValidationError(format!(
            "Query file not found: {}",
            query_file.display()
        ))
        .into());
    }

    let content = fs::read_to_string(query_file)?;
    let mut new_cmd = cmd.clone();
    new_cmd.params = Vec::new();

    // Parse the file (support both key=value format and JSON format)
    if content.trim().starts_with('{') {
        // JSON format
        let params: HashMap<String, String> = serde_json::from_str(&content)?;
        for (key, value) in params {
            new_cmd.params.push(format!("{}={}", key, value));
        }
    } else {
        // Key=value format (one per line)
        for line in content.lines() {
            let line = line.trim();
            if !line.is_empty() && !line.starts_with('#') {
                new_cmd.params.push(line.to_string());
            }
        }
    }

    println!("{}", "📂 Loading query from file:".bright_cyan());
    println!("  File: {}", query_file.display());
    println!("  Parameters loaded: {}", new_cmd.params.len());

    // Execute with the loaded parameters
    let mut operation_cmd = new_cmd;
    operation_cmd.query_file = None; // Clear to avoid recursion
    execute(operation_cmd)
}

/// Replay last successful query
fn replay_last_query(_cmd: &RunCommand) -> Result<()> {
    // Simplified version - replay feature removed to reduce complexity
    println!(
        "{}",
        "❌ Replay feature not available in simplified version".red()
    );
    println!("💡 Use shell history (up arrow) to replay previous commands");
    Ok(())
}

/// Generate an interactive template for the operation
fn generate_template_interactive(cmd: &RunCommand) -> Result<()> {
    let op_name = cmd
        .operation
        .as_ref()
        .ok_or_else(|| ApiError::ValidationError("Operation is required".to_string()))?;
    println!(
        "{} v{}",
        "Micro Rapid".bright_cyan(),
        env!("CARGO_PKG_VERSION")
    );

    // Find the API spec - use provided path or auto-detect
    let spec_path = get_spec_path(cmd)?;

    // Load and parse the spec
    let spec_content = fs::read_to_string(&spec_path)?;
    let spec = crate::core::parser::parse_spec(&spec_content)?;

    // Find the operation
    let operation = crate::core::show::find_operation_with_spec(&spec, op_name)?;

    // Display operation info
    println!(
        "📋 Operation: {} ({} {})",
        operation.operation_id.bright_cyan(),
        operation.method.to_uppercase().bright_green(),
        operation.path
    );

    // Display authentication requirements
    if let Some(security_reqs) = &operation.security {
        if !security_reqs.is_empty() {
            let auth_desc = if let Some(req) = security_reqs.first() {
                match spec.security_schemes.get(&req.scheme_name) {
                    Some(scheme) => match scheme.scheme_type.as_str() {
                        "apiKey" => {
                            format!("API Key ({})", scheme.name.as_deref().unwrap_or("api_key"))
                        }
                        "http" => match scheme.scheme.as_deref() {
                            Some("bearer") => "Bearer".to_string(),
                            Some("basic") => "Basic".to_string(),
                            _ => "HTTP".to_string(),
                        },
                        "oauth2" => "OAuth2".to_string(),
                        _ => req.scheme_name.clone(),
                    },
                    None => req.scheme_name.clone(),
                }
            } else {
                "Required".to_string()
            };
            println!("🔐 Auth: {} (from environment)", auth_desc.bright_yellow());
        }
    }

    // Check if this method needs a request body
    let needs_body = needs_body(&operation.method);

    if needs_body {
        // Generate body template for POST, PUT, PATCH
        let template = generate_operation_template(operation, &spec, cmd.minimal)?;

        // Display field information for request body
        if let Some(request_body) = &operation.request_body {
            // Get the first content type's schema (usually application/json)
            if let Some(media_type) = request_body.content.values().next() {
                let schema = &media_type.schema;
                let required_fields = schema
                    .required
                    .as_ref()
                    .map(|r| r.clone())
                    .unwrap_or_default();
                let all_fields: Vec<String> = if let serde_json::Value::Object(obj) = &template {
                    obj.keys().cloned().collect()
                } else {
                    vec![]
                };

                let optional_fields: Vec<String> = all_fields
                    .iter()
                    .filter(|f| !required_fields.contains(f))
                    .cloned()
                    .collect();

                println!();
                if !required_fields.is_empty() {
                    println!(
                        "Required fields: {}",
                        required_fields.join(", ").bright_yellow()
                    );
                }
                if !optional_fields.is_empty() && !cmd.minimal {
                    println!("Optional fields: {}", optional_fields.join(", ").dimmed());
                }
            }
        }

        // Pretty print the template
        println!("\n📄 Generated template with realistic examples:");
        let pretty_json = serde_json::to_string_pretty(&template)?;
        println!("{}", pretty_json.bright_white());

        // Save the template to file
        let filename = generate_template_filename(&operation.operation_id, cmd.save_as.as_deref());
        fs::write(&filename, &pretty_json)?;
        println!(
            "\n💾 Template saved to: {}",
            filename.display().to_string().bright_green()
        );

        // Show next steps for body-based requests
        println!("\n👉 Next steps:");
        let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
        println!(
            "   1. Edit: {} {}",
            editor.bright_cyan(),
            filename.display()
        );

        let run_cmd = format!("mrapids run {} --data @{}", op_name, filename.display());
        println!("   2. Run:  {}", run_cmd.bright_cyan());
    } else {
        // For GET, DELETE, HEAD, OPTIONS - show parameter information
        println!();

        // Display path parameters
        let path_params: Vec<_> = operation
            .parameters
            .iter()
            .filter(|p| p.location == crate::core::parser::ParameterLocation::Path)
            .collect();

        if !path_params.is_empty() {
            println!("{}", "PATH PARAMETERS (required):".bright_yellow());
            for param in &path_params {
                let example = generate_smart_example(&param.name, &param.schema);
                println!(
                    "{}: {}",
                    param.name.bright_white(),
                    serde_json::to_string(&example).unwrap_or_else(|_| "example".to_string())
                );
            }
            println!();
        }

        // Display query parameters with deduplication and grouping
        let query_params: Vec<_> = operation
            .parameters
            .iter()
            .filter(|p| p.location == crate::core::parser::ParameterLocation::Query)
            .cloned()
            .collect();

        if !query_params.is_empty() {
            // Display query parameters
            println!("{}", "QUERY PARAMETERS:".bright_yellow());
            for param in &query_params {
                let required = if param.required { " (required)" } else { "" };
                println!("  --param {}=<value>{}", param.name, required.red());
            }
            println!();
        }

        // Show usage examples for parameter-based requests
        println!("{}", "USAGE EXAMPLES:".bright_green());

        // Build example command with parameters
        let mut example_cmd = format!("mrapids run {}", op_name);

        // Add path parameter examples
        for param in &path_params {
            example_cmd.push_str(&format!(" --param {}=<value>", param.name));
        }

        // Add required query parameter examples
        for param in query_params.iter().filter(|p| p.required) {
            example_cmd.push_str(&format!(" --param {}=<value>", param.name));
        }

        println!("\n  {}", example_cmd.bright_cyan());

        // Show a concrete example with actual values
        if !path_params.is_empty() || !query_params.is_empty() {
            println!("\n{}", "CONCRETE EXAMPLE:".bright_green());
            let mut concrete_cmd = format!("mrapids run {}", op_name);

            for param in &path_params {
                let example = generate_parameter_example(&param);
                let value_str = match example {
                    Value::String(s) => s,
                    Value::Number(n) => n.to_string(),
                    _ => "value".to_string(),
                };
                concrete_cmd.push_str(&format!(" --param {}={}", param.name, value_str));
            }

            // Add example query parameters
            for param in query_params.iter().take(3) {
                // Show first 3 query params as example
                let example = generate_parameter_example(param);
                let value_str = match example {
                    Value::String(s) => format!("'{}'", s),
                    Value::Number(n) => n.to_string(),
                    _ => "'value'".to_string(),
                };
                concrete_cmd.push_str(&format!(" --param {}={}", param.name, value_str));
            }

            println!("  {}", concrete_cmd.bright_cyan());
        }

        println!(
            "\n💡 Note: {} requests use parameters, not request bodies.",
            operation.method.to_uppercase().bright_yellow()
        );
        println!("   Use --param key=value for parameters");
        println!("   Use --query key=value to force query parameters");
    }

    Ok(())
}

/// Generate a template for the operation (only for methods that need request bodies)
fn generate_operation_template(
    operation: &crate::core::parser::UnifiedOperation,
    _spec: &crate::core::parser::UnifiedSpec,
    minimal: bool,
) -> Result<Value> {
    // This function should only be called for POST, PUT, PATCH
    // which should have request bodies
    if let Some(request_body) = &operation.request_body {
        // Get the first content type's schema (usually application/json)
        if let Some(media_type) = request_body.content.values().next() {
            generate_template_from_schema(&media_type.schema, "body", minimal)
        } else {
            // Request body exists but no content types defined
            Ok(json!({}))
        }
    } else {
        // No request body defined for POST/PUT/PATCH - return empty object
        // This might happen with some APIs that use only query/path params
        Ok(json!({}))
    }
}

/// Generate a template from a schema
fn generate_template_from_schema(
    schema: &crate::core::parser::UnifiedSchema,
    field_name: &str,
    minimal: bool,
) -> Result<Value> {
    use crate::core::parser::SchemaType;

    match &schema.schema_type {
        SchemaType::Object => {
            let mut obj = serde_json::Map::new();

            if let Some(properties) = &schema.properties {
                for (prop_name, prop_schema) in properties {
                    // Skip optional fields if minimal mode
                    let required_fields = schema
                        .required
                        .as_ref()
                        .map(|r| r.clone())
                        .unwrap_or_default();
                    if minimal && !required_fields.contains(prop_name) {
                        continue;
                    }

                    let value = generate_template_from_schema(prop_schema, prop_name, minimal)?;
                    obj.insert(prop_name.clone(), value);
                }
            }

            Ok(Value::Object(obj))
        }
        SchemaType::Array => {
            // Generate a single example item
            let item = if let Some(items) = &schema.items {
                generate_template_from_schema(items, field_name, minimal)?
            } else {
                json!("example")
            };
            Ok(json!([item]))
        }
        _ => {
            // Use the existing smart example generator
            Ok(generate_smart_example(field_name, schema))
        }
    }
}

/// Generate a smart filename for the template
fn generate_template_filename(operation_id: &str, save_as: Option<&Path>) -> PathBuf {
    // If custom filename provided, use it
    if let Some(custom) = save_as {
        return custom.to_path_buf();
    }

    // Convert operation ID to kebab-case filename
    let base = to_kebab_case(operation_id);
    let mut filename = PathBuf::from(format!("{}.json", base));

    // Handle conflicts by adding a number
    let mut counter = 2;
    while filename.exists() {
        filename = PathBuf::from(format!("{}-{}.json", base, counter));
        counter += 1;
    }

    filename
}

/// Convert a string to kebab-case
fn to_kebab_case(s: &str) -> String {
    let mut result = String::new();
    let mut prev_upper = false;

    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() {
            if i > 0 && !prev_upper {
                result.push('-');
            }
            result.push(ch.to_lowercase().next().unwrap());
            prev_upper = true;
        } else {
            result.push(ch);
            prev_upper = false;
        }
    }

    result
}

/// Load and execute a saved query
fn load_saved_query(name: &str) -> Result<()> {
    use crate::core::saved_queries;

    println!("📂 Loading saved query: {}", name.bright_cyan());

    let query = saved_queries::load_query(name)?;

    // Display query details
    saved_queries::display_query_details(name)?;

    // Build equivalent RunCommand and execute
    println!();
    println!("{}", "Execute this query? (y/n): ".bright_yellow());

    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;

    if input.trim().to_lowercase() == "y" || input.trim().to_lowercase() == "yes" {
        println!();
        println!("{}", "Executing...".bright_green());
        println!();

        // Re-parse as RunCommand and execute
        let new_cmd = RunCommand {
            operation: Some(query.operation.clone()),
            params: query
                .params
                .iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect(),
            query_params: Vec::new(),
            headers: query
                .headers
                .iter()
                .map(|(k, v)| format!("{}: {}", k, v))
                .collect(),
            data: query.body.clone(),
            file: None,
            id: None,
            name: None,
            status: None,
            limit: None,
            offset: None,
            sort: None,
            auth: None,
            api_key: None,
            auth_profile: None,
            env: query.env.clone(),
            url: None,
            output: "pretty".to_string(),
            save: None,
            template: None,
            template_vars: Vec::new(),
            required_only: false,
            verbose: false,
            dry_run: false,
            as_curl: false,
            edit: false,
            stdin: false,
            retry: 0,
            timeout: 30,
            allow_insecure: false,
            allow_localhost: false,
            no_warnings: false,
            redact: false,
            interactive: false,
            save_as: None,
            minimal: false,
            help_query: false,
            build_query: false,
            query_file: None,
            replay_last: false,
            save_query: None,
            load_query: None,
            list_queries: false,
            save_to_collection: false,
            collection: None,
            save_as_request: None,
            json_output: false,
            log_decisions: false,
            spec: None,
        };

        execute_direct_operation(&new_cmd)
    } else {
        println!("{}", "Cancelled.".dimmed());
        Ok(())
    }
}

/// Save current query parameters
pub fn save_current_query(cmd: &RunCommand, name: &str) -> Result<()> {
    use crate::core::saved_queries::{save_query, SavedQuery};

    let op_name = cmd.operation.as_ref().ok_or_else(|| {
        ApiError::ValidationError("Operation is required to save a query".to_string())
    })?;

    let query = SavedQuery::from_run_params(
        name,
        op_name,
        &cmd.params,
        &cmd.headers,
        cmd.data.as_deref(),
        cmd.env.as_deref(),
    );

    let path = save_query(&query)?;

    println!();
    println!(
        "{} Saved query '{}' to {}",
        "".bright_green(),
        name.bright_cyan(),
        path.display().to_string().dimmed()
    );
    println!();
    println!(
        "{} mrapids run --load-query {}",
        "Run with:".bright_blue(),
        name
    );
    println!();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::config::AuthScheme;

    // ============================================================================
    // needs_body tests
    // ============================================================================

    #[test]
    fn test_needs_body_post() {
        assert!(needs_body("POST"));
        assert!(needs_body("post"));
        assert!(needs_body("Post"));
    }

    #[test]
    fn test_needs_body_put() {
        assert!(needs_body("PUT"));
        assert!(needs_body("put"));
    }

    #[test]
    fn test_needs_body_patch() {
        assert!(needs_body("PATCH"));
        assert!(needs_body("patch"));
    }

    #[test]
    fn test_needs_body_get_delete() {
        assert!(!needs_body("GET"));
        assert!(!needs_body("DELETE"));
        assert!(!needs_body("HEAD"));
        assert!(!needs_body("OPTIONS"));
    }

    // ============================================================================
    // to_kebab_case tests
    // ============================================================================

    #[test]
    fn test_to_kebab_case_camel() {
        assert_eq!(to_kebab_case("getUserById"), "get-user-by-id");
        assert_eq!(to_kebab_case("createOrder"), "create-order");
    }

    #[test]
    fn test_to_kebab_case_pascal() {
        assert_eq!(to_kebab_case("GetUser"), "get-user");
        assert_eq!(to_kebab_case("CreateNewCustomer"), "create-new-customer");
    }

    #[test]
    fn test_to_kebab_case_already_lowercase() {
        assert_eq!(to_kebab_case("getuser"), "getuser");
        assert_eq!(to_kebab_case("simple"), "simple");
    }

    #[test]
    fn test_to_kebab_case_with_numbers() {
        assert_eq!(to_kebab_case("getUser123"), "get-user123");
    }

    // ============================================================================
    // looks_like_url_encoded tests
    // ============================================================================

    #[test]
    fn test_looks_like_url_encoded_true() {
        assert!(looks_like_url_encoded("hello%20world"));
        assert!(looks_like_url_encoded("name%3Dvalue"));
        assert!(looks_like_url_encoded("%2F%2Fpath"));
    }

    #[test]
    fn test_looks_like_url_encoded_false() {
        assert!(!looks_like_url_encoded("hello world"));
        assert!(!looks_like_url_encoded("simple"));
        assert!(!looks_like_url_encoded("100%")); // Not valid %XX
        assert!(!looks_like_url_encoded("%ZZ")); // Invalid hex
    }

    // ============================================================================
    // smart_decode_param tests
    // ============================================================================

    #[test]
    fn test_smart_decode_param_encoded() {
        assert_eq!(smart_decode_param("hello%20world"), "hello world");
        assert_eq!(smart_decode_param("name%3Dvalue"), "name=value");
    }

    #[test]
    fn test_smart_decode_param_not_encoded() {
        assert_eq!(smart_decode_param("hello world"), "hello world");
        assert_eq!(smart_decode_param("simple"), "simple");
    }

    #[test]
    fn test_smart_decode_param_partial() {
        // 100% should not be decoded (not valid encoding)
        assert_eq!(smart_decode_param("100%"), "100%");
    }

    // ============================================================================
    // substitute_variables tests
    // ============================================================================

    #[test]
    fn test_substitute_variables_simple() {
        let mut vars = HashMap::new();
        vars.insert("NAME".to_string(), "John".to_string());
        vars.insert("AGE".to_string(), "30".to_string());

        let result = substitute_variables("Hello ${NAME}, you are ${AGE}", &vars).unwrap();
        assert_eq!(result, "Hello John, you are 30");
    }

    #[test]
    fn test_substitute_variables_missing() {
        let vars = HashMap::new();
        let result = substitute_variables("Hello ${NAME}", &vars).unwrap();
        // Missing variable should remain unchanged
        assert_eq!(result, "Hello ${NAME}");
    }

    #[test]
    fn test_substitute_variables_with_default() {
        let mut vars = HashMap::new();
        vars.insert("NAME".to_string(), "John".to_string());

        let result = substitute_variables("Hello ${NAME:default}", &vars).unwrap();
        assert_eq!(result, "Hello John");
    }

    #[test]
    fn test_substitute_variables_empty() {
        let vars = HashMap::new();
        let result = substitute_variables("No variables here", &vars).unwrap();
        assert_eq!(result, "No variables here");
    }

    // ============================================================================
    // Request struct tests
    // ============================================================================

    fn create_test_request() -> Request {
        Request {
            method: "GET".to_string(),
            path: "/users/{id}".to_string(),
            base_url: "https://api.example.com".to_string(),
            headers: HashMap::new(),
            query_params: HashMap::new(),
            path_params: HashMap::new(),
            body: None,
            spec_content_type: None,
        }
    }

    // ============================================================================
    // apply_auth_scheme_to_request tests
    // ============================================================================

    #[test]
    fn test_apply_auth_bearer_token() {
        let mut request = create_test_request();
        let scheme = AuthScheme::Bearer {
            token: "my-secret-token".to_string(),
            format: None,
        };

        apply_auth_scheme_to_request(&mut request, &scheme);

        assert_eq!(
            request.headers.get("Authorization"),
            Some(&"Bearer my-secret-token".to_string())
        );
    }

    #[test]
    fn test_apply_auth_api_key_header() {
        let mut request = create_test_request();
        let scheme = AuthScheme::ApiKey {
            location: "header".to_string(),
            name: "X-API-Key".to_string(),
            value: "api-key-123".to_string(),
        };

        apply_auth_scheme_to_request(&mut request, &scheme);

        assert_eq!(
            request.headers.get("X-API-Key"),
            Some(&"api-key-123".to_string())
        );
    }

    #[test]
    fn test_apply_auth_api_key_query() {
        let mut request = create_test_request();
        let scheme = AuthScheme::ApiKey {
            location: "query".to_string(),
            name: "api_key".to_string(),
            value: "query-key-456".to_string(),
        };

        apply_auth_scheme_to_request(&mut request, &scheme);

        assert_eq!(
            request.query_params.get("api_key"),
            Some(&"query-key-456".to_string())
        );
    }

    #[test]
    fn test_apply_auth_basic() {
        let mut request = create_test_request();
        let scheme = AuthScheme::Basic {
            username: "user".to_string(),
            password: "pass".to_string(),
        };

        apply_auth_scheme_to_request(&mut request, &scheme);

        let auth_header = request.headers.get("Authorization").unwrap();
        assert!(auth_header.starts_with("Basic "));

        // Decode and verify
        use base64::Engine;
        let encoded = auth_header.trim_start_matches("Basic ");
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .unwrap();
        let credentials = String::from_utf8(decoded).unwrap();
        assert_eq!(credentials, "user:pass");
    }

    // ============================================================================
    // find_env_var_with_value tests
    // ============================================================================

    #[test]
    fn test_find_env_var_with_value_found() {
        // Set a test environment variable
        std::env::set_var("TEST_MRAPIDS_TOKEN", "test-token-12345");

        let result = find_env_var_with_value("test-token-12345");
        assert_eq!(result, Some("TEST_MRAPIDS_TOKEN".to_string()));

        // Clean up
        std::env::remove_var("TEST_MRAPIDS_TOKEN");
    }

    #[test]
    fn test_find_env_var_with_value_not_found() {
        let result = find_env_var_with_value("this-value-does-not-exist-anywhere");
        assert_eq!(result, None);
    }

    // ============================================================================
    // Request building integration tests
    // ============================================================================

    #[test]
    fn test_request_headers_can_be_overridden() {
        let mut request = create_test_request();
        request
            .headers
            .insert("Content-Type".to_string(), "application/json".to_string());
        request
            .headers
            .insert("Accept".to_string(), "application/json".to_string());

        // Override Content-Type
        request
            .headers
            .insert("Content-Type".to_string(), "application/xml".to_string());

        assert_eq!(
            request.headers.get("Content-Type"),
            Some(&"application/xml".to_string())
        );
    }

    #[test]
    fn test_request_query_params() {
        let mut request = create_test_request();
        request
            .query_params
            .insert("limit".to_string(), "10".to_string());
        request
            .query_params
            .insert("offset".to_string(), "0".to_string());

        assert_eq!(request.query_params.len(), 2);
        assert_eq!(request.query_params.get("limit"), Some(&"10".to_string()));
    }

    #[test]
    fn test_request_with_body() {
        let mut request = create_test_request();
        request.method = "POST".to_string();
        request.body = Some(r#"{"name": "test"}"#.to_string());

        assert!(request.body.is_some());
        assert!(needs_body(&request.method));
    }

    #[test]
    fn test_content_type_from_spec() {
        let mut request = create_test_request();
        request.method = "POST".to_string();
        request.body = Some(r#"{"name": "test"}"#.to_string());
        request.spec_content_type = Some("application/json".to_string());

        // When spec_content_type is set, it should be used
        if request.body.is_some() {
            if let Some(spec_ct) = &request.spec_content_type {
                request
                    .headers
                    .insert("Content-Type".to_string(), spec_ct.clone());
            }
        }

        assert_eq!(
            request.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn test_content_type_fallback_to_json() {
        let mut request = create_test_request();
        request.method = "POST".to_string();
        request.body = Some(r#"{"name": "test"}"#.to_string());
        request.spec_content_type = None; // No spec content type

        // When body exists but no spec_content_type, should fallback to application/json
        if request.body.is_some() {
            if let Some(spec_ct) = &request.spec_content_type {
                request
                    .headers
                    .insert("Content-Type".to_string(), spec_ct.clone());
            } else if !request.headers.contains_key("Content-Type") {
                request
                    .headers
                    .insert("Content-Type".to_string(), "application/json".to_string());
            }
        }

        assert_eq!(
            request.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn test_content_type_not_set_for_get() {
        let mut request = create_test_request();
        request.method = "GET".to_string();
        request.body = None;
        request.spec_content_type = None;

        // GET requests without body should not have Content-Type set
        if request.body.is_some() {
            if let Some(spec_ct) = &request.spec_content_type {
                request
                    .headers
                    .insert("Content-Type".to_string(), spec_ct.clone());
            } else if !request.headers.contains_key("Content-Type") {
                request
                    .headers
                    .insert("Content-Type".to_string(), "application/json".to_string());
            }
        }

        assert_eq!(request.headers.get("Content-Type"), None);
    }

    #[test]
    fn test_content_type_preserves_existing() {
        let mut request = create_test_request();
        request.method = "POST".to_string();
        request.body = Some(r#"<xml>test</xml>"#.to_string());
        request.spec_content_type = None;
        request
            .headers
            .insert("Content-Type".to_string(), "application/xml".to_string());

        // Existing Content-Type should be preserved (not overwritten)
        if request.body.is_some() {
            if let Some(spec_ct) = &request.spec_content_type {
                request
                    .headers
                    .insert("Content-Type".to_string(), spec_ct.clone());
            } else if !request.headers.contains_key("Content-Type") {
                request
                    .headers
                    .insert("Content-Type".to_string(), "application/json".to_string());
            }
        }

        // Should still be XML, not overwritten to JSON
        assert_eq!(
            request.headers.get("Content-Type"),
            Some(&"application/xml".to_string())
        );
    }
}