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
use crate::cli::DoctorCommand;
use anyhow::Result;
use colored::*;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;

#[derive(Debug)]
struct DiagnosticResult {
    category: String,
    status: DiagnosticStatus,
    message: String,
    fix_hint: Option<String>,
}

#[derive(Debug, PartialEq)]
enum DiagnosticStatus {
    Ok,
    Warning,
    Error,
}

pub fn run_diagnostics(cmd: DoctorCommand, env: Option<String>) -> Result<()> {
    let mut results = Vec::new();

    // Get environment from parameter or default from mrapids.yaml
    let env_name = if let Some(env) = env {
        env
    } else {
        // Try to read default from mrapids.yaml
        let manifest_path = std::path::PathBuf::from("mrapids.yaml");
        if manifest_path.exists() {
            let content = fs::read_to_string(&manifest_path)?;
            let manifest: serde_yaml::Value = serde_yaml::from_str(&content)?;
            manifest
                .get("default_env")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| "development".to_string())
        } else {
            "development".to_string()
        }
    };

    // Print header
    println!(
        "\n{} {} {}",
        "🏥".bright_cyan(),
        "MRapids Configuration Check".bold(),
        format!("[{}]", env_name).bright_blue()
    );
    println!("{}", "".repeat(50).dimmed());

    // Check what to diagnose
    let check_all = cmd.check == "all";

    // 1. Check project structure
    if check_all || cmd.check == "config" {
        results.extend(check_project_structure(&cmd.path)?);
    }

    // 2. Check configuration
    if check_all || cmd.check == "config" {
        results.extend(check_configuration(&cmd.path)?);
    }

    // 3. Check authentication
    if check_all || cmd.check == "auth" {
        results.extend(check_authentication(&cmd.path, &env_name)?);
    }

    // 4. Check base URL resolution
    if check_all || cmd.check == "env" {
        results.extend(check_base_url_resolution(&cmd.path, &env_name)?);
    }

    // 5. Check OpenAPI spec
    if check_all || cmd.check == "spec" {
        results.extend(check_openapi_spec(&cmd.path)?);
    }

    // 6. Check environment variable consistency
    if check_all || cmd.check == "env" {
        results.extend(check_env_consistency(&cmd.path, &env_name)?);
    }

    // 7. Check decision logging status
    if check_all || cmd.check == "config" {
        results.extend(check_decision_logging());
    }

    // Apply fixes if requested
    if cmd.fix {
        apply_fixes(&cmd.path, &mut results)?;
    }

    // Display results
    display_results(&results, &cmd)?;

    // Show summary
    display_summary(&results, cmd.fix)?;

    Ok(())
}

fn check_project_structure(project_path: &Path) -> Result<Vec<DiagnosticResult>> {
    let mut results = Vec::new();

    println!("\n{} {}", "".green(), "Project Structure".bold());

    // Check for mrapids.yaml (now it IS used!)
    let mrapids_yaml = project_path.join("mrapids.yaml");
    if mrapids_yaml.exists() {
        // Try to parse it
        if let Ok(content) = fs::read_to_string(&mrapids_yaml) {
            if let Ok(_manifest) = serde_yaml::from_str::<crate::core::config::Manifest>(&content) {
                results.push(DiagnosticResult {
                    category: "Structure".to_string(),
                    status: DiagnosticStatus::Ok,
                    message: "mrapids.yaml manifest found and valid".to_string(),
                    fix_hint: None,
                });
            } else {
                results.push(DiagnosticResult {
                    category: "Structure".to_string(),
                    status: DiagnosticStatus::Warning,
                    message: "mrapids.yaml found but invalid format".to_string(),
                    fix_hint: Some("Check YAML syntax in mrapids.yaml".to_string()),
                });
            }
        }
    } else {
        results.push(DiagnosticResult {
            category: "Structure".to_string(),
            status: DiagnosticStatus::Error,
            message: "mrapids.yaml not found".to_string(),
            fix_hint: Some("Run: mrapids init <project-name>".to_string()),
        });
    }

    // Check for specs directory
    let specs_dir = project_path.join("specs");
    if specs_dir.exists() {
        // Look for API spec files
        let has_spec = ["api.yaml", "api.json", "openapi.yaml", "openapi.json"]
            .iter()
            .any(|f| specs_dir.join(f).exists());

        if has_spec {
            results.push(DiagnosticResult {
                category: "Structure".to_string(),
                status: DiagnosticStatus::Ok,
                message: "specs/ directory with API specification found".to_string(),
                fix_hint: None,
            });
        } else {
            results.push(DiagnosticResult {
                category: "Structure".to_string(),
                status: DiagnosticStatus::Warning,
                message: "specs/ directory exists but no API spec found".to_string(),
                fix_hint: Some("Add your OpenAPI spec to specs/api.yaml".to_string()),
            });
        }
    } else {
        results.push(DiagnosticResult {
            category: "Structure".to_string(),
            status: DiagnosticStatus::Error,
            message: "specs/ directory not found".to_string(),
            fix_hint: Some("Run: mrapids init <project-name>".to_string()),
        });
    }

    // Check for config directory
    let config_dir = project_path.join("config");
    if config_dir.exists() {
        // Check for environment configs
        let env_configs = [
            "default.yaml",
            "development.yaml",
            "staging.yaml",
            "production.yaml",
        ];
        let found_configs: Vec<_> = env_configs
            .iter()
            .filter(|f| config_dir.join(f).exists())
            .collect();

        if !found_configs.is_empty() {
            results.push(DiagnosticResult {
                category: "Structure".to_string(),
                status: DiagnosticStatus::Ok,
                message: format!(
                    "config/ directory with {} environment configs",
                    found_configs.len()
                ),
                fix_hint: None,
            });
        } else {
            results.push(DiagnosticResult {
                category: "Structure".to_string(),
                status: DiagnosticStatus::Warning,
                message: "config/ directory exists but no configs found".to_string(),
                fix_hint: Some("Add config/default.yaml or config/dev.yaml".to_string()),
            });
        }
    } else {
        results.push(DiagnosticResult {
            category: "Structure".to_string(),
            status: DiagnosticStatus::Warning,
            message: "config/ directory not found".to_string(),
            fix_hint: Some("Run: mrapids init <project-name>".to_string()),
        });
    }

    // Check for env directory
    let env_dir = project_path.join("env");
    if env_dir.exists() {
        // Check for .env files
        let env_files = [".env.development", ".env.staging", ".env.production"];
        let found_envs: Vec<_> = env_files
            .iter()
            .filter(|f| env_dir.join(f).exists())
            .collect();

        if !found_envs.is_empty() {
            results.push(DiagnosticResult {
                category: "Structure".to_string(),
                status: DiagnosticStatus::Ok,
                message: format!("env/ directory with {} env files", found_envs.len()),
                fix_hint: None,
            });
        } else {
            results.push(DiagnosticResult {
                category: "Structure".to_string(),
                status: DiagnosticStatus::Warning,
                message: "env/ directory exists but no .env files found".to_string(),
                fix_hint: Some(
                    "Add env/.env.development with your environment variables".to_string(),
                ),
            });
        }
    } else {
        results.push(DiagnosticResult {
            category: "Structure".to_string(),
            status: DiagnosticStatus::Warning,
            message: "env/ directory not found".to_string(),
            fix_hint: Some("Run: mrapids init <project-name>".to_string()),
        });
    }

    // Check for auth.yaml
    let auth_yaml = project_path.join("auth.yaml");
    if auth_yaml.exists() {
        results.push(DiagnosticResult {
            category: "Structure".to_string(),
            status: DiagnosticStatus::Ok,
            message: "auth.yaml file found".to_string(),
            fix_hint: None,
        });
    }

    Ok(results)
}

