raz-core 0.2.4

Universal command generator for Rust projects - Core library with stateless file analysis and cursor-aware execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
//! Context analysis and project structure detection

use crate::error::{RazError, RazResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Project context containing all relevant information for command generation
#[derive(Debug, Clone)]
pub struct ProjectContext {
    /// Root directory of the workspace
    pub workspace_root: PathBuf,

    /// Current file being edited (if any)
    pub current_file: Option<FileContext>,

    /// Current cursor position (if available)
    pub cursor_position: Option<Position>,

    /// Detected project type
    pub project_type: ProjectType,

    /// Project dependencies
    pub dependencies: Vec<Dependency>,

    /// Workspace members (for multi-crate workspaces)
    pub workspace_members: Vec<WorkspaceMember>,

    /// Build targets found in the project
    pub build_targets: Vec<BuildTarget>,

    /// Active cargo features
    pub active_features: Vec<String>,

    /// Environment variables relevant to the project
    pub env_vars: HashMap<String, String>,
}

/// File-specific context information
#[derive(Debug, Clone)]
pub struct FileContext {
    /// Path to the file
    pub path: PathBuf,

    /// Programming language of the file
    pub language: Language,

    /// Symbols found in the file (functions, structs, etc.)
    pub symbols: Vec<Symbol>,

    /// Import statements in the file
    pub imports: Vec<Import>,

    /// Symbol at the current cursor position
    pub cursor_symbol: Option<Symbol>,

    /// Module this file belongs to
    pub module_path: Option<String>,
}

/// Cursor position in a file
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Position {
    pub line: u32,
    pub column: u32,
}

/// Range in a file
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Range {
    pub start: Position,
    pub end: Position,
}

impl Range {
    pub fn contains(&self, position: Position) -> bool {
        position >= self.start && position <= self.end
    }

    pub fn contains_position(&self, position: Position) -> bool {
        self.contains(position)
    }
}

impl PartialOrd for Position {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Position {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.line
            .cmp(&other.line)
            .then(self.column.cmp(&other.column))
    }
}

/// Types of projects that can be detected
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProjectType {
    Binary,
    Library,
    Workspace,
    Leptos,
    Dioxus,
    Axum,
    Bevy,
    Tauri,
    Yew,
    Mixed(Vec<ProjectType>),
}

/// Programming language detection
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Language {
    Rust,
    Toml,
    Json,
    Yaml,
    Markdown,
    Unknown,
}

impl Language {
    pub fn from_path(path: &Path) -> Self {
        match path.extension().and_then(|s| s.to_str()) {
            Some("rs") => Language::Rust,
            Some("toml") => Language::Toml,
            Some("json") => Language::Json,
            Some("yaml" | "yml") => Language::Yaml,
            Some("md") => Language::Markdown,
            _ => Language::Unknown,
        }
    }
}

/// Symbols found in source code
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Symbol {
    pub name: String,
    pub kind: SymbolKind,
    pub range: Range,
    pub modifiers: Vec<String>,
    pub children: Vec<Symbol>,
    pub metadata: HashMap<String, String>,
}

/// Types of symbols that can be detected
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SymbolKind {
    Function,
    Struct,
    Enum,
    Trait,
    Module,
    Test,
    Impl,
    Constant,
    Static,
    TypeAlias,
    Macro,
    Variable,
}

/// Symbol visibility (legacy - now using modifiers)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Visibility {
    Public,
    Private,
    Crate,
    Super,
}

/// Import statements
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Import {
    pub path: String,
    pub alias: Option<String>,
    pub items: Vec<String>,
}

/// Project dependency information
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dependency {
    pub name: String,
    pub version: String,
    pub features: Vec<String>,
    pub optional: bool,
    pub dev_dependency: bool,
}

/// Workspace member information
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkspaceMember {
    pub name: String,
    pub path: PathBuf,
    pub package_type: ProjectType,
}

/// Build target information
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildTarget {
    pub name: String,
    pub target_type: TargetType,
    pub path: PathBuf,
}

/// Types of build targets
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TargetType {
    Binary,
    Library,
    Example,
    Test,
    Bench,
}

/// Enhanced test context for precise command generation
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestContext {
    /// Package name for the test
    pub package_name: Option<String>,
    /// Target type (lib, bin, test, etc.)
    pub target_type: TestTargetType,
    /// Full module path to the test (e.g., ["middleware", "csrf", "tests"])
    pub module_path: Vec<String>,
    /// Specific test function name
    pub test_name: Option<String>,
    /// Required feature flags
    pub features: Vec<String>,
    /// Environment variables needed for the test
    pub env_vars: Vec<(String, String)>,
    /// Working directory for the test command
    pub working_dir: Option<PathBuf>,
}

/// Test target types for enhanced test command generation
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TestTargetType {
    /// Library unit tests (--lib)
    Lib,
    /// Binary tests (--bin <name>)
    Bin(String),
    /// Integration tests (--test <name>)
    Test(String),
    /// Benchmark tests (--bench <name>)
    Bench(String),
    /// Example tests (--example <name>)
    Example(String),
}

impl TestContext {
    /// Create a new empty test context
    pub fn new() -> Self {
        Self {
            package_name: None,
            target_type: TestTargetType::Lib,
            module_path: Vec::new(),
            test_name: None,
            features: Vec::new(),
            env_vars: Vec::new(),
            working_dir: None,
        }
    }

    /// Get the full module path as a string (e.g., "middleware::csrf::tests")
    pub fn module_path_string(&self) -> Option<String> {
        if self.module_path.is_empty() {
            None
        } else {
            Some(self.module_path.join("::"))
        }
    }

