tfmcp 0.1.9

Terraform Model Context Protocol Tool - A CLI tool to manage Terraform through MCP
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
//! Module Health Analyzer
//!
//! Implements whitebox analysis for Terraform modules based on software engineering principles.
//! Detects issues related to cohesion, coupling, and module structure.
//!
//! Reference: Infrastructure code requires whitebox understanding - detailed visibility
//! into internal structure is essential, unlike application code abstraction.

use crate::terraform::model::{
    CohesionAnalysis, CohesionType, CountUsageWarning, CouplingAnalysis, CouplingType,
    DependencyType, GuidelineCheckResult, IssueCategory, IssueSeverity, ModuleBoundary,
    ModuleDependency, ModuleHealthAnalysis, ModuleIssue, ModuleMetrics, ProposedModuleStructure,
    RefactoringSuggestion, RefactoringType, ResourceDependencyGraph, ResourceEdge, ResourceNode,
    ResourceTypeGroup, SecretDetection, TerraformAnalysis,
};
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::{HashMap, HashSet};

// Regex patterns for extended parsing
static DATA_SOURCE_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"data\s+"([^"]+)"\s+"([^"]+)""#).expect("Invalid data source regex"));

static MODULE_CALL_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"module\s+"([^"]+)"\s*\{"#).expect("Invalid module call regex"));

static LOCALS_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"locals\s*\{"#).expect("Invalid locals regex"));

static REFERENCE_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"(aws_[a-z_]+|azurerm_[a-z_]+|google_[a-z_]+|kubernetes_[a-z_]+)\.([a-z_0-9]+)"#)
        .expect("Invalid reference regex")
});

static DEPENDS_ON_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"depends_on\s*=\s*\[([^\]]+)\]"#).expect("Invalid depends_on regex"));

static COUNT_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"count\s*=\s*"#).expect("Invalid count regex"));

static FOR_EACH_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"for_each\s*=\s*"#).expect("Invalid for_each regex"));

static MODULE_SOURCE_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"source\s*=\s*"([^"]+)""#).expect("Invalid module source regex"));

// Regex patterns for Future Architect guideline checks
static ANY_TYPE_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"type\s*=\s*any\b"#).expect("Invalid any type regex"));

static COUNT_VALUE_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"resource\s+"([^"]+)"\s+"([^"]+)"\s*\{[^}]*count\s*=\s*([^\n]+)"#)
        .expect("Invalid count value regex")
});

static DEFAULT_TAGS_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"default_tags\s*\{"#).expect("Invalid default_tags regex"));

static LIFECYCLE_PREVENT_DESTROY_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"lifecycle\s*\{[^}]*prevent_destroy\s*=\s*true"#).expect("Invalid lifecycle regex")
});