fn check_configuration(project_path: &Path) -> Result<Vec<DiagnosticResult>> {
    let mut results = Vec::new();

    println!("\n{} {}", "⚠️".yellow(), "Configuration Issues".bold());

    // Check for default.yaml
    let default_config = project_path.join("config/default.yaml");
    if default_config.exists() {
        // Try to parse it
        if let Ok(content) = fs::read_to_string(&default_config) {
            if content.contains("base_url:") {
                results.push(DiagnosticResult {
                    category: "Config".to_string(),
                    status: DiagnosticStatus::Ok,
                    message: "config/default.yaml exists with base_url".to_string(),
                    fix_hint: None,
                });
            } else {
                results.push(DiagnosticResult {
                    category: "Config".to_string(),
                    status: DiagnosticStatus::Warning,
                    message: "config/default.yaml missing base_url field".to_string(),
                    fix_hint: Some("Add: base_url: https://api.example.com".to_string()),
                });
            }
        }
    } else {
        results.push(DiagnosticResult {
            category: "Config".to_string(),
            status: DiagnosticStatus::Error,
            message: "config/default.yaml missing".to_string(),
            fix_hint: Some("Run: mrapids init <project-name> to create config".to_string()),
        });
    }

    // Check for .env file
    let env_file = project_path.join(".env");
    let env_example = project_path.join("config/.env.example");

    if !env_file.exists() && env_example.exists() {
        results.push(DiagnosticResult {
            category: "Config".to_string(),
            status: DiagnosticStatus::Warning,
            message: "No .env file found".to_string(),
            fix_hint: Some("Copy config/.env.example to .env and fill in values".to_string()),
        });
    } else if env_file.exists() {
        results.push(DiagnosticResult {
            category: "Config".to_string(),
            status: DiagnosticStatus::Ok,
            message: ".env file exists".to_string(),
            fix_hint: None,
        });
    }

    Ok(results)
}