    /// Get the full test path including module and test name
    pub fn full_test_path(&self) -> Option<String> {
        match (self.module_path_string(), &self.test_name) {
            (Some(module), Some(test)) => Some(format!("{module}::{test}")),
            (None, Some(test)) => Some(test.clone()),
            (Some(module), None) => Some(module),
            (None, None) => None,
        }
    }

    /// Check if this context has enough information for a precise test command
    pub fn is_precise(&self) -> bool {
        self.test_name.is_some() || !self.module_path.is_empty()
    }
}

impl Default for TestContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Main project analyzer
pub struct ProjectAnalyzer {
    workspace_detector: WorkspaceDetector,
    dependency_analyzer: DependencyAnalyzer,
    target_detector: TargetDetector,
    framework_detector: FrameworkDetector,
    file_analyzer: FileAnalyzer,
}

impl ProjectAnalyzer {
    pub fn new() -> Self {
        Self {
            workspace_detector: WorkspaceDetector::new(),
            dependency_analyzer: DependencyAnalyzer::new(),
            target_detector: TargetDetector::new(),
            framework_detector: FrameworkDetector::new(),
            file_analyzer: FileAnalyzer::new(),
        }
    }
}

impl Default for ProjectAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

impl ProjectAnalyzer {
    /// Analyze a project and return comprehensive context
    pub async fn analyze_project(&self, root: &Path) -> RazResult<ProjectContext> {
        // Find Cargo.toml
        let cargo_toml = self.find_cargo_toml(root)?;

        // Analyze workspace structure
        let mut workspace_info = self.workspace_detector.detect(&cargo_toml).await?;

        // Analyze dependencies from root
        let mut all_dependencies = self.dependency_analyzer.analyze(&cargo_toml).await?;

        // If this is a workspace, analyze dependencies from all members
        if workspace_info.is_workspace {
            for member in &mut workspace_info.members {
                let member_cargo_toml = root.join(&member.path).join("Cargo.toml");
                if member_cargo_toml.exists() {
                    // Extract the actual package name from the member's Cargo.toml
                    if let Ok(package_name) =
                        self.extract_package_name_from_toml(&member_cargo_toml)
                    {
                        member.name = package_name;
                    }

                    let member_deps = self.dependency_analyzer.analyze(&member_cargo_toml).await?;

                    // Detect member's project type based on its dependencies
                    let member_root = root.join(&member.path);
                    member.package_type = self
                        .framework_detector
                        .detect(&member_deps, &[], &member_root)
                        .await?;

                    // Add member dependencies to the overall list (avoiding duplicates)
                    for dep in member_deps {
                        if !all_dependencies.iter().any(|d| d.name == dep.name) {
                            all_dependencies.push(dep);
                        }
                    }
                }
            }
        } else {
            // For single package, ensure we have the correct package name
            if !workspace_info.members.is_empty() {
                if let Ok(package_name) = self.extract_package_name_from_toml(&cargo_toml) {
                    workspace_info.members[0].name = package_name;
                }
            }
        }

        // Detect build targets
        let targets = self.target_detector.detect(root).await?;

        // Detect overall framework type based on all dependencies
        let project_type = self
            .framework_detector
            .detect(&all_dependencies, &targets, root)
            .await?;

        Ok(ProjectContext {
            workspace_root: root.to_path_buf(),
            current_file: None,
            cursor_position: None,
            project_type,
            dependencies: all_dependencies,
            workspace_members: workspace_info.members,
            build_targets: targets,
            active_features: Vec::new(),
            env_vars: HashMap::new(),
        })
    }

    /// Analyze a specific file and add its context
    pub async fn analyze_file(
        &self,
        context: &mut ProjectContext,
        file_path: &Path,
        cursor: Option<Position>,
    ) -> RazResult<()> {
        let file_context = self.file_analyzer.analyze_file(file_path, cursor).await?;
        context.current_file = Some(file_context);
        context.cursor_position = cursor;
        Ok(())
    }

    /// Resolve test context from current project context and cursor position
    pub async fn resolve_test_context(
        &self,
        context: &ProjectContext,
    ) -> RazResult<Option<TestContext>> {
        let Some(ref file_context) = context.current_file else {
            return Ok(None);
        };

        // Only proceed if we're in a Rust file
        if file_context.language != Language::Rust {
            return Ok(None);
        }

        let mut test_context = TestContext::new();

        // 1. Resolve package name
        test_context.package_name = self.resolve_package_name(context, &file_context.path)?;

        // 2. Resolve target type (lib/bin/test)
        test_context.target_type = self.resolve_target_type(context, &file_context.path)?;

        // 3. Resolve module path
        test_context.module_path = self.resolve_module_path(&file_context.path)?;

        // 4. Resolve test name if cursor is on a test function
        if let Some(ref cursor_symbol) = file_context.cursor_symbol {
            if cursor_symbol.kind == SymbolKind::Test
                || (cursor_symbol.kind == SymbolKind::Function
                    && cursor_symbol.name.starts_with("test_"))
            {
                test_context.test_name = Some(cursor_symbol.name.clone());
            }
        }

        // 5. Resolve features and environment variables
        test_context.features = self.resolve_test_features(context, &file_context.path)?;
        test_context.env_vars = self.resolve_test_env_vars(context)?;

        // 6. Set working directory
        test_context.working_dir = Some(context.workspace_root.clone());

        // Only return context if we have meaningful test information
        if test_context.is_precise() || test_context.package_name.is_some() {
            Ok(Some(test_context))
        } else {
            Ok(None)
        }
    }