// Secret detection patterns (based on common secret patterns)
static SECRET_PATTERNS: Lazy<Vec<(&'static str, Regex)>> = Lazy::new(|| {
    vec![
        (
            "AWS Access Key",
            Regex::new(r#"(?i)(aws_access_key_id|access_key)\s*=\s*"[A-Z0-9]{20}""#).unwrap(),
        ),
        (
            "AWS Secret Key",
            Regex::new(r#"(?i)(aws_secret_access_key|secret_key)\s*=\s*"[A-Za-z0-9/+=]{40}""#)
                .unwrap(),
        ),
        (
            "Generic API Key",
            Regex::new(r#"(?i)(api_key|apikey)\s*=\s*"[A-Za-z0-9_-]{20,}""#).unwrap(),
        ),
        (
            "Generic Secret",
            Regex::new(r#"(?i)(password|secret|token)\s*=\s*"[^"]{8,}""#).unwrap(),
        ),
        (
            "Private Key",
            Regex::new(r#"-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----"#).unwrap(),
        ),
    ]
});

// Critical resources that should have prevent_destroy
static CRITICAL_RESOURCE_TYPES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
    vec![
        "aws_db_instance",
        "aws_rds_cluster",
        "aws_s3_bucket",
        "aws_dynamodb_table",
        "aws_elasticsearch_domain",
        "aws_elasticache_cluster",
        "aws_kms_key",
        "google_sql_database_instance",
        "google_storage_bucket",
        "azurerm_sql_database",
        "azurerm_storage_account",
    ]
    .into_iter()
    .collect()
});

// Thresholds for health analysis
const MAX_RECOMMENDED_VARIABLES: usize = 20;
const WARNING_VARIABLES: usize = 30;
const CRITICAL_VARIABLES: usize = 50;
const MAX_RESOURCE_TYPES: usize = 5;
const MAX_HIERARCHY_DEPTH: usize = 2;
const MIN_DESCRIPTION_RATIO: f64 = 0.8;

/// Resource type categories for cohesion analysis
fn get_resource_category(resource_type: &str) -> &'static str {
    let type_lower = resource_type.to_lowercase();

    // AWS categories
    if type_lower.contains("vpc")
        || type_lower.contains("subnet")
        || type_lower.contains("route")
        || type_lower.contains("internet_gateway")
        || type_lower.contains("nat_gateway")
        || type_lower.contains("network_acl")
    {
        return "networking-core";
    }
    if type_lower.contains("security_group") {
        return "networking-security";
    }
    if type_lower.contains("vpn") || type_lower.contains("transit") {
        return "networking-connectivity";
    }
    if type_lower.contains("flow_log") {
        return "networking-monitoring";
    }
    if type_lower.contains("lb")
        || type_lower.contains("load_balancer")
        || type_lower.contains("target_group")
        || type_lower.contains("listener")
    {
        return "load-balancing";
    }
    if type_lower.contains("instance")
        || type_lower.contains("launch_template")
        || type_lower.contains("autoscaling")
    {
        return "compute";
    }
    if type_lower.contains("rds")
        || type_lower.contains("db_")
        || type_lower.contains("dynamodb")
        || type_lower.contains("elasticache")
    {
        return "database";
    }
    if type_lower.contains("s3") || type_lower.contains("bucket") {
        return "storage";
    }
    if type_lower.contains("iam")
        || type_lower.contains("role")
        || type_lower.contains("policy")
        || type_lower.contains("kms")
    {
        return "security";
    }
    if type_lower.contains("lambda") || type_lower.contains("function") {
        return "serverless";
    }
    if type_lower.contains("eks")
        || type_lower.contains("ecs")
        || type_lower.contains("kubernetes")
        || type_lower.contains("container")
    {
        return "containers";
    }
    if type_lower.contains("cloudwatch")
        || type_lower.contains("log_group")
        || type_lower.contains("alarm")
        || type_lower.contains("metric")
    {
        return "monitoring";
    }
    if type_lower.contains("sns")
        || type_lower.contains("sqs")
        || type_lower.contains("eventbridge")
    {
        return "messaging";
    }
    if type_lower.contains("route53")
        || type_lower.contains("dns")
        || type_lower.contains("hosted_zone")
    {
        return "dns";
    }
    if type_lower.contains("acm") || type_lower.contains("certificate") {
        return "certificates";
    }
    if type_lower.contains("cloudfront") || type_lower.contains("cdn") {
        return "cdn";
    }
    if type_lower.contains("api_gateway") || type_lower.contains("apigateway") {
        return "api";
    }

    // Azure categories
    if type_lower.contains("azurerm_virtual_network")
        || type_lower.contains("azurerm_subnet")
        || type_lower.contains("azurerm_network")
    {
        return "networking-core";
    }
    if type_lower.contains("azurerm_vm") || type_lower.contains("azurerm_virtual_machine") {
        return "compute";
    }

    // GCP categories
    if type_lower.contains("google_compute_network")
        || type_lower.contains("google_compute_subnetwork")
    {
        return "networking-core";
    }
    if type_lower.contains("google_compute_instance") {
        return "compute";
    }

    "other"
}

/// Analyze module health
pub fn analyze_module_health(
    analysis: &TerraformAnalysis,
    file_contents: &HashMap<String, String>,
) -> ModuleHealthAnalysis {
    let metrics = calculate_metrics(analysis, file_contents);
    let cohesion = analyze_cohesion(analysis);
    let coupling = analyze_coupling(analysis, file_contents);
    let issues = detect_issues(analysis, &metrics, &cohesion, &coupling, file_contents);
    let recommendations = generate_recommendations(&issues, &metrics, &cohesion);
    let health_score = calculate_health_score(&metrics, &cohesion, &coupling, &issues);

    ModuleHealthAnalysis {
        module_path: analysis.project_directory.clone(),
        metrics,
        health_score,
        issues,
        recommendations,
        cohesion_analysis: cohesion,
        coupling_analysis: coupling,
    }
}

/// Calculate module metrics
fn calculate_metrics(
    analysis: &TerraformAnalysis,
    file_contents: &HashMap<String, String>,
) -> ModuleMetrics {
    let resource_types: HashSet<_> = analysis
        .resources
        .iter()
        .map(|r| r.resource_type.clone())
        .collect();

    let mut data_source_count = 0;
    let mut local_count = 0;
    let mut module_call_count = 0;
    let mut lines_of_code = 0;
    let mut hierarchy_depth = 0;

    for content in file_contents.values() {
        data_source_count += DATA_SOURCE_REGEX.captures_iter(content).count();
        local_count += LOCALS_REGEX.captures_iter(content).count();
        module_call_count += MODULE_CALL_REGEX.captures_iter(content).count();
        lines_of_code += content.lines().count();

        // Check for nested modules
        for cap in MODULE_SOURCE_REGEX.captures_iter(content) {
            let source = &cap[1];
            if source.starts_with("./") || source.starts_with("../") {
                let depth = source.matches('/').count();
                hierarchy_depth = hierarchy_depth.max(depth);
            }
        }
    }

    let variables_with_defaults = analysis
        .variables
        .iter()
        .filter(|v| v.default.is_some())
        .count();

    let variables_without_description = analysis
        .variables
        .iter()
        .filter(|v| {
            v.description.is_none()
                || v.description
                    .as_ref()
                    .map(|d| d.is_empty())
                    .unwrap_or(false)
        })
        .count();

    ModuleMetrics {
        variable_count: analysis.variables.len(),
        output_count: analysis.outputs.len(),
        resource_count: analysis.resources.len(),
        resource_type_count: resource_types.len(),
        provider_count: analysis.providers.len(),
        data_source_count,
        local_count,
        module_call_count,
        file_count: analysis.file_count,
        lines_of_code,
        hierarchy_depth,
        variables_with_defaults,
        variables_without_description,
    }
}

/// Analyze module cohesion
fn analyze_cohesion(analysis: &TerraformAnalysis) -> CohesionAnalysis {
    // Group resources by category
    let mut category_counts: HashMap<&str, Vec<String>> = HashMap::new();

    for resource in &analysis.resources {
        let category = get_resource_category(&resource.resource_type);
        category_counts
            .entry(category)
            .or_default()
            .push(resource.resource_type.clone());
    }

    let resource_type_groups: Vec<ResourceTypeGroup> = category_counts
        .into_iter()
        .map(|(name, types)| {
            let unique_types: HashSet<_> = types.iter().cloned().collect();
            ResourceTypeGroup {
                name: name.to_string(),
                resource_types: unique_types.into_iter().collect(),
                resource_count: types.len(),
            }
        })
        .collect();

    let num_categories = resource_type_groups.len();
    let total_resources = analysis.resources.len();

    // Determine cohesion type based on resource distribution
    let (cohesion_type, score, explanation) = if num_categories == 0 {
        (
            CohesionType::Functional,
            100,
            "Empty module or no resources analyzed".to_string(),
        )
    } else if num_categories == 1 {
        (
            CohesionType::Functional,
            95,
            format!(
                "Excellent cohesion: All {} resources belong to '{}' category",
                total_resources, resource_type_groups[0].name
            ),
        )
    } else if num_categories == 2 {
        // Check if the categories are related
        let categories: Vec<_> = resource_type_groups
            .iter()
            .map(|g| g.name.as_str())
            .collect();
        if are_categories_related(&categories) {
            (
                CohesionType::Sequential,
                85,
                format!(
                    "Good cohesion: {} categories ({}) are functionally related",
                    num_categories,
                    categories.join(", ")
                ),
            )
        } else {
            (
                CohesionType::Communicational,
                70,
                format!(
                    "Moderate cohesion: {} categories ({}) - consider if they should be separate modules",
                    num_categories,
                    categories.join(", ")
                ),
            )
        }
    } else if num_categories <= 4 {
        (
            CohesionType::Logical,
            50,
            format!(
                "Weak cohesion: {} different resource categories. Resources are grouped by type rather than function. Consider splitting into focused modules.",
                num_categories
            ),
        )
    } else {
        (
            CohesionType::Coincidental,
            25,
            format!(
                "Poor cohesion: {} different resource categories mixed together. This 'kitchen sink' module should be split.",
                num_categories
            ),
        )
    };

    CohesionAnalysis {
        cohesion_type,
        score,
        resource_type_groups,
        explanation,
    }
}

/// Check if resource categories are functionally related
fn are_categories_related(categories: &[&str]) -> bool {
    let related_pairs = [
        ("networking-core", "networking-security"),
        ("compute", "load-balancing"),
        ("database", "storage"),
        ("containers", "load-balancing"),
        ("serverless", "api"),
        ("monitoring", "logging"),
    ];

    if categories.len() != 2 {
        return false;
    }

    for (a, b) in &related_pairs {
        if (categories[0] == *a && categories[1] == *b)
            || (categories[0] == *b && categories[1] == *a)
        {
            return true;
        }
    }
    false
}

/// Analyze module coupling
fn analyze_coupling(
    analysis: &TerraformAnalysis,
    file_contents: &HashMap<String, String>,
) -> CouplingAnalysis {
    let mut dependencies = Vec::new();
    let mut control_coupling_count = 0;
    let mut module_sources: Vec<String> = Vec::new();

    for content in file_contents.values() {
        // Count control coupling (count/for_each based on variables)
        control_coupling_count += COUNT_REGEX.captures_iter(content).count();
        control_coupling_count += FOR_EACH_REGEX.captures_iter(content).count();

        // Extract module sources
        for cap in MODULE_SOURCE_REGEX.captures_iter(content) {
            module_sources.push(cap[1].to_string());
        }
    }

    // Analyze module dependencies
    for source in &module_sources {
        let dep_type = if source.starts_with("registry.terraform.io")
            || source.starts_with("terraform-")
            || source.contains("/") && !source.starts_with("./") && !source.starts_with("../")
        {
            "public-registry"
        } else if source.starts_with("./") || source.starts_with("../") {
            "local"
        } else {
            "other"
        };

        dependencies.push(ModuleDependency {
            source_module: analysis.project_directory.clone(),
            target_module: source.clone(),
            dependency_type: dep_type.to_string(),
            variables_passed: Vec::new(),
        });
    }

    // Determine coupling type
    let variable_ratio = if analysis.resources.is_empty() {
        0.0
    } else {
        analysis.variables.len() as f64 / analysis.resources.len() as f64
    };

    let (coupling_type, score, explanation) = if control_coupling_count > 10 || variable_ratio > 5.0
    {
        (
            CouplingType::Control,
            75,
            format!(
                "High control coupling: {} conditional constructs, {:.1} variables per resource. The module's behavior is heavily parameterized.",
                control_coupling_count, variable_ratio
            ),
        )
    } else if analysis.variables.len() > MAX_RECOMMENDED_VARIABLES {
        (
            CouplingType::Stamp,
            60,
            format!(
                "Moderate coupling: {} variables expose internal structure. Consider grouping related variables into objects.",
                analysis.variables.len()
            ),
        )
    } else if control_coupling_count > 5 {
        (
            CouplingType::Stamp,
            50,
            format!(
                "Moderate coupling: {} conditional constructs. Review if all conditions are necessary.",
                control_coupling_count
            ),
        )
    } else {
        (
            CouplingType::Data,
            30,
            "Low coupling: Module has clean interfaces with minimal control flow dependencies."
                .to_string(),
        )
    };

    CouplingAnalysis {
        coupling_type,
        score,
        dependencies,
        explanation,
    }
}

/// Detect issues in the module
fn detect_issues(
    _analysis: &TerraformAnalysis,
    metrics: &ModuleMetrics,
    cohesion: &CohesionAnalysis,
    coupling: &CouplingAnalysis,
    file_contents: &HashMap<String, String>,
) -> Vec<ModuleIssue> {
    let mut issues = Vec::new();

    // Check variable count
    if metrics.variable_count >= CRITICAL_VARIABLES {
        issues.push(ModuleIssue {
            severity: IssueSeverity::Critical,
            category: IssueCategory::ExcessiveVariables,
            message: format!(
                "Critical: {} variables exposed (threshold: {}). This indicates internal model exposure (モデル結合). Consider reducing interface surface.",
                metrics.variable_count, CRITICAL_VARIABLES
            ),
            file: None,
            line: None,
        });
    } else if metrics.variable_count >= WARNING_VARIABLES {
        issues.push(ModuleIssue {
            severity: IssueSeverity::Warning,
            category: IssueCategory::ExcessiveVariables,
            message: format!(
                "Warning: {} variables exposed (recommended: <{}). Review if all variables are necessary.",
                metrics.variable_count, MAX_RECOMMENDED_VARIABLES
            ),
            file: None,
            line: None,
        });
    }

    // Check resource type diversity (logical cohesion)
    if metrics.resource_type_count > MAX_RESOURCE_TYPES {
        issues.push(ModuleIssue {
            severity: IssueSeverity::Warning,
            category: IssueCategory::LogicalCohesion,
            message: format!(
                "Logical cohesion detected: {} different resource types in one module. This 'まとめすぎ' pattern reduces maintainability. Consider splitting by function.",
                metrics.resource_type_count
            ),
            file: None,
            line: None,
        });
    }

    // Check hierarchy depth
    if metrics.hierarchy_depth > MAX_HIERARCHY_DEPTH {
        issues.push(ModuleIssue {
            severity: IssueSeverity::Warning,
            category: IssueCategory::DeepHierarchy,
            message: format!(
                "Deep module hierarchy: {} levels (recommended: ≤{}). Deep nesting reduces visibility and makes debugging harder (多段構成).",
                metrics.hierarchy_depth, MAX_HIERARCHY_DEPTH
            ),
            file: None,
            line: None,
        });
    }

    // Check documentation
    let description_ratio = if metrics.variable_count > 0 {
        (metrics.variable_count - metrics.variables_without_description) as f64
            / metrics.variable_count as f64
    } else {
        1.0
    };

    if description_ratio < MIN_DESCRIPTION_RATIO {
        issues.push(ModuleIssue {
            severity: IssueSeverity::Info,
            category: IssueCategory::MissingDocumentation,
            message: format!(
                "{} of {} variables lack descriptions ({:.0}% documented). Documentation is essential for whitebox usage.",
                metrics.variables_without_description,
                metrics.variable_count,
                description_ratio * 100.0
            ),
            file: None,
            line: None,
        });
    }

    // Check for public module usage
    for dep in &coupling.dependencies {
        if dep.dependency_type == "public-registry" {
            issues.push(ModuleIssue {
                severity: IssueSeverity::Warning,
                category: IssueCategory::PublicModuleRisk,
                message: format!(
                    "Public module detected: '{}'. Public modules often have excessive variables and logical cohesion. Consider creating an organization-specific wrapper.",
                    dep.target_module
                ),
                file: None,
                line: None,
            });
        }
    }

    // Check for control coupling patterns
    for (filename, content) in file_contents {
        let count_occurrences = COUNT_REGEX.captures_iter(content).count();
        let for_each_occurrences = FOR_EACH_REGEX.captures_iter(content).count();

        if count_occurrences + for_each_occurrences > 5 {
            issues.push(ModuleIssue {
                severity: IssueSeverity::Info,
                category: IssueCategory::ControlCoupling,
                message: format!(
                    "High conditional complexity in '{}': {} count/for_each patterns. This may indicate control coupling (制御結合).",
                    filename,
                    count_occurrences + for_each_occurrences
                ),
                file: Some(filename.clone()),
                line: None,
            });
        }
    }

    // Check naming conventions
    for filename in file_contents.keys() {
        if filename == "main.tf" && metrics.resource_count > 5 {
            issues.push(ModuleIssue {
                severity: IssueSeverity::Info,
                category: IssueCategory::NamingConvention,
                message: "Consider renaming 'main.tf' to reflect its actual purpose (e.g., 'vpc.tf', 'compute.tf'). 'main.tf' doesn't convey what resources it contains.".to_string(),
                file: Some(filename.clone()),
                line: None,
            });
        }
    }

    // Cohesion-based issues
    if cohesion.score < 50 {
        issues.push(ModuleIssue {
            severity: IssueSeverity::Warning,
            category: IssueCategory::LogicalCohesion,
            message: cohesion.explanation.clone(),
            file: None,
            line: None,
        });
    }

    issues
}

/// Generate recommendations based on detected issues
fn generate_recommendations(
    issues: &[ModuleIssue],
    metrics: &ModuleMetrics,
    cohesion: &CohesionAnalysis,
) -> Vec<String> {
    let mut recommendations = Vec::new();

    // Variable reduction recommendations
    if metrics.variable_count > MAX_RECOMMENDED_VARIABLES {
        recommendations.push(format!(
            "🔧 Reduce variable exposure: Group related variables into objects, use locals for derived values, and set sensible defaults. Target: ≤{} variables.",
            MAX_RECOMMENDED_VARIABLES
        ));
    }

    // Cohesion recommendations
    if cohesion.resource_type_groups.len() > 3 {
        let groups: Vec<_> = cohesion
            .resource_type_groups
            .iter()
            .map(|g| g.name.as_str())
            .collect();
        recommendations.push(format!(
            "🔧 Split module by function: Current categories ({}). Create separate modules for each distinct function.",
            groups.join(", ")
        ));
    }

    // Documentation recommendations
    if metrics.variables_without_description > 0 {
        recommendations.push(format!(
            "📝 Add descriptions to {} variables. Use terraform-docs to generate documentation automatically.",
            metrics.variables_without_description
        ));
    }

    // Hierarchy recommendations
    if metrics.hierarchy_depth > MAX_HIERARCHY_DEPTH {
        recommendations.push(
            "🏗️ Flatten module hierarchy: Prefer composition over deep nesting. Consider using module composition patterns instead of deep hierarchies.".to_string()
        );
    }

    // Public module recommendations
    let public_module_issues = issues
        .iter()
        .filter(|i| matches!(i.category, IssueCategory::PublicModuleRisk))
        .count();
    if public_module_issues > 0 {
        recommendations.push(
            "⚠️ Create organization wrappers for public modules: Public modules expose too many options. Create thin wrappers that expose only the options your organization needs.".to_string()
        );
    }

    // General best practices
    if issues.is_empty() {
        recommendations.push(
            "✅ Module structure looks healthy! Continue following current patterns.".to_string(),
        );
    }

    recommendations
}

/// Calculate overall health score
fn calculate_health_score(
    metrics: &ModuleMetrics,
    cohesion: &CohesionAnalysis,
    coupling: &CouplingAnalysis,
    issues: &[ModuleIssue],
) -> u8 {
    let mut score: i32 = 100;

    // Deduct for variable count
    if metrics.variable_count > CRITICAL_VARIABLES {
        score -= 30;
    } else if metrics.variable_count > WARNING_VARIABLES {
        score -= 15;
    } else if metrics.variable_count > MAX_RECOMMENDED_VARIABLES {
        score -= 5;
    }

    // Deduct for cohesion issues
    score -= ((100 - cohesion.score as i32) / 3).min(25);

    // Deduct for coupling issues
    score -= (coupling.score as i32 / 4).min(20);

    // Deduct for issues
    for issue in issues {
        match issue.severity {
            IssueSeverity::Critical => score -= 15,
            IssueSeverity::Warning => score -= 5,
            IssueSeverity::Info => score -= 1,
        }
    }

    // Deduct for hierarchy depth
    if metrics.hierarchy_depth > MAX_HIERARCHY_DEPTH {
        score -= 10;
    }

    // Ensure score is within bounds
    score.clamp(0, 100) as u8
}

/// Build resource dependency graph
pub fn build_dependency_graph(
    analysis: &TerraformAnalysis,
    file_contents: &HashMap<String, String>,
) -> ResourceDependencyGraph {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();

    // Build resource lookup map
    let mut resource_map: HashMap<String, usize> = HashMap::new();

    // Create nodes for each resource
    for resource in &analysis.resources {
        let id = format!("{}.{}", resource.resource_type, resource.name);
        resource_map.insert(id.clone(), nodes.len());

        nodes.push(ResourceNode {
            id: id.clone(),
            resource_type: resource.resource_type.clone(),
            resource_name: resource.name.clone(),
            module_path: analysis.project_directory.clone(),
            file: resource.file.clone(),
            provider: resource.provider.clone(),
        });
    }

    // Find dependencies by scanning file contents
    for (filename, content) in file_contents {
        // Find explicit depends_on
        for cap in DEPENDS_ON_REGEX.captures_iter(content) {
            let deps_str = &cap[1];
            for dep in deps_str.split(',') {
                let dep_trimmed = dep.trim().trim_matches(|c| c == '[' || c == ']');
                if resource_map.contains_key(dep_trimmed) {
                    // Find which resource this depends_on belongs to
                    // This is simplified - in practice we'd need more context
                    for node in &nodes {
                        if content.contains(&format!("resource \"{}\"", node.resource_type)) {
                            edges.push(ResourceEdge {
                                source: node.id.clone(),
                                target: dep_trimmed.to_string(),
                                dependency_type: DependencyType::Explicit,
                                attribute: Some("depends_on".to_string()),
                            });
                            break;
                        }
                    }
                }
            }
        }

        // Find implicit references
        for cap in REFERENCE_REGEX.captures_iter(content) {
            let ref_type = &cap[1];
            let ref_name = &cap[2];
            let ref_id = format!("{}.{}", ref_type, ref_name);

            if resource_map.contains_key(&ref_id) {
                // Find the resource that contains this reference
                for resource in &analysis.resources {
                    if resource.file == *filename {
                        let source_id = format!("{}.{}", resource.resource_type, resource.name);
                        if source_id != ref_id {
                            // Avoid duplicate edges
                            let edge_exists = edges.iter().any(|e| {
                                e.source == source_id
                                    && e.target == ref_id
                                    && matches!(e.dependency_type, DependencyType::Implicit)
                            });

                            if !edge_exists {
                                edges.push(ResourceEdge {
                                    source: source_id,
                                    target: ref_id.clone(),
                                    dependency_type: DependencyType::Implicit,
                                    attribute: None,
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    // Create module boundary
    let module_boundaries = vec![ModuleBoundary {
        module_path: analysis.project_directory.clone(),
        resource_ids: nodes.iter().map(|n| n.id.clone()).collect(),
    }];

    ResourceDependencyGraph {
        nodes,
        edges,
        module_boundaries,
    }
}

/// Generate refactoring suggestions
pub fn suggest_refactoring(
    analysis: &TerraformAnalysis,
    health: &ModuleHealthAnalysis,
) -> Vec<RefactoringSuggestion> {
    let mut suggestions = Vec::new();

    // Suggest splitting if too many resource types
    if health.cohesion_analysis.resource_type_groups.len() > 2 {
        for group in &health.cohesion_analysis.resource_type_groups {
            if group.resource_count >= 2 {
                let affected_resources: Vec<String> = analysis
                    .resources
                    .iter()
                    .filter(|r| group.resource_types.contains(&r.resource_type))
                    .map(|r| format!("{}.{}", r.resource_type, r.name))
                    .collect();

                if !affected_resources.is_empty() {
                    suggestions.push(RefactoringSuggestion {
                        suggestion_type: RefactoringType::ExtractSubmodule,
                        priority: IssueSeverity::Warning,
                        description: format!(
                            "Extract '{}' resources into a dedicated module",
                            group.name
                        ),
                        affected_resources: affected_resources.clone(),
                        proposed_structure: Some(ProposedModuleStructure {
                            module_name: format!("modules/{}", group.name.replace('-', "_")),
                            resources: affected_resources,
                            variables: Vec::new(),
                            outputs: Vec::new(),
                        }),
                        migration_steps: vec![
                            format!("1. Create new module directory: modules/{}", group.name),
                            "2. Move related resources to new module".to_string(),
                            "3. Create variables.tf for required inputs".to_string(),
                            "4. Create outputs.tf for values needed by other resources".to_string(),
                            "5. Add 'moved' blocks to preserve state".to_string(),
                            "6. Run terraform plan to verify no changes".to_string(),
                        ],
                    });
                }
            }
        }
    }

    // Suggest wrapping public modules
    for dep in &health.coupling_analysis.dependencies {
        if dep.dependency_type == "public-registry" {
            suggestions.push(RefactoringSuggestion {
                suggestion_type: RefactoringType::WrapPublicModule,
                priority: IssueSeverity::Warning,
                description: format!(
                    "Create organization wrapper for public module: {}",
                    dep.target_module
                ),
                affected_resources: vec![dep.target_module.clone()],
                proposed_structure: Some(ProposedModuleStructure {
                    module_name: format!(
                        "modules/{}",
                        dep.target_module
                            .split('/')
                            .next_back()
                            .unwrap_or("wrapper")
                    ),
                    resources: Vec::new(),
                    variables: vec!["# Expose only necessary variables".to_string()],
                    outputs: vec!["# Forward only needed outputs".to_string()],
                }),
                migration_steps: vec![
                    "1. Create wrapper module directory".to_string(),
                    "2. Define minimal variable interface".to_string(),
                    "3. Call public module with organization defaults".to_string(),
                    "4. Forward only necessary outputs".to_string(),
                    "5. Update callers to use wrapper module".to_string(),
                ],
            });
        }
    }

    // Suggest adding descriptions
    if health.metrics.variables_without_description > 0 {
        let vars_needing_desc: Vec<String> = analysis
            .variables
            .iter()
            .filter(|v| {
                v.description.is_none()
                    || v.description
                        .as_ref()
                        .map(|d| d.is_empty())
                        .unwrap_or(false)
            })
            .map(|v| v.name.clone())
            .collect();

        suggestions.push(RefactoringSuggestion {
            suggestion_type: RefactoringType::AddDescriptions,
            priority: IssueSeverity::Info,
            description: format!(
                "Add descriptions to {} undocumented variables",
                vars_needing_desc.len()
            ),
            affected_resources: vars_needing_desc,
            proposed_structure: None,
            migration_steps: vec![
                "1. Review each variable's purpose".to_string(),
                "2. Add description field with clear explanation".to_string(),
                "3. Include example values where helpful".to_string(),
                "4. Run terraform-docs to generate documentation".to_string(),
            ],
        });
    }

    // Suggest flattening hierarchy
    if health.metrics.hierarchy_depth > MAX_HIERARCHY_DEPTH {
        suggestions.push(RefactoringSuggestion {
            suggestion_type: RefactoringType::FlattenHierarchy,
            priority: IssueSeverity::Warning,
            description: format!(
                "Reduce module hierarchy from {} levels to ≤{}",
                health.metrics.hierarchy_depth, MAX_HIERARCHY_DEPTH
            ),
            affected_resources: Vec::new(),
            proposed_structure: None,
            migration_steps: vec![
                "1. Identify deeply nested modules".to_string(),
                "2. Consider inlining small modules".to_string(),
                "3. Use module composition instead of nesting".to_string(),
                "4. Maintain visibility of resource details".to_string(),
            ],
        });
    }

    suggestions
}

// ==================== Future Architect Guideline Checks ====================

/// Check Terraform configurations against Future Architect guidelines
/// Reference: https://future-architect.github.io/coding-standards/documents/forTerraform/
pub fn check_guidelines(
    analysis: &TerraformAnalysis,
    file_contents: &HashMap<String, String>,
) -> GuidelineCheckResult {
    let mut result = GuidelineCheckResult::default();

    // Check variables missing type
    for var in &analysis.variables {
        if var.type_.is_none() {
            result.variables_missing_type.push(var.name.clone());
        }
    }

    // Check variables missing description
    for var in &analysis.variables {
        if var.description.is_none()
            || var
                .description
                .as_ref()
                .is_some_and(|d| d.trim().is_empty())
        {
            result.variables_missing_description.push(var.name.clone());
        }
    }

    // Check outputs missing description
    for output in &analysis.outputs {
        if output.description.is_none()
            || output
                .description
                .as_ref()
                .is_some_and(|d| d.trim().is_empty())
        {
            result.outputs_missing_description.push(output.name.clone());
        }
    }

    // Check providers missing version
    for provider in &analysis.providers {
        if provider.version.is_none() {
            result.providers_missing_version.push(provider.name.clone());
        }
    }

    // Check file contents for patterns
    let mut has_aws_provider = false;
    let mut has_default_tags = false;
    let mut resources_with_lifecycle: HashSet<String> = HashSet::new();

    for (filename, content) in file_contents {
        // Check for AWS provider
        if content.contains("provider \"aws\"") || content.contains("aws_") {
            has_aws_provider = true;
        }

        // Check for default_tags
        if DEFAULT_TAGS_REGEX.is_match(content) {
            has_default_tags = true;
        }

        // Check for any type usage
        if ANY_TYPE_REGEX.is_match(content) {
            // Find variable names using any type
            for line in content.lines() {
                if line.contains("type") && line.contains("any") {
                    // Try to find the variable name
                    if let Some(start) = content.find("variable \"") {
                        if let Some(end) = content[start + 10..].find('"') {
                            let var_name = &content[start + 10..start + 10 + end];
                            if !result.any_type_usage.contains(&var_name.to_string()) {
                                result.any_type_usage.push(var_name.to_string());
                            }
                        }
                    }
                }
            }
        }

        // Check for count usage that should be for_each
        check_count_usage(content, filename, &mut result.count_instead_of_foreach);

        // Check for hardcoded secrets
        check_secrets(content, filename, &mut result.hardcoded_secrets);

        // Check for lifecycle prevent_destroy
        if LIFECYCLE_PREVENT_DESTROY_REGEX.is_match(content) {
            for resource in &analysis.resources {
                if content.contains(&format!(
                    "resource \"{}\" \"{}\"",
                    resource.resource_type, resource.name
                )) {
                    resources_with_lifecycle
                        .insert(format!("{}.{}", resource.resource_type, resource.name));
                }
            }
        }
    }

    // Set missing_default_tags for AWS projects
    result.missing_default_tags = has_aws_provider && !has_default_tags;

    // Check for critical resources missing lifecycle protection
    for resource in &analysis.resources {
        if CRITICAL_RESOURCE_TYPES.contains(resource.resource_type.as_str()) {
            let resource_id = format!("{}.{}", resource.resource_type, resource.name);
            if !resources_with_lifecycle.contains(&resource_id) {
                result.missing_lifecycle_protection.push(resource_id);
            }
        }
    }

    // Calculate compliance score
    result.compliance_score = calculate_compliance_score(&result, analysis);

    result
}

/// Check for count usage that should be for_each
fn check_count_usage(content: &str, filename: &str, warnings: &mut Vec<CountUsageWarning>) {
    // Simple heuristic: if count is used with a variable or expression that isn't 0 or 1,
    // it might be better as for_each
    for cap in COUNT_VALUE_REGEX.captures_iter(content) {
        let resource_type = cap.get(1).map(|m| m.as_str()).unwrap_or("");
        let resource_name = cap.get(2).map(|m| m.as_str()).unwrap_or("");
        let count_value = cap.get(3).map(|m| m.as_str()).unwrap_or("").trim();

        // Skip if count is used for 0/1 toggle (conditional creation)
        let is_toggle = count_value == "0"
            || count_value == "1"
            || count_value.contains("? 1 : 0")
            || count_value.contains("? 0 : 1")
            || count_value.starts_with("var.enable_")
            || count_value.starts_with("var.create_")
            || count_value.starts_with("local.enable_")
            || count_value.starts_with("local.create_");

        if !is_toggle {
            warnings.push(CountUsageWarning {
                resource_name: format!("{}.{}", resource_type, resource_name),
                resource_type: resource_type.to_string(),
                suggestion: format!(
                    "Consider using for_each instead of count in {} (file: {}). \
                     for_each provides stable resource addresses when items are added/removed.",
                    resource_name, filename
                ),
            });
        }
    }
}

/// Check for hardcoded secrets in content
fn check_secrets(content: &str, filename: &str, detections: &mut Vec<SecretDetection>) {
    for (line_num, line) in content.lines().enumerate() {
        // Skip comments
        let trimmed = line.trim();
        if trimmed.starts_with('#') || trimmed.starts_with("//") {
            continue;
        }

        for (pattern_name, regex) in SECRET_PATTERNS.iter() {
            if regex.is_match(line) {
                detections.push(SecretDetection {
                    file: filename.to_string(),
                    line: line_num + 1,
                    pattern: pattern_name.to_string(),
                    severity: if *pattern_name == "Private Key" || pattern_name.contains("Secret") {
                        "critical".to_string()
                    } else {
                        "high".to_string()
                    },
                });
            }
        }
    }
}

/// Calculate compliance score based on guideline violations
fn calculate_compliance_score(result: &GuidelineCheckResult, analysis: &TerraformAnalysis) -> u8 {
    let mut score: i32 = 100;

    // Variables missing type: -3 points each, max -15
    let type_penalty = (result.variables_missing_type.len() as i32 * 3).min(15);
    score -= type_penalty;

    // Variables missing description: -2 points each, max -10
    let var_desc_penalty = (result.variables_missing_description.len() as i32 * 2).min(10);
    score -= var_desc_penalty;

    // Outputs missing description: -2 points each, max -10
    let out_desc_penalty = (result.outputs_missing_description.len() as i32 * 2).min(10);
    score -= out_desc_penalty;

    // count instead of for_each: -5 points each, max -15
    let count_penalty = (result.count_instead_of_foreach.len() as i32 * 5).min(15);
    score -= count_penalty;

    // any type usage: -5 points each, max -10
    let any_penalty = (result.any_type_usage.len() as i32 * 5).min(10);
    score -= any_penalty;

    // Providers missing version: -5 points each, max -10
    let version_penalty = (result.providers_missing_version.len() as i32 * 5).min(10);
    score -= version_penalty;

    // Missing default_tags for AWS: -10 points
    if result.missing_default_tags && !analysis.providers.is_empty() {
        score -= 10;
    }

    // Hardcoded secrets: -20 points each (critical issue)
    let secret_penalty = (result.hardcoded_secrets.len() as i32 * 20).min(40);
    score -= secret_penalty;

    // Missing lifecycle protection: -5 points each, max -15
    let lifecycle_penalty = (result.missing_lifecycle_protection.len() as i32 * 5).min(15);
    score -= lifecycle_penalty;

    score.clamp(0, 100) as u8
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::terraform::model::{TerraformOutput, TerraformProvider, TerraformVariable};

    #[test]
    fn test_check_guidelines_missing_type() {
        let analysis = TerraformAnalysis {
            project_directory: "/test".to_string(),
            file_count: 1,
            resources: vec![],
            variables: vec![
                TerraformVariable {
                    name: "var_with_type".to_string(),
                    description: Some("Has type".to_string()),
                    type_: Some("string".to_string()),
                    default: None,
                },
                TerraformVariable {
                    name: "var_without_type".to_string(),
                    description: Some("No type".to_string()),
                    type_: None,
                    default: None,
                },
            ],
            outputs: vec![],
            providers: vec![],
        };
        let file_contents = HashMap::new();
        let result = check_guidelines(&analysis, &file_contents);

        assert_eq!(result.variables_missing_type.len(), 1);
        assert_eq!(result.variables_missing_type[0], "var_without_type");
    }

    #[test]
    fn test_check_guidelines_missing_description() {
        let analysis = TerraformAnalysis {
            project_directory: "/test".to_string(),
            file_count: 1,
            resources: vec![],
            variables: vec![
                TerraformVariable {
                    name: "var_with_desc".to_string(),
                    description: Some("Has description".to_string()),
                    type_: Some("string".to_string()),
                    default: None,
                },
                TerraformVariable {
                    name: "var_without_desc".to_string(),
                    description: None,
                    type_: Some("string".to_string()),
                    default: None,
                },
            ],
            outputs: vec![
                TerraformOutput {
                    name: "output_with_desc".to_string(),
                    description: Some("Has description".to_string()),
                    value: None,
                },
                TerraformOutput {
                    name: "output_without_desc".to_string(),
                    description: None,
                    value: None,
                },
            ],
            providers: vec![],
        };
        let file_contents = HashMap::new();
        let result = check_guidelines(&analysis, &file_contents);

        assert_eq!(result.variables_missing_description.len(), 1);
        assert_eq!(result.variables_missing_description[0], "var_without_desc");
        assert_eq!(result.outputs_missing_description.len(), 1);
        assert_eq!(result.outputs_missing_description[0], "output_without_desc");
    }

    #[test]
    fn test_check_guidelines_provider_version() {
        let analysis = TerraformAnalysis {
            project_directory: "/test".to_string(),
            file_count: 1,
            resources: vec![],
            variables: vec![],
            outputs: vec![],
            providers: vec![
                TerraformProvider {
                    name: "aws".to_string(),
                    version: Some("~> 5.0".to_string()),
                },
                TerraformProvider {
                    name: "random".to_string(),
                    version: None,
                },
            ],
        };
        let file_contents = HashMap::new();
        let result = check_guidelines(&analysis, &file_contents);

        assert_eq!(result.providers_missing_version.len(), 1);
        assert_eq!(result.providers_missing_version[0], "random");
    }

    #[test]
    fn test_compliance_score_calculation() {
        let analysis = TerraformAnalysis {
            project_directory: "/test".to_string(),
            file_count: 1,
            resources: vec![],
            variables: vec![TerraformVariable {
                name: "good_var".to_string(),
                description: Some("Good variable".to_string()),
                type_: Some("string".to_string()),
                default: None,
            }],
            outputs: vec![TerraformOutput {
                name: "good_output".to_string(),
                description: Some("Good output".to_string()),
                value: None,
            }],
            providers: vec![TerraformProvider {
                name: "aws".to_string(),
                version: Some("~> 5.0".to_string()),
            }],
        };
        let file_contents = HashMap::new();
        let result = check_guidelines(&analysis, &file_contents);

        // Perfect compliance should give 100 or close to it
        assert!(result.compliance_score >= 90);
    }

    fn create_test_analysis() -> TerraformAnalysis {
        TerraformAnalysis {
            project_directory: "/test/module".to_string(),
            file_count: 3,
            resources: vec![
                crate::terraform::model::TerraformResource {
                    resource_type: "aws_vpc".to_string(),
                    name: "main".to_string(),
                    file: "vpc.tf".to_string(),
                    provider: "aws".to_string(),
                },
                crate::terraform::model::TerraformResource {
                    resource_type: "aws_subnet".to_string(),
                    name: "public".to_string(),
                    file: "vpc.tf".to_string(),
                    provider: "aws".to_string(),
                },
                crate::terraform::model::TerraformResource {
                    resource_type: "aws_instance".to_string(),
                    name: "web".to_string(),
                    file: "compute.tf".to_string(),
                    provider: "aws".to_string(),
                },
            ],
            variables: vec![
                TerraformVariable {
                    name: "vpc_cidr".to_string(),
                    description: Some("VPC CIDR block".to_string()),
                    type_: Some("string".to_string()),
                    default: None,
                },
                TerraformVariable {
                    name: "instance_type".to_string(),
                    description: None,
                    type_: Some("string".to_string()),
                    default: Some(serde_json::json!("t3.micro")),
                },
            ],
            outputs: vec![TerraformOutput {
                name: "vpc_id".to_string(),
                description: Some("The VPC ID".to_string()),
                value: None,
            }],
            providers: vec![TerraformProvider {
                name: "aws".to_string(),
                version: Some("~> 5.0".to_string()),
            }],
        }
    }

    #[test]
    fn test_resource_category() {
        assert_eq!(get_resource_category("aws_vpc"), "networking-core");
        assert_eq!(get_resource_category("aws_subnet"), "networking-core");
        assert_eq!(get_resource_category("aws_instance"), "compute");
        assert_eq!(get_resource_category("aws_s3_bucket"), "storage");
        assert_eq!(
            get_resource_category("aws_security_group"),
            "networking-security"
        );
        assert_eq!(
            get_resource_category("aws_vpn_gateway"),
            "networking-connectivity"
        );
    }

    #[test]
    fn test_calculate_metrics() {
        let analysis = create_test_analysis();
        let mut file_contents = HashMap::new();
        file_contents.insert(
            "vpc.tf".to_string(),
            r#"
            resource "aws_vpc" "main" {}
            resource "aws_subnet" "public" {}
            "#
            .to_string(),
        );

        let metrics = calculate_metrics(&analysis, &file_contents);
        assert_eq!(metrics.variable_count, 2);
        assert_eq!(metrics.resource_count, 3);
        assert_eq!(metrics.output_count, 1);
    }

    #[test]
    fn test_analyze_cohesion() {
        let analysis = create_test_analysis();
        let cohesion = analyze_cohesion(&analysis);

        // Should have moderate cohesion (networking + compute)
        assert!(cohesion.score > 0);
        assert!(!cohesion.resource_type_groups.is_empty());
    }

    #[test]
    fn test_health_score_bounds() {
        let analysis = create_test_analysis();
        let file_contents = HashMap::new();
        let health = analyze_module_health(&analysis, &file_contents);

        assert!(health.health_score <= 100);
    }
}