fn check_authentication(project_path: &Path, env_name: &str) -> Result<Vec<DiagnosticResult>> {
    let mut results = Vec::new();

    println!(
        "\n{} {} {}",
        "🔑".yellow(),
        "Authentication".bold(),
        format!("[{}]", env_name).bright_blue()
    );

    // Check OpenAPI spec for auth requirements
    let spec_files = [
        "specs/api.yaml",
        "specs/api.json",
        "specs/openapi.yaml",
        "specs/openapi.json",
    ];
    let mut auth_methods = Vec::new();

    for spec_file in &spec_files {
        let spec_path = project_path.join(spec_file);
        if spec_path.exists() {
            if let Ok(content) = fs::read_to_string(&spec_path) {
                // Check for auth schemes in OpenAPI spec
                if content.contains("bearerAuth") || content.contains("scheme: bearer") {
                    auth_methods.push("Bearer Token");
                }
                if content.contains("apiKey") || content.contains("type: apiKey") {
                    auth_methods.push("API Key");
                }
                if content.contains("basic") || content.contains("scheme: basic") {
                    auth_methods.push("Basic Auth");
                }
                if content.contains("oauth2") || content.contains("type: oauth2") {
                    auth_methods.push("OAuth 2.0");
                }
            }
            break;
        }
    }

    if !auth_methods.is_empty() {
        results.push(DiagnosticResult {
            category: "Auth".to_string(),
            status: DiagnosticStatus::Ok,
            message: format!("API spec defines: {}", auth_methods.join(", ")),
            fix_hint: None,
        });
    }

    // Check environment variables for common auth patterns
    let env_prefix = env_name.to_uppercase();

    // Check for environment-specific auth variables
    let has_bearer = env::var(format!("{}_{}", env_prefix.replace("-", "_"), "API_TOKEN")).is_ok()
        || env::var(format!("{}_{}", env_prefix.replace("-", "_"), "TOKEN")).is_ok();
    let has_api_key = env::var(format!("{}_{}", env_prefix.replace("-", "_"), "API_KEY")).is_ok();
    let has_basic = env::var(format!("{}_{}", env_prefix.replace("-", "_"), "BASIC_AUTH")).is_ok();

    // Also check generic variables
    let has_generic_token = env::var("API_TOKEN").is_ok() || env::var("AUTH_TOKEN").is_ok();
    let has_generic_key = env::var("API_KEY").is_ok();

    if !has_bearer && !has_api_key && !has_basic && !has_generic_token && !has_generic_key {
        results.push(DiagnosticResult {
            category: "Auth".to_string(),
            status: DiagnosticStatus::Warning,
            message: "No auth credentials found in environment".to_string(),
            fix_hint: Some(format!(
                "Add credentials to env/.env.{} (e.g., {}_API_TOKEN, {}_API_KEY)",
                env_name,
                env_prefix.replace("-", "_"),
                env_prefix.replace("-", "_")
            )),
        });
    } else {
        let mut configured = Vec::new();
        if has_bearer || has_generic_token {
            configured.push("Bearer/Token");
        }
        if has_api_key || has_generic_key {
            configured.push("API Key");
        }
        if has_basic {
            configured.push("Basic Auth");
        }

        results.push(DiagnosticResult {
            category: "Auth".to_string(),
            status: DiagnosticStatus::Ok,
            message: format!("Auth credentials found: {}", configured.join(", ")),
            fix_hint: None,
        });
    }

    Ok(results)
}

fn check_base_url_resolution(project_path: &Path, env_name: &str) -> Result<Vec<DiagnosticResult>> {
    let mut results = Vec::new();

    println!(
        "\n{} {} {}",
        "🌐".bright_blue(),
        "Base URL Resolution".bold(),
        format!("[{}]", env_name).bright_blue()
    );
    println!("   Checking resolution order:");

    let mut found_url = None;
    let mut resolution_steps = Vec::new();

    // 1. Check environment-specific config first
    let env_config = project_path.join(format!("config/{}.yaml", env_name));
    if env_config.exists() {
        if let Ok(content) = fs::read_to_string(&env_config) {
            if let Some(line) = content.lines().find(|l| l.trim().starts_with("base_url:")) {
                let url = line.split(':').nth(1).map(|s| s.trim()).unwrap_or("");
                if !url.is_empty() && !url.starts_with("$") {
                    found_url = Some(url.to_string());
                    resolution_steps.push(format!(
                        "   1. config/{}.yaml: {} {}",
                        env_name,
                        "".green(),
                        url
                    ));
                } else if url.starts_with("$") {
                    resolution_steps.push(format!(
                        "   1. config/{}.yaml: {} Uses env variable: {}",
                        env_name,
                        "".green(),
                        url
                    ));
                } else {
                    resolution_steps.push(format!(
                        "   1. config/{}.yaml: {} No base_url field",
                        env_name,
                        "".red()
                    ));
                }
            } else {
                resolution_steps.push(format!(
                    "   1. config/{}.yaml: {} No base_url field",
                    env_name,
                    "".red()
                ));
            }
        }
    } else {
        resolution_steps.push(format!(
            "   1. config/{}.yaml: {} File not found",
            env_name,
            "".red()
        ));
    }

    // 2. Check config/default.yaml
    let default_config = project_path.join("config/default.yaml");
    if default_config.exists() && found_url.is_none() {
        if let Ok(content) = fs::read_to_string(&default_config) {
            if let Some(line) = content.lines().find(|l| l.trim().starts_with("base_url:")) {
                let url = line.split(':').nth(1).map(|s| s.trim()).unwrap_or("");
                if !url.is_empty() && !url.starts_with("$") {
                    found_url = Some(url.to_string());
                    resolution_steps.push(format!(
                        "   2. config/default.yaml: {} {}",
                        "".green(),
                        url
                    ));
                } else {
                    resolution_steps.push(format!(
                        "   2. config/default.yaml: {} Uses env variable",
                        "".green()
                    ));
                }
            } else {
                resolution_steps.push(format!(
                    "   2. config/default.yaml: {} No base_url field",
                    "".red()
                ));
            }
        }
    } else {
        resolution_steps.push(format!(
            "   2. config/default.yaml: {} File not found",
            "".red()
        ));
    }

    // 3. Check environment-specific variables first
    let env_prefix = env_name.to_uppercase().replace("-", "_");
    let env_base_url_var = format!("{}_BASE_URL", env_prefix);

    if let Ok(url) = env::var(&env_base_url_var) {
        if found_url.is_none() {
            found_url = Some(url.clone());
        }
        resolution_steps.push(format!(
            "   3. ${}: {} {}",
            env_base_url_var,
            "".green(),
            url
        ));
    } else {
        resolution_steps.push(format!(
            "   3. ${}: {} Not set",
            env_base_url_var,
            "".red()
        ));
    }

    // 4. Check generic environment variables
    if let Ok(url) = env::var("API_BASE_URL") {
        if found_url.is_none() {
            found_url = Some(url.clone());
        }
        resolution_steps.push(format!("   4. $API_BASE_URL: {} {}", "".green(), url));
    } else {
        resolution_steps.push(format!("   4. $API_BASE_URL: {} Not set", "".red()));
    }

    if let Ok(url) = env::var("MRAPIDS_BASE_URL") {
        if found_url.is_none() {
            found_url = Some(url.clone());
        }
        resolution_steps.push(format!("   5. $MRAPIDS_BASE_URL: {} {}", "".green(), url));
    } else {
        resolution_steps.push(format!("   5. $MRAPIDS_BASE_URL: {} Not set", "".red()));
    }

    // 6. Check OpenAPI spec
    let spec_files = [
        "specs/api.yaml",
        "specs/api.json",
        "specs/openapi.yaml",
        "specs/openapi.json",
    ];
    let mut spec_url = None;

    for spec_file in &spec_files {
        let spec_path = project_path.join(spec_file);
        if spec_path.exists() {
            if let Ok(content) = fs::read_to_string(&spec_path) {
                // Look for servers section
                if let Some(servers_line) = content.lines().find(|l| l.trim().starts_with("- url:"))
                {
                    let url = servers_line
                        .split(':')
                        .skip(1)
                        .collect::<Vec<_>>()
                        .join(":")
                        .trim()
                        .to_string();
                    spec_url = Some(url.clone());
                    if found_url.is_none() && !url.contains("localhost") {
                        found_url = Some(url.clone());
                    }
                    break;
                }
            }
        }
    }

    if let Some(url) = spec_url {
        resolution_steps.push(format!("   6. OpenAPI servers[0]: {} {}", "".green(), url));
    } else {
        resolution_steps.push(format!(
            "   6. OpenAPI servers[0]: {} Missing or empty",
            "".red()
        ));
    }

    // Print resolution steps
    for step in resolution_steps {
        println!("{}", step);
    }

    // Final result
    if let Some(url) = found_url {
        println!("\n   Will use: {}", url.bright_green());
        results.push(DiagnosticResult {
            category: "URL".to_string(),
            status: DiagnosticStatus::Ok,
            message: format!("Base URL resolved to: {}", url),
            fix_hint: None,
        });
    } else {
        results.push(DiagnosticResult {
            category: "URL".to_string(),
            status: DiagnosticStatus::Error,
            message: "No base URL could be resolved".to_string(),
            fix_hint: Some("Set API_BASE_URL env var or add to config/default.yaml".to_string()),
        });
    }

    Ok(results)
}