    /// Resolve package name from file path and workspace structure
    fn resolve_package_name(
        &self,
        context: &ProjectContext,
        file_path: &Path,
    ) -> RazResult<Option<String>> {
        // For single-package projects
        if context.workspace_members.len() == 1 {
            return Ok(Some(context.workspace_members[0].name.clone()));
        }

        // For workspace projects, find which member contains this file
        for member in &context.workspace_members {
            let member_path = if member.path.is_absolute() {
                member.path.clone()
            } else {
                context.workspace_root.join(&member.path)
            };

            if file_path.starts_with(&member_path) {
                return Ok(Some(member.name.clone()));
            }
        }

        // Fallback: extract from the nearest Cargo.toml
        let mut current_dir = file_path.parent();
        while let Some(dir) = current_dir {
            let cargo_toml = dir.join("Cargo.toml");
            if cargo_toml.exists() {
                if let Ok(name) = self.extract_package_name_from_toml(&cargo_toml) {
                    return Ok(Some(name));
                }
            }
            current_dir = dir.parent();
        }

        Ok(None)
    }

    /// Extract package name from Cargo.toml
    fn extract_package_name_from_toml(&self, cargo_toml: &Path) -> RazResult<String> {
        let content = fs::read_to_string(cargo_toml)?;
        let parsed: toml::Value = toml::from_str(&content)
            .map_err(|e| RazError::parse(format!("Invalid Cargo.toml: {e}")))?;

        parsed
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            .map(|s| s.to_string())
            .ok_or_else(|| RazError::parse("No package name found in Cargo.toml".to_string()))
    }

    /// Resolve target type from file path
    fn resolve_target_type(
        &self,
        context: &ProjectContext,
        file_path: &Path,
    ) -> RazResult<TestTargetType> {
        let file_str = file_path.to_string_lossy();

        // Check for integration tests (tests/ directory)
        if file_str.contains("/tests/") {
            if let Some(test_name) = file_path.file_stem().and_then(|s| s.to_str()) {
                return Ok(TestTargetType::Test(test_name.to_string()));
            }
        }

        // Check for examples (examples/ directory)
        if file_str.contains("/examples/") {
            if let Some(example_name) = file_path.file_stem().and_then(|s| s.to_str()) {
                return Ok(TestTargetType::Example(example_name.to_string()));
            }
        }

        // Check for benchmarks (benches/ directory)
        if file_str.contains("/benches/") {
            if let Some(bench_name) = file_path.file_stem().and_then(|s| s.to_str()) {
                return Ok(TestTargetType::Bench(bench_name.to_string()));
            }
        }

        // Check if it's a library file
        if file_str.contains("/src/lib.rs") || file_str.contains("/src/mod.rs") {
            return Ok(TestTargetType::Lib);
        }

        // Check for binary files
        if file_str.contains("/src/main.rs") {
            // Main binary
            return Ok(TestTargetType::Bin("main".to_string()));
        }

        if file_str.contains("/src/bin/") {
            if let Some(bin_name) = file_path.file_stem().and_then(|s| s.to_str()) {
                return Ok(TestTargetType::Bin(bin_name.to_string()));
            }
        }

        // Check against build targets for more precise detection
        for target in &context.build_targets {
            if file_path.starts_with(target.path.parent().unwrap_or(&context.workspace_root)) {
                return match target.target_type {
                    TargetType::Binary => Ok(TestTargetType::Bin(target.name.clone())),
                    TargetType::Library => Ok(TestTargetType::Lib),
                    TargetType::Test => Ok(TestTargetType::Test(target.name.clone())),
                    TargetType::Bench => Ok(TestTargetType::Bench(target.name.clone())),
                    TargetType::Example => Ok(TestTargetType::Example(target.name.clone())),
                };
            }
        }

        // Default to library
        Ok(TestTargetType::Lib)
    }

    /// Resolve module path from file path using multiple strategies
    fn resolve_module_path(&self, file_path: &Path) -> RazResult<Vec<String>> {
        // Strategy 1: Tree-sitter AST analysis (most precise)
        if let Ok(module_path) = self.resolve_module_path_treesitter(file_path) {
            if !module_path.is_empty() {
                return Ok(module_path);
            }
        }

        // Strategy 2: Rust Analyzer LSP integration (if available)
        if let Ok(module_path) = self.resolve_module_path_rust_analyzer(file_path) {
            if !module_path.is_empty() {
                return Ok(module_path);
            }
        }

        // Strategy 3: Basic file path analysis (fallback)
        if let Some(module_str) = FileAnalyzer::extract_module_path(file_path) {
            Ok(module_str
                .split("::")
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .collect())
        } else {
            Ok(Vec::new())
        }
    }

    /// Resolve module path using tree-sitter AST analysis
    fn resolve_module_path_treesitter(&self, file_path: &Path) -> RazResult<Vec<String>> {
        // Only proceed if tree-sitter is available
        if self.file_analyzer.rust_analyzer.is_none() {
            return Ok(Vec::new());
        }

        let content = fs::read_to_string(file_path)?;
        let mut rust_analyzer = crate::ast::RustAnalyzer::new()?;
        let tree = rust_analyzer.parse(&content)?;

        // 1. Start with file-based module path
        let mut module_path = Vec::new();
        if let Some(base_path) = FileAnalyzer::extract_module_path(file_path) {
            module_path = base_path
                .split("::")
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .collect();
        }

        // 2. Look for nested module declarations and test modules
        let symbols = rust_analyzer.extract_symbols(&tree, &content)?;

        // Find test modules (common pattern: mod tests { ... })
        let test_modules: Vec<_> = symbols
            .iter()
            .filter(|s| {
                s.kind == SymbolKind::Module && (s.name == "tests" || s.name.contains("test"))
            })
            .collect();

        // If we're in a test module, add it to the path
        if !test_modules.is_empty() {
            // For now, assume we're in the first test module found
            // TODO: Use cursor position to determine exact module when available
            if let Some(test_mod) = test_modules.first() {
                module_path.push(test_mod.name.clone());
            }
        }

        // 3. Enhance path detection based on common Rust patterns
        module_path = self.enhance_module_path_with_patterns(module_path, file_path, &content)?;

        Ok(module_path)
    }

    /// Enhance module path detection with common Rust patterns
    fn enhance_module_path_with_patterns(
        &self,
        mut module_path: Vec<String>,
        file_path: &Path,
        content: &str,
    ) -> RazResult<Vec<String>> {
        let file_str = file_path.to_string_lossy();

        // Pattern 1: Test files often have tests module
        if (content.contains("#[cfg(test)]") || content.contains("mod tests"))
            && !module_path.iter().any(|m| m == "tests")
        {
            module_path.push("tests".to_string());
        }

        // Pattern 2: Integration tests in tests/ directory
        if file_str.contains("/tests/") {
            // Integration tests don't typically have nested module paths
            // The test file name becomes the module
            if let Some(test_name) = file_path.file_stem().and_then(|s| s.to_str()) {
                module_path = vec![test_name.to_string()];
            }
        }

        // Pattern 3: Common module patterns (middleware, handlers, etc.)
        let common_modules = [
            "middleware",
            "handlers",
            "controllers",
            "services",
            "utils",
            "helpers",
        ];
        for common in &common_modules {
            if file_str.contains(&format!("/{common}/"))
                && !module_path.contains(&common.to_string())
            {
                // Find the position to insert this module
                if let Some(pos) = module_path.iter().position(|m| m == "tests") {
                    module_path.insert(pos, common.to_string());
                } else {
                    module_path.insert(
                        module_path.len().saturating_sub(1).max(0),
                        common.to_string(),
                    );
                }
            }
        }

        Ok(module_path)
    }

    /// Resolve module path using rust-analyzer LSP integration
    fn resolve_module_path_rust_analyzer(&self, _file_path: &Path) -> RazResult<Vec<String>> {
        // TODO: Implement rust-analyzer LSP integration
        // This would involve:
        // 1. Starting/connecting to rust-analyzer LSP server
        // 2. Sending textDocument/documentSymbol request
        // 3. Parsing the response to extract module hierarchy
        // 4. Mapping cursor position to exact module path

        // For now, return empty to fall back to other strategies
        Ok(Vec::new())
    }

    /// Resolve features required for testing this file
    fn resolve_test_features(
        &self,
        context: &ProjectContext,
        _file_path: &Path,
    ) -> RazResult<Vec<String>> {
        // For now, return active features from the project context
        // TODO: In the future, we could parse #[cfg(feature = "...")] attributes from the file
        Ok(context.active_features.clone())
    }

    /// Resolve environment variables needed for testing
    fn resolve_test_env_vars(&self, context: &ProjectContext) -> RazResult<Vec<(String, String)>> {
        Ok(context
            .env_vars
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect())
    }

    fn find_cargo_toml(&self, root: &Path) -> RazResult<PathBuf> {
        let cargo_toml = root.join("Cargo.toml");
        if cargo_toml.exists() {
            Ok(cargo_toml)
        } else {
            Err(RazError::invalid_workspace(root))
        }
    }
}

/// Workspace detection and analysis
pub struct WorkspaceDetector;

impl WorkspaceDetector {
    pub fn new() -> Self {
        Self
    }
}

impl Default for WorkspaceDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl WorkspaceDetector {
    pub async fn detect(&self, cargo_toml: &Path) -> RazResult<WorkspaceInfo> {
        let content = fs::read_to_string(cargo_toml)?;
        let parsed: toml::Value = toml::from_str(&content)
            .map_err(|e| RazError::parse(format!("Invalid Cargo.toml: {e}")))?;

        if let Some(workspace) = parsed.get("workspace") {
            let members = self.extract_workspace_members(workspace)?;
            Ok(WorkspaceInfo {
                is_workspace: true,
                members,
            })
        } else {
            // Single package
            let package_name = parsed
                .get("package")
                .and_then(|p| p.get("name"))
                .and_then(|n| n.as_str())
                .unwrap_or("unknown")
                .to_string();

            Ok(WorkspaceInfo {
                is_workspace: false,
                members: vec![WorkspaceMember {
                    name: package_name,
                    path: cargo_toml.parent().unwrap().to_path_buf(),
                    package_type: ProjectType::Binary, // Will be refined later
                }],
            })
        }
    }

    fn extract_workspace_members(
        &self,
        workspace: &toml::Value,
    ) -> RazResult<Vec<WorkspaceMember>> {
        let members = workspace
            .get("members")
            .and_then(|m| m.as_array())
            .ok_or_else(|| RazError::parse("Workspace missing members"))?;

        let mut result = Vec::new();

        for member in members {
            if let Some(path_str) = member.as_str() {
                result.push(WorkspaceMember {
                    name: path_str.to_string(), // Will be updated with actual package name
                    path: PathBuf::from(path_str),
                    package_type: ProjectType::Binary, // Will be refined later
                });
            }
        }

        Ok(result)
    }
}

#[derive(Debug)]
pub struct WorkspaceInfo {
    pub is_workspace: bool,
    pub members: Vec<WorkspaceMember>,
}

/// Dependency analysis
pub struct DependencyAnalyzer;

impl DependencyAnalyzer {
    pub fn new() -> Self {
        Self
    }
}

impl Default for DependencyAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

impl DependencyAnalyzer {
    pub async fn analyze(&self, cargo_toml: &Path) -> RazResult<Vec<Dependency>> {
        let content = fs::read_to_string(cargo_toml)?;
        let parsed: toml::Value = toml::from_str(&content)
            .map_err(|e| RazError::parse(format!("Invalid Cargo.toml: {e}")))?;

        let mut dependencies = Vec::new();

        // Regular dependencies
        if let Some(deps) = parsed.get("dependencies").and_then(|d| d.as_table()) {
            dependencies.extend(self.parse_dependencies(deps, false)?);
        }

        // Dev dependencies
        if let Some(dev_deps) = parsed.get("dev-dependencies").and_then(|d| d.as_table()) {
            dependencies.extend(self.parse_dependencies(dev_deps, true)?);
        }

        Ok(dependencies)
    }