fn check_openapi_spec(project_path: &Path) -> Result<Vec<DiagnosticResult>> {
    let mut results = Vec::new();

    // Find spec file
    let spec_files = [
        "specs/api.yaml",
        "specs/api.json",
        "specs/openapi.yaml",
        "specs/openapi.json",
    ];
    let mut spec_found = false;

    for spec_file in &spec_files {
        let spec_path = project_path.join(spec_file);
        if spec_path.exists() {
            spec_found = true;

            // Basic validation
            if let Ok(content) = fs::read_to_string(&spec_path) {
                if content.contains("openapi:") || content.contains("\"openapi\"") {
                    results.push(DiagnosticResult {
                        category: "Spec".to_string(),
                        status: DiagnosticStatus::Ok,
                        message: format!("Valid OpenAPI spec found: {}", spec_file),
                        fix_hint: None,
                    });
                } else if content.contains("swagger:") || content.contains("\"swagger\"") {
                    results.push(DiagnosticResult {
                        category: "Spec".to_string(),
                        status: DiagnosticStatus::Ok,
                        message: format!("Valid Swagger spec found: {}", spec_file),
                        fix_hint: None,
                    });
                }
            }
            break;
        }
    }

    if !spec_found {
        results.push(DiagnosticResult {
            category: "Spec".to_string(),
            status: DiagnosticStatus::Error,
            message: "No OpenAPI/Swagger spec found".to_string(),
            fix_hint: Some("Run: mrapids init --from-url <openapi-url>".to_string()),
        });
    }

    Ok(results)
}