    fn parse_dependencies(
        &self,
        deps: &toml::value::Table,
        is_dev: bool,
    ) -> RazResult<Vec<Dependency>> {
        let mut result = Vec::new();

        for (name, value) in deps {
            let dependency = match value {
                toml::Value::String(version) => Dependency {
                    name: name.clone(),
                    version: version.clone(),
                    features: Vec::new(),
                    optional: false,
                    dev_dependency: is_dev,
                },
                toml::Value::Table(table) => {
                    let version = table
                        .get("version")
                        .and_then(|v| v.as_str())
                        .unwrap_or("*")
                        .to_string();

                    let features = table
                        .get("features")
                        .and_then(|f| f.as_array())
                        .map(|arr| {
                            arr.iter()
                                .filter_map(|v| v.as_str())
                                .map(|s| s.to_string())
                                .collect()
                        })
                        .unwrap_or_default();

                    let optional = table
                        .get("optional")
                        .and_then(|o| o.as_bool())
                        .unwrap_or(false);

                    Dependency {
                        name: name.clone(),
                        version,
                        features,
                        optional,
                        dev_dependency: is_dev,
                    }
                }
                _ => continue,
            };

            result.push(dependency);
        }

        Ok(result)
    }
}

/// Build target detection
pub struct TargetDetector;

impl TargetDetector {
    pub fn new() -> Self {
        Self
    }
}

impl Default for TargetDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl TargetDetector {
    pub async fn detect(&self, root: &Path) -> RazResult<Vec<BuildTarget>> {
        let mut targets = Vec::new();

        // Check for main.rs (binary)
        let main_rs = root.join("src/main.rs");
        if main_rs.exists() {
            targets.push(BuildTarget {
                name: "main".to_string(),
                target_type: TargetType::Binary,
                path: main_rs,
            });
        }

        // Check for lib.rs (library)
        let lib_rs = root.join("src/lib.rs");
        if lib_rs.exists() {
            targets.push(BuildTarget {
                name: "lib".to_string(),
                target_type: TargetType::Library,
                path: lib_rs,
            });
        }

        // Check examples directory
        let examples_dir = root.join("examples");
        if examples_dir.exists() {
            for entry in fs::read_dir(&examples_dir)? {
                let entry = entry?;
                if let Some(name) = entry.file_name().to_str() {
                    if name.ends_with(".rs") {
                        let name = name.strip_suffix(".rs").unwrap();
                        targets.push(BuildTarget {
                            name: name.to_string(),
                            target_type: TargetType::Example,
                            path: entry.path(),
                        });
                    }
                }
            }
        }

        // Check tests directory
        let tests_dir = root.join("tests");
        if tests_dir.exists() {
            for entry in fs::read_dir(&tests_dir)? {
                let entry = entry?;
                if let Some(name) = entry.file_name().to_str() {
                    if name.ends_with(".rs") {
                        let name = name.strip_suffix(".rs").unwrap();
                        targets.push(BuildTarget {
                            name: name.to_string(),
                            target_type: TargetType::Test,
                            path: entry.path(),
                        });
                    }
                }
            }
        }

        Ok(targets)
    }
}

/// Framework detection based on dependencies and project structure
pub struct FrameworkDetector {
    rules: Vec<DetectionRule>,
}

impl FrameworkDetector {
    pub fn new() -> Self {
        Self {
            rules: Self::default_rules(),
        }
    }
}

impl Default for FrameworkDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl FrameworkDetector {
    pub async fn detect(
        &self,
        dependencies: &[Dependency],
        _targets: &[BuildTarget],
        workspace_root: &Path,
    ) -> RazResult<ProjectType> {
        let mut detected_frameworks = Vec::new();

        for rule in &self.rules {
            if rule.matches(dependencies, workspace_root) {
                // Check if we already detected this framework type
                if !detected_frameworks.contains(&rule.project_type) {
                    detected_frameworks.push(rule.project_type.clone());
                }
            }
        }

        match detected_frameworks.len() {
            0 => Ok(ProjectType::Binary), // Default fallback
            1 => Ok(detected_frameworks.into_iter().next().unwrap()),
            _ => {
                // Multiple frameworks detected - create a mixed project type
                // Sort frameworks by priority (Tauri first as it's often the wrapper)
                detected_frameworks.sort_by_key(|framework| match framework {
                    ProjectType::Tauri => 0,  // Highest priority - desktop wrapper
                    ProjectType::Leptos => 1, // Web framework
                    ProjectType::Dioxus => 2, // Cross-platform UI
                    ProjectType::Yew => 3,    // Web framework
                    ProjectType::Bevy => 4,   // Game engine
                    ProjectType::Axum => 5,   // Web server
                    _ => 6,                   // Other types
                });
                Ok(ProjectType::Mixed(detected_frameworks))
            }
        }
    }