fn check_env_consistency(project_path: &Path, env_name: &str) -> Result<Vec<DiagnosticResult>> {
    let mut results = Vec::new();

    println!(
        "\n{} {} {}",
        "🔄".bright_green(),
        "Environment Variable Consistency".bold(),
        format!("[{}]", env_name).bright_blue()
    );

    // Load config file for the environment
    let config_file = project_path.join(format!("config/{}.yaml", env_name));
    let default_config = project_path.join("config/default.yaml");
    let env_file = project_path.join(format!("env/.env.{}", env_name));

    // Collect all variable references from config
    let mut config_vars = Vec::new();

    // Check environment-specific config
    if config_file.exists() {
        if let Ok(content) = fs::read_to_string(&config_file) {
            config_vars.extend(extract_env_vars(&content));
        }
    }

    // Check default config
    if default_config.exists() {
        if let Ok(content) = fs::read_to_string(&default_config) {
            config_vars.extend(extract_env_vars(&content));
        }
    }

    // Remove duplicates
    config_vars.sort();
    config_vars.dedup();

    if config_vars.is_empty() {
        results.push(DiagnosticResult {
            category: "EnvConsistency".to_string(),
            status: DiagnosticStatus::Ok,
            message: "No environment variables referenced in config".to_string(),
            fix_hint: None,
        });
        return Ok(results);
    }

    // Load environment variables from .env file
    let mut env_vars = HashMap::new();
    if env_file.exists() {
        if let Ok(content) = fs::read_to_string(&env_file) {
            for line in content.lines() {
                let line = line.trim();
                if !line.is_empty() && !line.starts_with('#') {
                    if let Some(eq_pos) = line.find('=') {
                        let key = line[..eq_pos].trim().to_string();
                        let value = line[eq_pos + 1..].trim().to_string();
                        env_vars.insert(key, value);
                    }
                }
            }
        }
    }

    // Also check currently loaded environment variables
    for var in &config_vars {
        if env::var(var).is_ok() && !env_vars.contains_key(var) {
            env_vars.insert(var.clone(), "<from environment>".to_string());
        }
    }

    // Check each config variable
    let mut missing_vars = Vec::new();
    let mut defined_vars = Vec::new();

    println!(
        "   Checking {} variables referenced in config:",
        config_vars.len()
    );

    for var in &config_vars {
        if env_vars.contains_key(var) {
            let value = &env_vars[var];
            let display_value = if value == "<from environment>" {
                value.to_string()
            } else if value.is_empty() {
                "<empty>".to_string()
            } else if value.len() > 20 {
                format!("{}...", &value[..20])
            } else {
                value.clone()
            };
            println!("   {} ${}: {}", "".green(), var, display_value.dimmed());
            defined_vars.push(var.clone());
        } else {
            println!("   {} ${}: {}", "".red(), var, "Not defined".red());
            missing_vars.push(var.clone());
        }
    }

    // Generate results
    if missing_vars.is_empty() {
        results.push(DiagnosticResult {
            category: "EnvConsistency".to_string(),
            status: DiagnosticStatus::Ok,
            message: format!("All {} config variables are defined", config_vars.len()),
            fix_hint: None,
        });
    } else {
        results.push(DiagnosticResult {
            category: "EnvConsistency".to_string(),
            status: DiagnosticStatus::Error,
            message: format!(
                "{} of {} config variables are missing",
                missing_vars.len(),
                config_vars.len()
            ),
            fix_hint: Some(format!(
                "Add to env/.env.{}: {}",
                env_name,
                missing_vars.join(", ")
            )),
        });
    }

    // Check for unused env variables (defined but not referenced)
    let unused_vars: Vec<String> = env_vars
        .keys()
        .filter(|k| !config_vars.contains(k) && *k != "<from environment>")
        .cloned()
        .collect();

    if !unused_vars.is_empty() {
        println!(
            "\n   {} Unused variables in env/.env.{}:",
            "⚠️".yellow(),
            env_name
        );
        for var in &unused_vars {
            println!("     - {}", var.yellow());
        }
        results.push(DiagnosticResult {
            category: "EnvConsistency".to_string(),
            status: DiagnosticStatus::Warning,
            message: format!("{} unused variables in .env file", unused_vars.len()),
            fix_hint: Some(format!("Consider removing: {}", unused_vars.join(", "))),
        });
    }

    Ok(results)
}

fn extract_env_vars(content: &str) -> Vec<String> {
    let mut vars = Vec::new();
    let re = regex::Regex::new(r"\$\{([A-Z_][A-Z0-9_]*)(:-[^}]*)?\}").unwrap();

    for cap in re.captures_iter(content) {
        if let Some(var_name) = cap.get(1) {
            vars.push(var_name.as_str().to_string());
        }
    }

    // Also check for $VAR_NAME format
    let re2 = regex::Regex::new(r"\$([A-Z_][A-Z0-9_]*)").unwrap();
    for cap in re2.captures_iter(content) {
        if let Some(var_name) = cap.get(1) {
            let var = var_name.as_str().to_string();
            // Avoid duplicates and avoid matching ${} style that we already caught
            if !content.contains(&format!("${{{}", var))
                && !content.contains(&format!("${{{}:", var))
            {
                vars.push(var);
            }
        }
    }

    vars
}