    fn default_rules() -> Vec<DetectionRule> {
        vec![
            // Tauri detection (highest priority due to specific structure)
            DetectionRule {
                framework: "tauri".to_string(),
                project_type: ProjectType::Tauri,
                conditions: vec![
                    DetectionCondition::HasFilePattern("src-tauri/Cargo.toml".to_string()),
                    DetectionCondition::HasFilePattern("src-tauri/tauri.conf.json".to_string()),
                ],
            },
            // Alternative Tauri detection by dependency
            DetectionRule {
                framework: "tauri".to_string(),
                project_type: ProjectType::Tauri,
                conditions: vec![DetectionCondition::HasDependency("tauri".to_string())],
            },
            // Leptos detection with configuration file
            DetectionRule {
                framework: "leptos".to_string(),
                project_type: ProjectType::Leptos,
                conditions: vec![
                    DetectionCondition::HasAnyDependency(vec![
                        "leptos".to_string(),
                        "leptos_axum".to_string(),
                        "leptos_actix".to_string(),
                        "leptos_router".to_string(),
                        "leptos_reactive".to_string(),
                    ]),
                    DetectionCondition::ConfigFileContains(
                        PathBuf::from("Cargo.toml"),
                        "[package.metadata.leptos]".to_string(),
                    ),
                ],
            },
            // Leptos detection by dependency only (fallback)
            DetectionRule {
                framework: "leptos".to_string(),
                project_type: ProjectType::Leptos,
                conditions: vec![DetectionCondition::HasAnyDependency(vec![
                    "leptos".to_string(),
                    "leptos_axum".to_string(),
                    "leptos_actix".to_string(),
                    "leptos_router".to_string(),
                    "leptos_reactive".to_string(),
                ])],
            },
            // Dioxus detection with configuration file
            DetectionRule {
                framework: "dioxus".to_string(),
                project_type: ProjectType::Dioxus,
                conditions: vec![
                    DetectionCondition::HasDependency("dioxus".to_string()),
                    DetectionCondition::HasFile(PathBuf::from("Dioxus.toml")),
                ],
            },
            // Dioxus detection by dependency only (fallback)
            DetectionRule {
                framework: "dioxus".to_string(),
                project_type: ProjectType::Dioxus,
                conditions: vec![DetectionCondition::HasAnyDependency(vec![
                    "dioxus".to_string(),
                    "dioxus-web".to_string(),
                    "dioxus-desktop".to_string(),
                    "dioxus-mobile".to_string(),
                ])],
            },
            // Bevy detection
            DetectionRule {
                framework: "bevy".to_string(),
                project_type: ProjectType::Bevy,
                conditions: vec![DetectionCondition::HasDependency("bevy".to_string())],
            },
            // Axum detection
            DetectionRule {
                framework: "axum".to_string(),
                project_type: ProjectType::Axum,
                conditions: vec![DetectionCondition::HasDependency("axum".to_string())],
            },
            // Yew detection with Trunk configuration
            DetectionRule {
                framework: "yew".to_string(),
                project_type: ProjectType::Yew,
                conditions: vec![
                    DetectionCondition::HasDependency("yew".to_string()),
                    DetectionCondition::HasFile(PathBuf::from("Trunk.toml")),
                ],
            },
            // Yew detection by dependency only (fallback)
            DetectionRule {
                framework: "yew".to_string(),
                project_type: ProjectType::Yew,
                conditions: vec![DetectionCondition::HasAnyDependency(vec![
                    "yew".to_string(),
                    "yew-router".to_string(),
                    "yew-hooks".to_string(),
                ])],
            },
        ]
    }
}

#[derive(Debug)]
pub struct DetectionRule {
    pub framework: String,
    pub project_type: ProjectType,
    pub conditions: Vec<DetectionCondition>,
}

impl DetectionRule {
    pub fn matches(&self, dependencies: &[Dependency], workspace_root: &Path) -> bool {
        self.conditions
            .iter()
            .all(|condition| condition.is_met(dependencies, workspace_root))
    }
}

#[derive(Debug)]
pub enum DetectionCondition {
    HasDependency(String),
    HasAnyDependency(Vec<String>),
    HasFile(PathBuf),
    HasFilePattern(String),
    ConfigFileContains(PathBuf, String),
}

impl DetectionCondition {
    pub fn is_met(&self, dependencies: &[Dependency], workspace_root: &Path) -> bool {
        match self {
            DetectionCondition::HasDependency(name) => {
                dependencies.iter().any(|dep| dep.name == *name)
            }
            DetectionCondition::HasAnyDependency(names) => {
                dependencies.iter().any(|dep| names.contains(&dep.name))
            }
            DetectionCondition::HasFile(path) => path.exists(),
            DetectionCondition::HasFilePattern(pattern) => {
                Self::check_file_pattern(workspace_root, pattern)
            }
            DetectionCondition::ConfigFileContains(path, content) => {
                Self::check_file_content(workspace_root, path, content)
            }
        }
    }

    /// Check if any files matching the given pattern exist in the workspace
    fn check_file_pattern(workspace_root: &Path, pattern: &str) -> bool {
        // Create the full pattern by joining with workspace root
        let full_pattern = workspace_root.join(pattern);
        let pattern_str = full_pattern.to_string_lossy();

        // Use glob to find matching files
        match glob::glob(&pattern_str) {
            Ok(paths) => {
                // Check if any paths match
                paths.filter_map(Result::ok).next().is_some()
            }
            Err(_) => false,
        }
    }

    /// Check if a file contains specific content
    fn check_file_content(workspace_root: &Path, file_path: &Path, content: &str) -> bool {
        let full_path = if file_path.is_absolute() {
            file_path.to_path_buf()
        } else {
            workspace_root.join(file_path)
        };

        match std::fs::read_to_string(&full_path) {
            Ok(file_content) => file_content.contains(content),
            Err(_) => false,
        }
    }
}

/// File analysis using tree-sitter
pub struct FileAnalyzer {
    rust_analyzer: Option<crate::ast::RustAnalyzer>,
}

impl Default for FileAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

impl FileAnalyzer {
    pub fn new() -> Self {
        let rust_analyzer = crate::ast::RustAnalyzer::new().ok();
        Self { rust_analyzer }
    }