fn apply_fixes(project_path: &Path, results: &mut Vec<DiagnosticResult>) -> Result<()> {
    println!(
        "\n{} {}",
        "🔧".bright_yellow(),
        "Auto-fixing issues...".bold()
    );

    let mut fixed_count = 0;

    for result in results.iter_mut() {
        if result.status != DiagnosticStatus::Ok {
            match result.message.as_str() {
                "config/default.yaml missing" => {
                    // Create default config
                    let config_dir = project_path.join("config");
                    fs::create_dir_all(&config_dir)?;

                    let default_config = r#"# Default environment configuration
name: default
description: Default environment

# Set your API base URL
base_url: ${API_BASE_URL:-https://api.example.com}

# Common headers
headers:
  Accept: application/json
  User-Agent: MRapids/1.0
"#;
                    fs::write(config_dir.join("default.yaml"), default_config)?;

                    result.status = DiagnosticStatus::Ok;
                    result.message =
                        "Created config/default.yaml with extracted base URL".to_string();
                    fixed_count += 1;
                    println!("   {} Created config/default.yaml", "".green());
                }
                "No .env file found" => {
                    // Copy .env.example to .env
                    let env_example = project_path.join("config/.env.example");
                    let env_file = project_path.join(".env");

                    if env_example.exists() {
                        fs::copy(&env_example, &env_file)?;
                        result.status = DiagnosticStatus::Ok;
                        result.message = "Created .env from .env.example template".to_string();
                        fixed_count += 1;
                        println!("   {} Created .env from template", "".green());
                    }
                }
                _ => {}
            }
        }
    }

    if fixed_count > 0 {
        println!(
            "\nFixed {} of {} issues.",
            fixed_count,
            results
                .iter()
                .filter(|r| r.status != DiagnosticStatus::Ok)
                .count()
                + fixed_count
        );
    } else {
        println!("   No auto-fixable issues found.");
    }

    Ok(())
}

fn display_results(results: &[DiagnosticResult], cmd: &DoctorCommand) -> Result<()> {
    if cmd.format == "json" {
        // JSON output for CI/CD integration
        let json_results: Vec<HashMap<String, String>> = results
            .iter()
            .map(|r| {
                let mut map = HashMap::new();
                map.insert("category".to_string(), r.category.clone());
                map.insert("status".to_string(), format!("{:?}", r.status));
                map.insert("message".to_string(), r.message.clone());
                if let Some(fix) = &r.fix_hint {
                    map.insert("fix".to_string(), fix.clone());
                }
                map
            })
            .collect();

        println!("{}", serde_json::to_string_pretty(&json_results)?);
    } else {
        // Text output (already displayed inline)
        for result in results {
            if result.status != DiagnosticStatus::Ok {
                let icon = match result.status {
                    DiagnosticStatus::Warning => "⚠️".yellow(),
                    DiagnosticStatus::Error => "".red(),
                    _ => "".green(),
                };

                println!("   {} {}", icon, result.message);
                if let Some(fix) = &result.fix_hint {
                    println!("     {} {}", "".dimmed(), fix.bright_cyan());
                }
            }
        }
    }

    Ok(())
}

fn display_summary(results: &[DiagnosticResult], auto_fixed: bool) -> Result<()> {
    let errors = results
        .iter()
        .filter(|r| r.status == DiagnosticStatus::Error)
        .count();
    let warnings = results
        .iter()
        .filter(|r| r.status == DiagnosticStatus::Warning)
        .count();

    println!("\n{} {}", "📊".bright_cyan(), "Summary".bold());
    println!("   Issues found: {}", errors + warnings);
    println!("   Errors: {}", errors);
    println!("   Warnings: {}", warnings);

    if errors == 0 && warnings == 0 {
        println!("\n{} Everything configured correctly!", "".green());
    } else if !auto_fixed {
        println!("\n{} {}", "".yellow(), "Quick Fixes".bold());

        // Show numbered quick fixes
        let mut fix_num = 1;
        for result in results {
            if result.status != DiagnosticStatus::Ok {
                if let Some(fix) = &result.fix_hint {
                    println!("   {}. {}", fix_num, fix.bright_cyan());
                    fix_num += 1;
                }
            }
        }

        println!("\n   Run 'mrapids doctor --fix' to auto-fix issues where possible");
    }

    Ok(())
}

/// Check decision logging configuration
fn check_decision_logging() -> Vec<DiagnosticResult> {
    let mut results = Vec::new();

    // Check MRAPIDS_DECISION_LOG environment variable
    let decision_log_status = match env::var("MRAPIDS_DECISION_LOG") {
        Ok(val) if val == "true" || val == "1" => {
            let default_path = dirs::home_dir()
                .map(|h| h.join(".mrapids").join("decisions.jsonl"))
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| "~/.mrapids/decisions.jsonl".to_string());
            (
                DiagnosticStatus::Ok,
                format!("Enabled → {}", default_path),
                None,
            )
        }
        Ok(val) if !val.is_empty() => (DiagnosticStatus::Ok, format!("Enabled → {}", val), None),
        _ => (
            DiagnosticStatus::Ok,
            "Disabled (opt-in only)".to_string(),
            Some("Set MRAPIDS_DECISION_LOG=true or use --log-decisions flag".to_string()),
        ),
    };

    results.push(DiagnosticResult {
        category: "Decision Logging".to_string(),
        status: decision_log_status.0,
        message: decision_log_status.1,
        fix_hint: decision_log_status.2,
    });

    results
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // ============================================================================
    // DiagnosticStatus tests
    // ============================================================================

    #[test]
    fn test_diagnostic_status_equality() {
        assert_eq!(DiagnosticStatus::Ok, DiagnosticStatus::Ok);
        assert_eq!(DiagnosticStatus::Warning, DiagnosticStatus::Warning);
        assert_eq!(DiagnosticStatus::Error, DiagnosticStatus::Error);
        assert_ne!(DiagnosticStatus::Ok, DiagnosticStatus::Error);
    }

    // ============================================================================
    // DiagnosticResult tests
    // ============================================================================

    #[test]
    fn test_diagnostic_result_creation() {
        let result = DiagnosticResult {
            category: "Test".to_string(),
            status: DiagnosticStatus::Ok,
            message: "Test passed".to_string(),
            fix_hint: None,
        };
        assert_eq!(result.category, "Test");
        assert_eq!(result.status, DiagnosticStatus::Ok);
    }

    #[test]
    fn test_diagnostic_result_with_fix_hint() {
        let result = DiagnosticResult {
            category: "Config".to_string(),
            status: DiagnosticStatus::Error,
            message: "Missing config".to_string(),
            fix_hint: Some("Run mrapids init".to_string()),
        };
        assert!(result.fix_hint.is_some());
        assert_eq!(result.fix_hint.unwrap(), "Run mrapids init");
    }

    // ============================================================================
    // extract_env_vars tests
    // ============================================================================

    #[test]
    fn test_extract_env_vars_curly_brace() {
        let content = "base_url: ${API_BASE_URL}";
        let vars = extract_env_vars(content);
        assert!(vars.contains(&"API_BASE_URL".to_string()));
    }

    #[test]
    fn test_extract_env_vars_with_default() {
        let content = "base_url: ${API_BASE_URL:-https://api.example.com}";
        let vars = extract_env_vars(content);
        assert!(vars.contains(&"API_BASE_URL".to_string()));
    }

    #[test]
    fn test_extract_env_vars_multiple() {
        let content = r#"
base_url: ${API_BASE_URL}
headers:
  Authorization: Bearer ${API_TOKEN}
  X-API-Key: ${API_KEY}
"#;
        let vars = extract_env_vars(content);
        assert!(vars.contains(&"API_BASE_URL".to_string()));
        assert!(vars.contains(&"API_TOKEN".to_string()));
        assert!(vars.contains(&"API_KEY".to_string()));
    }

    #[test]
    fn test_extract_env_vars_dollar_sign() {
        let content = "token: $AUTH_TOKEN";
        let vars = extract_env_vars(content);
        assert!(vars.contains(&"AUTH_TOKEN".to_string()));
    }

    #[test]
    fn test_extract_env_vars_empty() {
        let content = "base_url: https://api.example.com";
        let vars = extract_env_vars(content);
        assert!(vars.is_empty());
    }

    // ============================================================================
    // check_project_structure tests
    // ============================================================================

    #[test]
    fn test_check_project_structure_missing_all() {
        let temp_dir = TempDir::new().unwrap();
        let results = check_project_structure(temp_dir.path()).unwrap();

        // Should have errors for missing mrapids.yaml and specs/
        let errors: Vec<_> = results
            .iter()
            .filter(|r| r.status == DiagnosticStatus::Error)
            .collect();
        assert!(!errors.is_empty());
    }

    #[test]
    fn test_check_project_structure_with_manifest() {
        let temp_dir = TempDir::new().unwrap();

        // Create mrapids.yaml
        let manifest = r#"
name: test-project
version: 1.0.0
default_spec: specs/api.yaml
default_env: development
"#;
        fs::write(temp_dir.path().join("mrapids.yaml"), manifest).unwrap();

        let results = check_project_structure(temp_dir.path()).unwrap();

        // Should have OK for manifest
        let manifest_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("mrapids.yaml"));
        assert!(manifest_ok);
    }

    #[test]
    fn test_check_project_structure_with_specs() {
        let temp_dir = TempDir::new().unwrap();

        // Create specs directory with api.yaml
        fs::create_dir_all(temp_dir.path().join("specs")).unwrap();
        fs::write(
            temp_dir.path().join("specs/api.yaml"),
            "openapi: 3.0.0\ninfo:\n  title: Test\n  version: 1.0.0\npaths: {}",
        )
        .unwrap();

        let results = check_project_structure(temp_dir.path()).unwrap();

        // Should have OK for specs
        let specs_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("specs/"));
        assert!(specs_ok);
    }

    #[test]
    fn test_check_project_structure_with_config() {
        let temp_dir = TempDir::new().unwrap();

        // Create config directory with files
        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/default.yaml"),
            "base_url: http://localhost",
        )
        .unwrap();
        fs::write(
            temp_dir.path().join("config/development.yaml"),
            "base_url: http://localhost",
        )
        .unwrap();

        let results = check_project_structure(temp_dir.path()).unwrap();

        // Should have OK for config
        let config_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("config/"));
        assert!(config_ok);
    }

    #[test]
    fn test_check_project_structure_with_env() {
        let temp_dir = TempDir::new().unwrap();

        // Create env directory with files
        fs::create_dir_all(temp_dir.path().join("env")).unwrap();
        fs::write(
            temp_dir.path().join("env/.env.development"),
            "API_TOKEN=test",
        )
        .unwrap();

        let results = check_project_structure(temp_dir.path()).unwrap();

        // Should have OK for env
        let env_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("env/"));
        assert!(env_ok);
    }

    // ============================================================================
    // check_configuration tests
    // ============================================================================

    #[test]
    fn test_check_configuration_missing_default() {
        let temp_dir = TempDir::new().unwrap();
        let results = check_configuration(temp_dir.path()).unwrap();

        let has_error = results.iter().any(|r| {
            r.status == DiagnosticStatus::Error && r.message.contains("default.yaml missing")
        });
        assert!(has_error);
    }

    #[test]
    fn test_check_configuration_with_base_url() {
        let temp_dir = TempDir::new().unwrap();

        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/default.yaml"),
            "base_url: https://api.example.com",
        )
        .unwrap();

        let results = check_configuration(temp_dir.path()).unwrap();

        let has_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("base_url"));
        assert!(has_ok);
    }

    #[test]
    fn test_check_configuration_missing_base_url() {
        let temp_dir = TempDir::new().unwrap();

        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/default.yaml"),
            "timeout: 30000",
        )
        .unwrap();

        let results = check_configuration(temp_dir.path()).unwrap();

        let has_warning = results.iter().any(|r| {
            r.status == DiagnosticStatus::Warning && r.message.contains("missing base_url")
        });
        assert!(has_warning);
    }

    // ============================================================================
    // check_openapi_spec tests
    // ============================================================================

    #[test]
    fn test_check_openapi_spec_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let results = check_openapi_spec(temp_dir.path()).unwrap();

        let has_error = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Error && r.message.contains("No OpenAPI"));
        assert!(has_error);
    }

    #[test]
    fn test_check_openapi_spec_valid_openapi() {
        let temp_dir = TempDir::new().unwrap();

        fs::create_dir_all(temp_dir.path().join("specs")).unwrap();
        fs::write(
            temp_dir.path().join("specs/api.yaml"),
            "openapi: 3.0.0\ninfo:\n  title: Test\n  version: 1.0.0",
        )
        .unwrap();

        let results = check_openapi_spec(temp_dir.path()).unwrap();

        let has_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("Valid OpenAPI"));
        assert!(has_ok);
    }

    #[test]
    fn test_check_openapi_spec_valid_swagger() {
        let temp_dir = TempDir::new().unwrap();

        fs::create_dir_all(temp_dir.path().join("specs")).unwrap();
        fs::write(
            temp_dir.path().join("specs/api.yaml"),
            "swagger: \"2.0\"\ninfo:\n  title: Test\n  version: 1.0.0",
        )
        .unwrap();

        let results = check_openapi_spec(temp_dir.path()).unwrap();

        let has_ok = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Ok && r.message.contains("Valid Swagger"));
        assert!(has_ok);
    }

    // ============================================================================
    // check_authentication tests
    // ============================================================================

    #[test]
    fn test_check_authentication_with_bearer_in_spec() {
        let temp_dir = TempDir::new().unwrap();

        fs::create_dir_all(temp_dir.path().join("specs")).unwrap();
        fs::write(
            temp_dir.path().join("specs/api.yaml"),
            r#"
openapi: 3.0.0
info:
  title: Test
  version: 1.0.0
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
"#,
        )
        .unwrap();

        let results = check_authentication(temp_dir.path(), "development").unwrap();

        let has_bearer = results.iter().any(|r| r.message.contains("Bearer Token"));
        assert!(has_bearer);
    }

    #[test]
    fn test_check_authentication_with_api_key_in_spec() {
        let temp_dir = TempDir::new().unwrap();

        fs::create_dir_all(temp_dir.path().join("specs")).unwrap();
        fs::write(
            temp_dir.path().join("specs/api.yaml"),
            r#"
openapi: 3.0.0
info:
  title: Test
  version: 1.0.0
components:
  securitySchemes:
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
"#,
        )
        .unwrap();

        let results = check_authentication(temp_dir.path(), "development").unwrap();

        let has_api_key = results.iter().any(|r| r.message.contains("API Key"));
        assert!(has_api_key);
    }

    // ============================================================================
    // check_env_consistency tests
    // ============================================================================

    #[test]
    fn test_check_env_consistency_no_vars() {
        let temp_dir = TempDir::new().unwrap();

        // Create config without env vars
        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/development.yaml"),
            "base_url: https://api.example.com",
        )
        .unwrap();

        let results = check_env_consistency(temp_dir.path(), "development").unwrap();

        let has_ok = results.iter().any(|r| {
            r.status == DiagnosticStatus::Ok && r.message.contains("No environment variables")
        });
        assert!(has_ok);
    }

    #[test]
    fn test_check_env_consistency_with_defined_vars() {
        let temp_dir = TempDir::new().unwrap();

        // Create config with env var
        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/development.yaml"),
            "base_url: ${API_URL}",
        )
        .unwrap();

        // Create env file with the var
        fs::create_dir_all(temp_dir.path().join("env")).unwrap();
        fs::write(
            temp_dir.path().join("env/.env.development"),
            "API_URL=https://api.example.com",
        )
        .unwrap();

        let results = check_env_consistency(temp_dir.path(), "development").unwrap();

        let has_ok = results.iter().any(|r| {
            r.status == DiagnosticStatus::Ok && r.message.contains("variables are defined")
        });
        assert!(has_ok);
    }

    #[test]
    fn test_check_env_consistency_with_missing_vars() {
        let temp_dir = TempDir::new().unwrap();

        // Create config with env var
        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/development.yaml"),
            "base_url: ${MISSING_VAR}",
        )
        .unwrap();

        // Create empty env file (no MISSING_VAR)
        fs::create_dir_all(temp_dir.path().join("env")).unwrap();
        fs::write(
            temp_dir.path().join("env/.env.development"),
            "OTHER_VAR=value",
        )
        .unwrap();

        let results = check_env_consistency(temp_dir.path(), "development").unwrap();

        let has_error = results
            .iter()
            .any(|r| r.status == DiagnosticStatus::Error && r.message.contains("missing"));
        assert!(has_error);
    }

    // ============================================================================
    // Full project diagnostic tests
    // ============================================================================

    #[test]
    fn test_full_project_all_ok() {
        let temp_dir = TempDir::new().unwrap();

        // Create complete project structure
        let manifest = r#"
name: test-project
version: 1.0.0
default_spec: specs/api.yaml
default_env: development
"#;
        fs::write(temp_dir.path().join("mrapids.yaml"), manifest).unwrap();

        fs::create_dir_all(temp_dir.path().join("specs")).unwrap();
        fs::write(
            temp_dir.path().join("specs/api.yaml"),
            "openapi: 3.0.0\ninfo:\n  title: Test\n  version: 1.0.0\npaths: {}",
        )
        .unwrap();

        fs::create_dir_all(temp_dir.path().join("config")).unwrap();
        fs::write(
            temp_dir.path().join("config/default.yaml"),
            "base_url: https://api.example.com",
        )
        .unwrap();
        fs::write(
            temp_dir.path().join("config/development.yaml"),
            "base_url: https://dev.api.example.com",
        )
        .unwrap();

        fs::create_dir_all(temp_dir.path().join("env")).unwrap();
        fs::write(
            temp_dir.path().join("env/.env.development"),
            "# Development env",
        )
        .unwrap();

        // Run all checks
        let mut all_results = Vec::new();
        all_results.extend(check_project_structure(temp_dir.path()).unwrap());
        all_results.extend(check_configuration(temp_dir.path()).unwrap());
        all_results.extend(check_openapi_spec(temp_dir.path()).unwrap());

        // Count errors
        let error_count = all_results
            .iter()
            .filter(|r| r.status == DiagnosticStatus::Error)
            .count();

        // Should have no errors for a complete project
        assert_eq!(
            error_count,
            0,
            "Expected no errors but found: {:?}",
            all_results
                .iter()
                .filter(|r| r.status == DiagnosticStatus::Error)
                .collect::<Vec<_>>()
        );
    }
}