    pub async fn analyze_file(
        &self,
        path: &Path,
        cursor: Option<Position>,
    ) -> RazResult<FileContext> {
        let language = Language::from_path(path);

        if language == Language::Rust && self.rust_analyzer.is_some() {
            self.analyze_rust_file(path, cursor).await
        } else {
            // Fallback for non-Rust files or if tree-sitter fails
            Ok(FileContext {
                path: path.to_path_buf(),
                language,
                symbols: Vec::new(),
                imports: Vec::new(),
                cursor_symbol: None,
                module_path: Self::extract_module_path(path),
            })
        }
    }

    async fn analyze_rust_file(
        &self,
        path: &Path,
        cursor: Option<Position>,
    ) -> RazResult<FileContext> {
        if let Some(ref _analyzer) = self.rust_analyzer {
            let content = fs::read_to_string(path)?;
            let mut rust_analyzer = crate::ast::RustAnalyzer::new()?;
            let tree = rust_analyzer.parse(&content)?;

            // Extract symbols
            let symbols = rust_analyzer.extract_symbols(&tree, &content)?;

            // Find cursor symbol if position is provided
            let cursor_symbol = if let Some(pos) = cursor {
                rust_analyzer.symbol_at_position(&tree, &content, pos)?
            } else {
                None
            };

            // Extract imports (basic implementation)
            let imports = self.extract_imports(&content);

            Ok(FileContext {
                path: path.to_path_buf(),
                language: Language::Rust,
                symbols,
                imports,
                cursor_symbol,
                module_path: Self::extract_module_path(path),
            })
        } else {
            Err(RazError::analysis(
                "Rust analyzer not available".to_string(),
            ))
        }
    }

    fn extract_imports(&self, content: &str) -> Vec<Import> {
        let mut imports = Vec::new();

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("use ") {
                if let Some(import) = self.parse_use_statement(trimmed) {
                    imports.push(import);
                }
            }
        }

        imports
    }

    fn parse_use_statement(&self, use_line: &str) -> Option<Import> {
        let use_part = use_line.strip_prefix("use ")?.strip_suffix(";")?;

        // Handle glob imports: use module::*;
        if use_part.ends_with("::*") {
            let path = use_part.strip_suffix("::*")?.to_string();
            return Some(Import {
                path,
                alias: None,
                items: vec!["*".to_string()],
            });
        }

        // Handle braced imports first: use path::{item1, item2 as alias, item3};
        // Check for braces before checking for simple aliases
        if let Some(brace_start) = use_part.find("::{") {
            if let Some(brace_end) = use_part.rfind('}') {
                let path = use_part[..brace_start].trim().to_string();
                let items_str = &use_part[brace_start + 3..brace_end];
                let items = self.parse_import_items(items_str);

                return Some(Import {
                    path,
                    alias: None,
                    items,
                });
            }
        }

        // Handle simple alias: use path as alias;
        if let Some(as_pos) = use_part.find(" as ") {
            let path = use_part[..as_pos].trim();
            let alias = use_part[as_pos + 4..].trim();
            return Some(Import {
                path: path.to_string(),
                alias: Some(alias.to_string()),
                items: vec![],
            });
        }

        // Simple import: use path;
        Some(Import {
            path: use_part.to_string(),
            alias: None,
            items: vec![],
        })
    }

    /// Parse comma-separated import items, handling aliases and nested groups
    fn parse_import_items(&self, items_str: &str) -> Vec<String> {
        let mut items = Vec::new();
        let mut current_item = String::new();
        let mut brace_depth = 0;

        for ch in items_str.chars() {
            match ch {
                '{' => {
                    brace_depth += 1;
                    current_item.push(ch);
                }
                '}' => {
                    brace_depth -= 1;
                    current_item.push(ch);
                }
                ',' if brace_depth == 0 => {
                    let item = current_item.trim();
                    if !item.is_empty() {
                        items.push(item.to_string());
                    }
                    current_item.clear();
                }
                _ => current_item.push(ch),
            }
        }

        // Add the last item
        let item = current_item.trim();
        if !item.is_empty() {
            items.push(item.to_string());
        }

        items
    }

    pub fn extract_module_path(path: &Path) -> Option<String> {
        // Extract module path from file path
        // e.g., src/handlers/auth.rs -> handlers::auth
        if let Some(src_index) = path.to_str()?.find("src/") {
            let relative_path = &path.to_str()?[src_index + 4..];
            let without_extension = relative_path.strip_suffix(".rs")?;
            let module_path = without_extension.replace('/', "::").replace("main", "");
            if module_path.is_empty() {
                None
            } else {
                Some(module_path)
            }
        } else {
            None
        }
    }
}

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

    #[tokio::test]
    async fn test_project_analysis() {
        let temp_dir = TempDir::new().unwrap();
        let cargo_toml = temp_dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"
            [package]
            name = "test-project"
            version = "0.1.0"
            edition = "2021"
            
            [dependencies]
            leptos = "0.5"
        "#,
        )
        .unwrap();

        let analyzer = ProjectAnalyzer::new();
        let context = analyzer.analyze_project(temp_dir.path()).await.unwrap();

        assert_eq!(context.workspace_root, temp_dir.path());
        assert_eq!(context.project_type, ProjectType::Leptos);
        assert!(context.dependencies.iter().any(|d| d.name == "leptos"));
    }

    #[test]
    fn test_language_detection() {
        assert_eq!(Language::from_path(Path::new("main.rs")), Language::Rust);
        assert_eq!(Language::from_path(Path::new("Cargo.toml")), Language::Toml);
        assert_eq!(
            Language::from_path(Path::new("package.json")),
            Language::Json
        );
    }

    #[test]
    fn test_position_ordering() {
        let pos1 = Position { line: 1, column: 5 };
        let pos2 = Position { line: 2, column: 3 };
        let pos3 = Position {
            line: 1,
            column: 10,
        };

        assert!(pos1 < pos2);
        assert!(pos1 < pos3);
        assert!(pos3 < pos2);
    }

    #[test]
    fn test_range_contains() {
        let range = Range {
            start: Position { line: 1, column: 0 },
            end: Position {
                line: 3,
                column: 10,
            },
        };

        assert!(range.contains(Position { line: 2, column: 5 }));
        assert!(range.contains(Position { line: 1, column: 0 }));
        assert!(range.contains(Position {
            line: 3,
            column: 10
        }));
        assert!(!range.contains(Position { line: 0, column: 5 }));
        assert!(!range.contains(Position { line: 4, column: 5 }));
    }

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

        // Create test files
        std::fs::create_dir_all(temp_path.join("src-tauri")).unwrap();
        std::fs::write(temp_path.join("src-tauri/Cargo.toml"), "").unwrap();
        std::fs::write(temp_path.join("src-tauri/tauri.conf.json"), "{}").unwrap();
        std::fs::write(temp_path.join("Dioxus.toml"), "[application]").unwrap();

        // Test pattern matching
        assert!(DetectionCondition::check_file_pattern(
            temp_path,
            "src-tauri/Cargo.toml"
        ));
        assert!(DetectionCondition::check_file_pattern(
            temp_path,
            "src-tauri/*.json"
        ));
        assert!(DetectionCondition::check_file_pattern(
            temp_path,
            "Dioxus.toml"
        ));
        assert!(!DetectionCondition::check_file_pattern(
            temp_path,
            "nonexistent.toml"
        ));
        assert!(!DetectionCondition::check_file_pattern(
            temp_path,
            "src-nonexistent/*.toml"
        ));
    }

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

        // Create test file with content
        let cargo_toml_content = r#"
[package]
name = "test"

[package.metadata.leptos]
output-name = "my-app"
        "#;
        std::fs::write(temp_path.join("Cargo.toml"), cargo_toml_content).unwrap();

        // Test content checking
        assert!(DetectionCondition::check_file_content(
            temp_path,
            &PathBuf::from("Cargo.toml"),
            "[package.metadata.leptos]"
        ));
        assert!(DetectionCondition::check_file_content(
            temp_path,
            &PathBuf::from("Cargo.toml"),
            "output-name"
        ));
        assert!(!DetectionCondition::check_file_content(
            temp_path,
            &PathBuf::from("Cargo.toml"),
            "nonexistent-content"
        ));
        assert!(!DetectionCondition::check_file_content(
            temp_path,
            &PathBuf::from("nonexistent.toml"),
            "any-content"
        ));
    }

    #[tokio::test]
    async fn test_multi_framework_detection() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create a mixed Tauri + Leptos project structure
        std::fs::create_dir_all(temp_path.join("src-tauri")).unwrap();
        std::fs::write(temp_path.join("src-tauri/Cargo.toml"), "").unwrap();
        std::fs::write(temp_path.join("src-tauri/tauri.conf.json"), "{}").unwrap();

        let cargo_toml_content = r#"
[package]
name = "mixed-app"

[package.metadata.leptos]
output-name = "my-app"

[dependencies]
leptos = "0.6"
tauri = "1.0"
        "#;
        std::fs::write(temp_path.join("Cargo.toml"), cargo_toml_content).unwrap();

        // Test framework detection
        let detector = FrameworkDetector::new();
        let deps = vec![
            Dependency {
                name: "leptos".to_string(),
                version: "0.6".to_string(),
                features: vec![],
                optional: false,
                dev_dependency: false,
            },
            Dependency {
                name: "tauri".to_string(),
                version: "1.0".to_string(),
                features: vec![],
                optional: false,
                dev_dependency: false,
            },
        ];

        let result = detector.detect(&deps, &[], temp_path).await.unwrap();

        match result {
            ProjectType::Mixed(frameworks) => {
                assert!(frameworks.contains(&ProjectType::Tauri));
                assert!(frameworks.contains(&ProjectType::Leptos));
                // Tauri should be first (higher priority)
                assert_eq!(frameworks[0], ProjectType::Tauri);
            }
            _ => panic!("Expected Mixed project type, got {result:?}"),
        }
    }

    #[test]
    fn test_complex_use_statement_parsing() {
        let analyzer = FileAnalyzer::new();

        // Test glob import
        let import = analyzer.parse_use_statement("use std::*;").unwrap();
        assert_eq!(import.path, "std");
        assert_eq!(import.items, vec!["*"]);

        // Test simple alias
        let import = analyzer
            .parse_use_statement("use std::collections::HashMap as Map;")
            .unwrap();
        assert_eq!(import.path, "std::collections::HashMap");
        assert_eq!(import.alias, Some("Map".to_string()));

        // Test braced imports
        let import = analyzer
            .parse_use_statement("use std::{fs, io, collections::HashMap};")
            .unwrap();
        assert_eq!(import.path, "std");
        assert_eq!(import.items, vec!["fs", "io", "collections::HashMap"]);

        // Test complex braced imports with aliases
        let import = analyzer
            .parse_use_statement("use crate::module::{Item1, Item2 as Alias, Item3};")
            .unwrap();
        assert_eq!(import.path, "crate::module");
        assert_eq!(import.items, vec!["Item1", "Item2 as Alias", "Item3"]);

        // Test nested braces (complex case)
        let import = analyzer
            .parse_use_statement("use std::{fs, io::{self, Read, Write}};")
            .unwrap();
        assert_eq!(import.path, "std");
        assert_eq!(import.items, vec!["fs", "io::{self, Read, Write}"]);

        // Test simple import
        let import = analyzer
            .parse_use_statement("use std::collections::HashMap;")
            .unwrap();
        assert_eq!(import.path, "std::collections::HashMap");
        assert!(import.items.is_empty());
        assert!(import.alias.is_none());
    }
}