selfware 0.2.2

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

use crate::bm25::BM25Index;
use anyhow::Result;
use chrono::{DateTime, Utc};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

// Pre-compiled regexes for Rust symbol indexing (compiled once, reused across calls)
static FN_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?(async\s+)?fn\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static STRUCT_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?struct\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static ENUM_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?enum\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static TRAIT_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?trait\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static IMPL_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*impl(<.*?>)?\s+(\w+)").unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static CONST_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?const\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static TYPE_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?type\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static MACRO_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?macro_rules!\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});
static MOD_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(pub(\(.*?\))?\s+)?mod\s+(\w+)")
        .unwrap_or_else(|e| panic!("Invalid regex pattern: {e}"))
});

// TODO: Consider migrating to tokio::sync::RwLock if ProjectIntelligence methods become async.
// Currently all methods are synchronous, so std::sync::RwLock is correct and avoids
// requiring .await at every lock acquisition. Migration would require making refresh(),
// search(), index_files(), and all accessor call-sites async (~50+ changes).

/// Main intelligence hub coordinating all analysis
#[derive(Debug)]
pub struct ProjectIntelligence {
    /// Root directory being indexed
    root: PathBuf,
    /// Symbol index
    symbols: Arc<RwLock<SymbolIndex>>,
    /// Dependency graph
    dependencies: Arc<RwLock<DependencyGraph>>,
    /// Git state
    git_state: Arc<RwLock<GitState>>,
    /// File index
    files: Arc<RwLock<FileIndex>>,
    /// Pattern detector
    patterns: Arc<RwLock<PatternDetector>>,
    /// Last update time
    last_update: DateTime<Utc>,
}

/// Symbol types that can be indexed
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SymbolKind {
    Function,
    Struct,
    Enum,
    Trait,
    Impl,
    Const,
    Static,
    Type,
    Macro,
    Module,
}

impl SymbolKind {
    /// Icon for display
    pub fn icon(&self) -> &'static str {
        match self {
            SymbolKind::Function => "ƒ",
            SymbolKind::Struct => "",
            SymbolKind::Enum => "",
            SymbolKind::Trait => "",
            SymbolKind::Impl => "",
            SymbolKind::Const => "C",
            SymbolKind::Static => "S",
            SymbolKind::Type => "T",
            SymbolKind::Macro => "M",
            SymbolKind::Module => "",
        }
    }

    /// Color for display (ANSI code)
    pub fn color(&self) -> &'static str {
        match self {
            SymbolKind::Function => "\x1b[33m",                   // Yellow
            SymbolKind::Struct => "\x1b[36m",                     // Cyan
            SymbolKind::Enum => "\x1b[35m",                       // Magenta
            SymbolKind::Trait => "\x1b[34m",                      // Blue
            SymbolKind::Impl => "\x1b[32m",                       // Green
            SymbolKind::Const | SymbolKind::Static => "\x1b[31m", // Red
            SymbolKind::Type => "\x1b[94m",                       // Light blue
            SymbolKind::Macro => "\x1b[95m",                      // Light magenta
            SymbolKind::Module => "\x1b[37m",                     // White
        }
    }
}

/// A symbol found in the codebase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Symbol {
    /// Symbol name
    pub name: String,
    /// Symbol kind
    pub kind: SymbolKind,
    /// File containing this symbol
    pub file: PathBuf,
    /// Line number (1-indexed)
    pub line: usize,
    /// Column (1-indexed)
    pub column: usize,
    /// Full signature/declaration
    pub signature: String,
    /// Documentation comment if any
    pub doc: Option<String>,
    /// Visibility (pub, pub(crate), etc.)
    pub visibility: Visibility,
    /// Parent symbol (for nested items)
    pub parent: Option<String>,
}

impl Symbol {
    /// Create a new symbol
    pub fn new(name: String, kind: SymbolKind, file: PathBuf, line: usize) -> Self {
        Self {
            name,
            kind,
            file,
            line,
            column: 1,
            signature: String::new(),
            doc: None,
            visibility: Visibility::Private,
            parent: None,
        }
    }

    /// Set signature
    pub fn with_signature(mut self, signature: String) -> Self {
        self.signature = signature;
        self
    }

    /// Set documentation
    pub fn with_doc(mut self, doc: String) -> Self {
        self.doc = Some(doc);
        self
    }

    /// Set visibility
    pub fn with_visibility(mut self, visibility: Visibility) -> Self {
        self.visibility = visibility;
        self
    }

    /// Set parent
    pub fn with_parent(mut self, parent: String) -> Self {
        self.parent = Some(parent);
        self
    }

    /// Set column
    pub fn with_column(mut self, column: usize) -> Self {
        self.column = column;
        self
    }

    /// Format for display
    pub fn display(&self) -> String {
        format!(
            "{} {} {}:{}",
            self.kind.icon(),
            self.name,
            self.file.display(),
            self.line
        )
    }
}

/// Visibility of a symbol
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Visibility {
    #[default]
    Private,
    Pub,
    PubCrate,
    PubSuper,
    PubIn(String),
}

impl Visibility {
    /// Parse visibility from source
    pub fn parse(s: &str) -> Self {
        if s.starts_with("pub(crate)") {
            Visibility::PubCrate
        } else if s.starts_with("pub(super)") {
            Visibility::PubSuper
        } else if s.starts_with("pub(in") {
            // Extract path
            if let Some(start) = s.find("pub(in ") {
                if let Some(end) = s[start..].find(')') {
                    let path = s[start + 7..start + end].to_string();
                    return Visibility::PubIn(path);
                }
            }
            Visibility::Pub
        } else if s.starts_with("pub") {
            Visibility::Pub
        } else {
            Visibility::Private
        }
    }

    /// Is this public?
    pub fn is_public(&self) -> bool {
        matches!(self, Visibility::Pub)
    }
}

/// Symbol index for the project
#[derive(Debug, Default)]
pub struct SymbolIndex {
    /// All symbols by name
    by_name: HashMap<String, Vec<Symbol>>,
    /// Symbols by file
    by_file: HashMap<PathBuf, Vec<Symbol>>,
    /// Symbols by kind
    by_kind: HashMap<SymbolKind, Vec<Symbol>>,
    /// Total count
    count: usize,
    /// BM25 index for ranked search
    bm25: BM25Index,
}

impl SymbolIndex {
    /// Create new empty index
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a symbol to the index
    pub fn add(&mut self, symbol: Symbol) {
        // Build searchable text for BM25: name + signature + doc
        let searchable = format!(
            "{} {} {}",
            symbol.name,
            symbol.signature,
            symbol.doc.as_deref().unwrap_or("")
        );
        let doc_id = Self::make_doc_id(&symbol.file, symbol.line, &symbol.name);
        self.bm25.add(&doc_id, searchable);

        self.by_name
            .entry(symbol.name.clone())
            .or_default()
            .push(symbol.clone());
        self.by_file
            .entry(symbol.file.clone())
            .or_default()
            .push(symbol.clone());
        self.by_kind
            .entry(symbol.kind.clone())
            .or_default()
            .push(symbol);
        self.count += 1;
    }

    /// Search symbols using BM25 ranking
    ///
    /// Returns symbols ranked by relevance to the query.
    /// Uses BM25 for ranking with CamelCase and snake_case tokenization.
    pub fn search(&mut self, query: &str) -> Vec<&Symbol> {
        // Use BM25 for ranked search
        let bm25_results = self.bm25.search(query, 100);

        // Map BM25 results back to symbols
        let mut results = Vec::new();
        for result in bm25_results {
            // Parse doc_id using null-byte separator (handles paths with colons)
            if let Some((file_str, line, name)) = Self::parse_doc_id(&result.id) {
                if let Some(symbols) = self.by_name.get(name) {
                    // Find the specific symbol by file and line
                    for symbol in symbols {
                        if symbol.file.to_string_lossy() == file_str && symbol.line == line {
                            results.push(symbol);
                            break;
                        }
                    }
                }
            }
        }
        results
    }

    /// Search symbols using simple substring matching (legacy)
    ///
    /// Use `search()` for ranked results; this is for exact substring matching.
    pub fn search_contains(&self, query: &str) -> Vec<&Symbol> {
        let query_lower = query.to_lowercase();
        let mut results: Vec<_> = self
            .by_name
            .iter()
            .filter(|(name, _)| name.to_lowercase().contains(&query_lower))
            .flat_map(|(_, symbols)| symbols.iter())
            .collect();
        results.sort_by(|a, b| a.name.cmp(&b.name));
        results
    }

    /// Get symbols by exact name
    pub fn get(&self, name: &str) -> Option<&Vec<Symbol>> {
        self.by_name.get(name)
    }

    /// Get symbols in a file
    pub fn in_file(&self, file: &Path) -> Option<&Vec<Symbol>> {
        self.by_file.get(file)
    }

    /// Get symbols of a specific kind
    pub fn of_kind(&self, kind: &SymbolKind) -> Option<&Vec<Symbol>> {
        self.by_kind.get(kind)
    }

    /// Get all functions
    pub fn functions(&self) -> Vec<&Symbol> {
        self.by_kind
            .get(&SymbolKind::Function)
            .map(|v| v.iter().collect())
            .unwrap_or_default()
    }

    /// Get all structs
    pub fn structs(&self) -> Vec<&Symbol> {
        self.by_kind
            .get(&SymbolKind::Struct)
            .map(|v| v.iter().collect())
            .unwrap_or_default()
    }

    /// Total symbol count
    pub fn len(&self) -> usize {
        self.count
    }

    /// Is empty
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Clear the index
    pub fn clear(&mut self) {
        self.by_name.clear();
        self.by_file.clear();
        self.by_kind.clear();
        self.bm25.clear();
        self.count = 0;
    }

    /// Remove symbols from a file
    pub fn remove_file(&mut self, file: &Path) {
        if let Some(symbols) = self.by_file.remove(file) {
            let removed_count = symbols.len();
            for symbol in &symbols {
                // Remove from BM25 index
                let doc_id = Self::make_doc_id(&symbol.file, symbol.line, &symbol.name);
                self.bm25.remove_all(&doc_id);

                if let Some(by_name) = self.by_name.get_mut(&symbol.name) {
                    by_name.retain(|s| s.file != file);
                }
                if let Some(by_kind) = self.by_kind.get_mut(&symbol.kind) {
                    by_kind.retain(|s| s.file != file);
                }
            }
            self.count = self.count.saturating_sub(removed_count);
        }
    }

    /// Create a stable document ID for BM25 (uses \x00 as separator to avoid path issues)
    fn make_doc_id(file: &Path, line: usize, name: &str) -> String {
        format!("{}\x00{}\x00{}", file.display(), line, name)
    }

    /// Parse a document ID back into components
    fn parse_doc_id(doc_id: &str) -> Option<(&str, usize, &str)> {
        let parts: Vec<&str> = doc_id.splitn(3, '\x00').collect();
        if parts.len() == 3 {
            let line = parts[1].parse().ok()?;
            Some((parts[0], line, parts[2]))
        } else {
            None
        }
    }
}

/// Dependency information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dependency {
    /// Crate name
    pub name: String,
    /// Version requirement
    pub version: String,
    /// Features enabled
    pub features: Vec<String>,
    /// Is optional
    pub optional: bool,
    /// Is dev dependency
    pub dev: bool,
    /// Is build dependency
    pub build: bool,
}

impl Dependency {
    /// Create a new dependency
    pub fn new(name: String, version: String) -> Self {
        Self {
            name,
            version,
            features: Vec::new(),
            optional: false,
            dev: false,
            build: false,
        }
    }

    /// Add features
    pub fn with_features(mut self, features: Vec<String>) -> Self {
        self.features = features;
        self
    }

    /// Mark as optional
    pub fn optional(mut self) -> Self {
        self.optional = true;
        self
    }

    /// Mark as dev dependency
    pub fn dev(mut self) -> Self {
        self.dev = true;
        self
    }

    /// Mark as build dependency
    pub fn build(mut self) -> Self {
        self.build = true;
        self
    }
}

/// Dependency graph from Cargo.toml
#[derive(Debug, Default)]
pub struct DependencyGraph {
    /// Direct dependencies
    pub dependencies: Vec<Dependency>,
    /// Dev dependencies
    pub dev_dependencies: Vec<Dependency>,
    /// Build dependencies
    pub build_dependencies: Vec<Dependency>,
    /// Package name
    pub package_name: Option<String>,
    /// Package version
    pub package_version: Option<String>,
    /// Features defined
    pub features: HashMap<String, Vec<String>>,
}

impl DependencyGraph {
    /// Create new empty graph
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse from Cargo.toml content
    pub fn parse(content: &str) -> Result<Self> {
        let value: toml::Value = toml::from_str(content)?;
        let mut graph = Self::new();

        // Parse package info
        if let Some(package) = value.get("package") {
            if let Some(name) = package.get("name").and_then(|v| v.as_str()) {
                graph.package_name = Some(name.to_string());
            }
            if let Some(version) = package.get("version").and_then(|v| v.as_str()) {
                graph.package_version = Some(version.to_string());
            }
        }

        // Parse dependencies
        if let Some(deps) = value.get("dependencies") {
            graph.dependencies = Self::parse_deps(deps)?;
        }

        // Parse dev-dependencies
        if let Some(deps) = value.get("dev-dependencies") {
            graph.dev_dependencies = Self::parse_deps(deps)?;
            for dep in &mut graph.dev_dependencies {
                dep.dev = true;
            }
        }

        // Parse build-dependencies
        if let Some(deps) = value.get("build-dependencies") {
            graph.build_dependencies = Self::parse_deps(deps)?;
            for dep in &mut graph.build_dependencies {
                dep.build = true;
            }
        }

        // Parse features
        if let Some(features) = value.get("features").and_then(|v| v.as_table()) {
            for (name, value) in features {
                if let Some(arr) = value.as_array() {
                    let deps: Vec<String> = arr
                        .iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect();
                    graph.features.insert(name.clone(), deps);
                }
            }
        }

        Ok(graph)
    }

    /// Parse dependencies section
    fn parse_deps(deps: &toml::Value) -> Result<Vec<Dependency>> {
        let mut result = Vec::new();

        if let Some(table) = deps.as_table() {
            for (name, value) in table {
                let dep = match value {
                    toml::Value::String(version) => Dependency::new(name.clone(), version.clone()),
                    toml::Value::Table(t) => {
                        let version = t
                            .get("version")
                            .and_then(|v| v.as_str())
                            .unwrap_or("*")
                            .to_string();
                        let mut dep = Dependency::new(name.clone(), version);

                        if let Some(features) = t.get("features").and_then(|v| v.as_array()) {
                            dep.features = features
                                .iter()
                                .filter_map(|v| v.as_str().map(String::from))
                                .collect();
                        }

                        if let Some(optional) = t.get("optional").and_then(|v| v.as_bool()) {
                            dep.optional = optional;
                        }

                        dep
                    }
                    _ => continue,
                };
                result.push(dep);
            }
        }

        Ok(result)
    }

    /// Get all dependencies (direct + dev + build)
    pub fn all(&self) -> Vec<&Dependency> {
        self.dependencies
            .iter()
            .chain(self.dev_dependencies.iter())
            .chain(self.build_dependencies.iter())
            .collect()
    }

    /// Find dependency by name
    pub fn find(&self, name: &str) -> Option<&Dependency> {
        self.all().into_iter().find(|d| d.name == name)
    }

    /// Count all dependencies
    pub fn count(&self) -> usize {
        self.dependencies.len() + self.dev_dependencies.len() + self.build_dependencies.len()
    }
}

/// Git state for the project
#[derive(Debug, Default)]
pub struct GitState {
    /// Current branch
    pub branch: Option<String>,
    /// Current commit hash
    pub commit: Option<String>,
    /// Is the repo dirty (uncommitted changes)
    pub dirty: bool,
    /// Untracked files
    pub untracked: Vec<PathBuf>,
    /// Modified files
    pub modified: Vec<PathBuf>,
    /// Staged files
    pub staged: Vec<PathBuf>,
    /// Remote tracking branch
    pub remote: Option<String>,
    /// Commits ahead of remote
    pub ahead: usize,
    /// Commits behind remote
    pub behind: usize,
}

impl GitState {
    /// Create new state
    pub fn new() -> Self {
        Self::default()
    }

    /// Update from git repository
    pub fn update(&mut self, repo_path: &Path) -> Result<()> {
        let repo = git2::Repository::open(repo_path)?;

        // Get current branch
        if let Ok(head) = repo.head() {
            if head.is_branch() {
                self.branch = head.shorthand().map(String::from);
            }
            if let Some(oid) = head.target() {
                self.commit = Some(oid.to_string());
            }
        }

        // Get status
        let statuses = repo.statuses(None)?;
        self.untracked.clear();
        self.modified.clear();
        self.staged.clear();

        for entry in statuses.iter() {
            if let Some(path) = entry.path() {
                let path = PathBuf::from(path);
                let status = entry.status();

                if status.is_wt_new() {
                    self.untracked.push(path.clone());
                }
                if status.is_wt_modified() || status.is_wt_deleted() {
                    self.modified.push(path.clone());
                }
                if status.is_index_new() || status.is_index_modified() || status.is_index_deleted()
                {
                    self.staged.push(path);
                }
            }
        }

        self.dirty =
            !self.untracked.is_empty() || !self.modified.is_empty() || !self.staged.is_empty();

        Ok(())
    }

    /// Get status summary
    pub fn summary(&self) -> String {
        let mut parts = Vec::new();

        if let Some(ref branch) = self.branch {
            parts.push(format!("on {}", branch));
        }

        if self.dirty {
            let changes = self.modified.len() + self.staged.len();
            parts.push(format!("{} changes", changes));
        }

        if !self.untracked.is_empty() {
            parts.push(format!("{} untracked", self.untracked.len()));
        }

        if self.ahead > 0 {
            parts.push(format!("{}", self.ahead));
        }

        if self.behind > 0 {
            parts.push(format!("{}", self.behind));
        }

        parts.join(", ")
    }
}

/// File index entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEntry {
    /// File path
    pub path: PathBuf,
    /// File size in bytes
    pub size: u64,
    /// Last modified time
    pub modified: DateTime<Utc>,
    /// File type/extension
    pub extension: Option<String>,
    /// Language detected
    pub language: Option<String>,
    /// Line count
    pub lines: Option<usize>,
}

impl FileEntry {
    /// Create from path
    pub fn from_path(path: PathBuf) -> Result<Self> {
        let metadata = std::fs::metadata(&path)?;
        let modified = metadata.modified()?.into();
        let extension = path.extension().map(|e| e.to_string_lossy().to_string());
        let language = extension.as_ref().and_then(|e| detect_language(e));

        Ok(Self {
            path,
            size: metadata.len(),
            modified,
            extension,
            language,
            lines: None,
        })
    }

    /// Count lines in file
    pub fn count_lines(&mut self) -> Result<usize> {
        let content = std::fs::read_to_string(&self.path)?;
        let count = content.lines().count();
        self.lines = Some(count);
        Ok(count)
    }
}

/// Detect language from extension
pub fn detect_language(ext: &str) -> Option<String> {
    let lang = match ext.to_lowercase().as_str() {
        "rs" => "Rust",
        "py" => "Python",
        "js" => "JavaScript",
        "ts" => "TypeScript",
        "tsx" | "jsx" => "React",
        "go" => "Go",
        "java" => "Java",
        "c" | "h" => "C",
        "cpp" | "hpp" | "cc" | "cxx" => "C++",
        "rb" => "Ruby",
        "php" => "PHP",
        "swift" => "Swift",
        "kt" | "kts" => "Kotlin",
        "scala" => "Scala",
        "hs" => "Haskell",
        "ml" | "mli" => "OCaml",
        "ex" | "exs" => "Elixir",
        "erl" | "hrl" => "Erlang",
        "clj" | "cljs" => "Clojure",
        "lua" => "Lua",
        "r" => "R",
        "sql" => "SQL",
        "sh" | "bash" | "zsh" => "Shell",
        "md" | "markdown" => "Markdown",
        "json" => "JSON",
        "yaml" | "yml" => "YAML",
        "toml" => "TOML",
        "xml" => "XML",
        "html" | "htm" => "HTML",
        "css" => "CSS",
        "scss" | "sass" => "SASS",
        "vue" => "Vue",
        "svelte" => "Svelte",
        _ => return None,
    };
    Some(lang.to_string())
}

/// File index for the project
#[derive(Debug, Default)]
pub struct FileIndex {
    /// All files
    files: HashMap<PathBuf, FileEntry>,
    /// Files by extension
    by_extension: HashMap<String, Vec<PathBuf>>,
    /// Files by language
    by_language: HashMap<String, Vec<PathBuf>>,
}

impl FileIndex {
    /// Create new index
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a file to the index
    pub fn add(&mut self, entry: FileEntry) {
        let path = entry.path.clone();

        if let Some(ext) = &entry.extension {
            self.by_extension
                .entry(ext.clone())
                .or_default()
                .push(path.clone());
        }

        if let Some(lang) = &entry.language {
            self.by_language
                .entry(lang.clone())
                .or_default()
                .push(path.clone());
        }

        self.files.insert(path, entry);
    }

    /// Get file by path
    pub fn get(&self, path: &Path) -> Option<&FileEntry> {
        self.files.get(path)
    }

    /// Get files by extension
    pub fn by_extension(&self, ext: &str) -> Vec<&FileEntry> {
        self.by_extension
            .get(ext)
            .map(|paths| paths.iter().filter_map(|p| self.files.get(p)).collect())
            .unwrap_or_default()
    }

    /// Get files by language
    pub fn by_language(&self, lang: &str) -> Vec<&FileEntry> {
        self.by_language
            .get(lang)
            .map(|paths| paths.iter().filter_map(|p| self.files.get(p)).collect())
            .unwrap_or_default()
    }

    /// Remove file from index
    pub fn remove(&mut self, path: &Path) {
        if let Some(entry) = self.files.remove(path) {
            if let Some(ext) = &entry.extension {
                if let Some(paths) = self.by_extension.get_mut(ext) {
                    paths.retain(|p| p != path);
                }
            }
            if let Some(lang) = &entry.language {
                if let Some(paths) = self.by_language.get_mut(lang) {
                    paths.retain(|p| p != path);
                }
            }
        }
    }

    /// Total file count
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// Is empty
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Clear index
    pub fn clear(&mut self) {
        self.files.clear();
        self.by_extension.clear();
        self.by_language.clear();
    }

    /// Get language statistics
    pub fn language_stats(&self) -> HashMap<String, usize> {
        self.by_language
            .iter()
            .map(|(lang, paths)| (lang.clone(), paths.len()))
            .collect()
    }
}

/// Code pattern detection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodePattern {
    /// Pattern name
    pub name: String,
    /// Description
    pub description: String,
    /// Category
    pub category: PatternCategory,
    /// Locations where this pattern was found
    pub locations: Vec<PatternLocation>,
}

impl CodePattern {
    /// Create new pattern
    pub fn new(name: String, description: String, category: PatternCategory) -> Self {
        Self {
            name,
            description,
            category,
            locations: Vec::new(),
        }
    }

    /// Add a location
    pub fn add_location(&mut self, file: PathBuf, line: usize, snippet: String) {
        self.locations.push(PatternLocation {
            file,
            line,
            snippet,
        });
    }
}

/// Pattern category
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PatternCategory {
    Design,      // Design patterns (singleton, factory, etc.)
    AntiPattern, // Bad practices
    Convention,  // Coding conventions
    Security,    // Security-related patterns
    Performance, // Performance patterns
    Testing,     // Testing patterns
}

impl PatternCategory {
    /// Icon for category
    pub fn icon(&self) -> &'static str {
        match self {
            PatternCategory::Design => "🏗️",
            PatternCategory::AntiPattern => "⚠️",
            PatternCategory::Convention => "📏",
            PatternCategory::Security => "🔒",
            PatternCategory::Performance => "",
            PatternCategory::Testing => "🧪",
        }
    }
}

/// Location of a pattern match
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternLocation {
    pub file: PathBuf,
    pub line: usize,
    pub snippet: String,
}

/// Pattern detector for code analysis
#[derive(Debug, Default)]
pub struct PatternDetector {
    /// Detected patterns
    patterns: Vec<CodePattern>,
    /// Pattern rules
    rules: Vec<PatternRule>,
}

/// Rule for detecting patterns
#[derive(Debug, Clone)]
pub struct PatternRule {
    /// Pattern name
    pub name: String,
    /// Category
    pub category: PatternCategory,
    /// Description
    pub description: String,
    /// Regex pattern
    pub regex: Regex,
}

impl PatternRule {
    /// Create a new rule
    pub fn new(
        name: &str,
        category: PatternCategory,
        description: &str,
        pattern: &str,
    ) -> Result<Self> {
        Ok(Self {
            name: name.to_string(),
            category,
            description: description.to_string(),
            regex: Regex::new(pattern)?,
        })
    }
}

impl PatternDetector {
    /// Create new detector with default rules
    pub fn new() -> Self {
        let mut detector = Self::default();
        detector.add_default_rules();
        detector
    }

    /// Add default pattern rules
    fn add_default_rules(&mut self) {
        // Unwrap usage (potential panic)
        if let Ok(rule) = PatternRule::new(
            "unwrap_usage",
            PatternCategory::AntiPattern,
            "Direct .unwrap() calls can panic",
            r"\.unwrap\(\)",
        ) {
            self.rules.push(rule);
        }

        // TODO comments
        if let Ok(rule) = PatternRule::new(
            "todo_comment",
            PatternCategory::Convention,
            "TODO comments indicate unfinished work",
            r"(?i)//\s*TODO:",
        ) {
            self.rules.push(rule);
        }

        // FIXME comments
        if let Ok(rule) = PatternRule::new(
            "fixme_comment",
            PatternCategory::Convention,
            "FIXME comments indicate bugs or issues",
            r"(?i)//\s*FIXME:",
        ) {
            self.rules.push(rule);
        }

        // Unsafe blocks
        if let Ok(rule) = PatternRule::new(
            "unsafe_block",
            PatternCategory::Security,
            "Unsafe blocks require careful review",
            r"unsafe\s*\{",
        ) {
            self.rules.push(rule);
        }

        // Clone in loop
        if let Ok(rule) = PatternRule::new(
            "clone_in_loop",
            PatternCategory::Performance,
            "Cloning in loops can be expensive",
            r"for\s+.*\{[^}]*\.clone\(\)",
        ) {
            self.rules.push(rule);
        }

        // Test function
        if let Ok(rule) = PatternRule::new(
            "test_function",
            PatternCategory::Testing,
            "Test functions",
            r"#\[test\]",
        ) {
            self.rules.push(rule);
        }
    }

    /// Analyze content for patterns
    pub fn analyze(&mut self, file: &Path, content: &str) {
        for rule in &self.rules {
            for (line_num, line) in content.lines().enumerate() {
                if rule.regex.is_match(line) {
                    // Find or create pattern
                    let pattern = self.patterns.iter_mut().find(|p| p.name == rule.name);

                    if let Some(pattern) = pattern {
                        pattern.add_location(file.to_path_buf(), line_num + 1, line.to_string());
                    } else {
                        let mut pattern = CodePattern::new(
                            rule.name.clone(),
                            rule.description.clone(),
                            rule.category.clone(),
                        );
                        pattern.add_location(file.to_path_buf(), line_num + 1, line.to_string());
                        self.patterns.push(pattern);
                    }
                }
            }
        }
    }

    /// Get all detected patterns
    pub fn patterns(&self) -> &[CodePattern] {
        &self.patterns
    }

    /// Get patterns by category
    pub fn by_category(&self, category: &PatternCategory) -> Vec<&CodePattern> {
        self.patterns
            .iter()
            .filter(|p| &p.category == category)
            .collect()
    }

    /// Get anti-patterns (issues to fix)
    pub fn anti_patterns(&self) -> Vec<&CodePattern> {
        self.by_category(&PatternCategory::AntiPattern)
    }

    /// Clear detected patterns
    pub fn clear(&mut self) {
        self.patterns.clear();
    }

    /// Add custom rule
    pub fn add_rule(&mut self, rule: PatternRule) {
        self.rules.push(rule);
    }

    /// Summary of findings
    pub fn summary(&self) -> HashMap<PatternCategory, usize> {
        let mut result = HashMap::new();
        for pattern in &self.patterns {
            *result.entry(pattern.category.clone()).or_insert(0) += pattern.locations.len();
        }
        result
    }
}

impl ProjectIntelligence {
    /// Create new intelligence for a project root
    pub fn new(root: PathBuf) -> Self {
        Self {
            root,
            symbols: Arc::new(RwLock::new(SymbolIndex::new())),
            dependencies: Arc::new(RwLock::new(DependencyGraph::new())),
            git_state: Arc::new(RwLock::new(GitState::new())),
            files: Arc::new(RwLock::new(FileIndex::new())),
            patterns: Arc::new(RwLock::new(PatternDetector::new())),
            last_update: Utc::now(),
        }
    }

    /// Get project root
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Get symbol index
    pub fn symbols(&self) -> &Arc<RwLock<SymbolIndex>> {
        &self.symbols
    }

    /// Get dependency graph
    pub fn dependencies(&self) -> &Arc<RwLock<DependencyGraph>> {
        &self.dependencies
    }

    /// Get git state
    pub fn git_state(&self) -> &Arc<RwLock<GitState>> {
        &self.git_state
    }

    /// Get file index
    pub fn files(&self) -> &Arc<RwLock<FileIndex>> {
        &self.files
    }

    /// Get pattern detector
    pub fn patterns(&self) -> &Arc<RwLock<PatternDetector>> {
        &self.patterns
    }

    /// Refresh all indexes
    pub fn refresh(&mut self) -> Result<()> {
        // Update git state
        if let Ok(mut git) = self.git_state.write() {
            let _ = git.update(&self.root);
        }

        // Parse Cargo.toml
        let cargo_path = self.root.join("Cargo.toml");
        if cargo_path.exists() {
            if let Ok(content) = std::fs::read_to_string(&cargo_path) {
                if let Ok(deps) = DependencyGraph::parse(&content) {
                    if let Ok(mut graph) = self.dependencies.write() {
                        *graph = deps;
                    }
                }
            }
        }

        // Index files
        self.index_files()?;

        self.last_update = Utc::now();
        Ok(())
    }

    /// Index all files in the project
    fn index_files(&mut self) -> Result<()> {
        use walkdir::WalkDir;

        let mut file_index = self
            .files
            .write()
            .map_err(|_| anyhow::anyhow!("Lock error"))?;
        let mut symbol_index = self
            .symbols
            .write()
            .map_err(|_| anyhow::anyhow!("Lock error"))?;
        let mut pattern_detector = self
            .patterns
            .write()
            .map_err(|_| anyhow::anyhow!("Lock error"))?;

        file_index.clear();
        symbol_index.clear();
        pattern_detector.clear();

        for entry in WalkDir::new(&self.root)
            .into_iter()
            .filter_entry(|e| {
                let name = e.file_name().to_string_lossy();
                !name.starts_with('.') && name != "target" && name != "node_modules"
            })
            .filter_map(|e| e.ok())
        {
            if entry.file_type().is_file() {
                let path = entry.path().to_path_buf();
                if let Ok(file_entry) = FileEntry::from_path(path.clone()) {
                    file_index.add(file_entry);

                    // Index Rust files for symbols and patterns
                    if path.extension().map(|e| e == "rs").unwrap_or(false) {
                        if let Ok(content) = std::fs::read_to_string(&path) {
                            self.index_rust_symbols(&mut symbol_index, &path, &content);
                            pattern_detector.analyze(&path, &content);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Index symbols from Rust source
    fn index_rust_symbols(&self, index: &mut SymbolIndex, file: &Path, content: &str) {
        for (line_num, line) in content.lines().enumerate() {
            let line_num = line_num + 1;

            // Functions
            if let Some(caps) = FN_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(4) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Function,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Structs
            else if let Some(caps) = STRUCT_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Struct,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Enums
            else if let Some(caps) = ENUM_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Enum,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Traits
            else if let Some(caps) = TRAIT_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Trait,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Impls
            else if let Some(caps) = IMPL_REGEX.captures(line) {
                if let Some(name_match) = caps.get(2) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Impl,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Constants
            else if let Some(caps) = CONST_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Const,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Type aliases
            else if let Some(caps) = TYPE_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Type,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Macros
            else if let Some(caps) = MACRO_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    let symbol = Symbol::new(
                        name_match.as_str().to_string(),
                        SymbolKind::Macro,
                        file.to_path_buf(),
                        line_num,
                    )
                    .with_visibility(vis)
                    .with_signature(line.trim().to_string());
                    index.add(symbol);
                }
            }
            // Modules
            else if let Some(caps) = MOD_REGEX.captures(line) {
                let vis = Visibility::parse(caps.get(1).map(|m| m.as_str()).unwrap_or(""));
                if let Some(name_match) = caps.get(3) {
                    // Skip module declarations that just reference other files
                    if !line.contains(';') || line.contains('{') {
                        let symbol = Symbol::new(
                            name_match.as_str().to_string(),
                            SymbolKind::Module,
                            file.to_path_buf(),
                            line_num,
                        )
                        .with_visibility(vis)
                        .with_signature(line.trim().to_string());
                        index.add(symbol);
                    }
                }
            }
        }
    }

    /// Get last update time
    pub fn last_update(&self) -> DateTime<Utc> {
        self.last_update
    }

    /// Quick search across all indexes using BM25 ranking
    pub fn search(&self, query: &str) -> Vec<SearchResult> {
        let mut results = Vec::new();

        // Search symbols (needs write lock for BM25 lazy rebuild)
        if let Ok(mut symbols) = self.symbols.write() {
            for symbol in symbols.search(query) {
                results.push(SearchResult::Symbol(symbol.clone()));
            }
        }

        // Search files
        if let Ok(files) = self.files.read() {
            let query_lower = query.to_lowercase();
            for (path, entry) in &files.files {
                if path.to_string_lossy().to_lowercase().contains(&query_lower) {
                    results.push(SearchResult::File(entry.clone()));
                }
            }
        }

        results
    }
}

/// Search result types
#[derive(Debug, Clone)]
pub enum SearchResult {
    Symbol(Symbol),
    File(FileEntry),
    Pattern(CodePattern),
}

impl SearchResult {
    /// Display the result
    pub fn display(&self) -> String {
        match self {
            SearchResult::Symbol(s) => s.display(),
            SearchResult::File(f) => format!("📄 {}", f.path.display()),
            SearchResult::Pattern(p) => format!(
                "{} {} ({} matches)",
                p.category.icon(),
                p.name,
                p.locations.len()
            ),
        }
    }
}

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

    #[test]
    fn test_symbol_kind_icons() {
        assert_eq!(SymbolKind::Function.icon(), "ƒ");
        assert_eq!(SymbolKind::Struct.icon(), "");
        assert_eq!(SymbolKind::Enum.icon(), "");
        assert_eq!(SymbolKind::Trait.icon(), "");
        assert_eq!(SymbolKind::Impl.icon(), "");
        assert_eq!(SymbolKind::Const.icon(), "C");
        assert_eq!(SymbolKind::Static.icon(), "S");
        assert_eq!(SymbolKind::Type.icon(), "T");
        assert_eq!(SymbolKind::Macro.icon(), "M");
        assert_eq!(SymbolKind::Module.icon(), "");
    }

    #[test]
    fn test_symbol_kind_colors() {
        assert!(SymbolKind::Function.color().contains("33"));
        assert!(SymbolKind::Struct.color().contains("36"));
    }

    #[test]
    fn test_symbol_creation() {
        let sym = Symbol::new(
            "test_fn".to_string(),
            SymbolKind::Function,
            PathBuf::from("src/lib.rs"),
            10,
        );
        assert_eq!(sym.name, "test_fn");
        assert_eq!(sym.kind, SymbolKind::Function);
        assert_eq!(sym.line, 10);
    }

    #[test]
    fn test_symbol_builder() {
        let sym = Symbol::new(
            "test".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        )
        .with_signature("fn test() -> Result<()>".to_string())
        .with_doc("Test function".to_string())
        .with_visibility(Visibility::Pub)
        .with_parent("TestStruct".to_string())
        .with_column(5);

        assert_eq!(sym.signature, "fn test() -> Result<()>");
        assert_eq!(sym.doc, Some("Test function".to_string()));
        assert_eq!(sym.visibility, Visibility::Pub);
        assert_eq!(sym.parent, Some("TestStruct".to_string()));
        assert_eq!(sym.column, 5);
    }

    #[test]
    fn test_symbol_display() {
        let sym = Symbol::new(
            "my_func".to_string(),
            SymbolKind::Function,
            PathBuf::from("src/lib.rs"),
            42,
        );
        let display = sym.display();
        assert!(display.contains("ƒ"));
        assert!(display.contains("my_func"));
        assert!(display.contains("42"));
    }

    #[test]
    fn test_visibility_parse() {
        assert_eq!(Visibility::parse("pub fn"), Visibility::Pub);
        assert_eq!(Visibility::parse("pub(crate) fn"), Visibility::PubCrate);
        assert_eq!(Visibility::parse("pub(super) fn"), Visibility::PubSuper);
        assert_eq!(Visibility::parse("fn"), Visibility::Private);
    }

    #[test]
    fn test_visibility_is_public() {
        assert!(Visibility::Pub.is_public());
        assert!(!Visibility::Private.is_public());
        assert!(!Visibility::PubCrate.is_public());
    }

    #[test]
    fn test_visibility_default() {
        let v: Visibility = Default::default();
        assert_eq!(v, Visibility::Private);
    }

    #[test]
    fn test_symbol_index_add_search() {
        let mut index = SymbolIndex::new();
        index.add(Symbol::new(
            "test_function".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        ));
        index.add(Symbol::new(
            "TestStruct".to_string(),
            SymbolKind::Struct,
            PathBuf::from("test.rs"),
            10,
        ));

        assert_eq!(index.len(), 2);
        assert!(!index.is_empty());

        let results = index.search("test");
        assert_eq!(results.len(), 2);

        let results = index.search("Struct");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_symbol_index_get() {
        let mut index = SymbolIndex::new();
        index.add(Symbol::new(
            "my_fn".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        ));

        assert!(index.get("my_fn").is_some());
        assert!(index.get("nonexistent").is_none());
    }

    #[test]
    fn test_symbol_index_in_file() {
        let mut index = SymbolIndex::new();
        let path = PathBuf::from("src/lib.rs");
        index.add(Symbol::new(
            "fn1".to_string(),
            SymbolKind::Function,
            path.clone(),
            1,
        ));
        index.add(Symbol::new(
            "fn2".to_string(),
            SymbolKind::Function,
            path.clone(),
            5,
        ));

        let symbols = index.in_file(&path).unwrap();
        assert_eq!(symbols.len(), 2);
    }

    #[test]
    fn test_symbol_index_of_kind() {
        let mut index = SymbolIndex::new();
        index.add(Symbol::new(
            "fn1".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        ));
        index.add(Symbol::new(
            "Struct1".to_string(),
            SymbolKind::Struct,
            PathBuf::from("test.rs"),
            5,
        ));

        let funcs = index.of_kind(&SymbolKind::Function).unwrap();
        assert_eq!(funcs.len(), 1);
    }

    #[test]
    fn test_symbol_index_functions_structs() {
        let mut index = SymbolIndex::new();
        index.add(Symbol::new(
            "fn1".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        ));
        index.add(Symbol::new(
            "Struct1".to_string(),
            SymbolKind::Struct,
            PathBuf::from("test.rs"),
            5,
        ));

        assert_eq!(index.functions().len(), 1);
        assert_eq!(index.structs().len(), 1);
    }

    #[test]
    fn test_symbol_index_remove_file() {
        let mut index = SymbolIndex::new();
        let path = PathBuf::from("test.rs");
        index.add(Symbol::new(
            "fn1".to_string(),
            SymbolKind::Function,
            path.clone(),
            1,
        ));
        index.add(Symbol::new(
            "fn2".to_string(),
            SymbolKind::Function,
            path.clone(),
            5,
        ));

        assert_eq!(index.len(), 2);
        index.remove_file(&path);
        assert_eq!(index.len(), 0);
    }

    #[test]
    fn test_symbol_index_clear() {
        let mut index = SymbolIndex::new();
        index.add(Symbol::new(
            "fn1".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        ));
        index.clear();
        assert!(index.is_empty());
    }

    #[test]
    fn test_dependency_creation() {
        let dep = Dependency::new("serde".to_string(), "1.0".to_string());
        assert_eq!(dep.name, "serde");
        assert_eq!(dep.version, "1.0");
        assert!(!dep.optional);
        assert!(!dep.dev);
        assert!(!dep.build);
    }

    #[test]
    fn test_dependency_builder() {
        let dep = Dependency::new("tokio".to_string(), "1.0".to_string())
            .with_features(vec!["full".to_string()])
            .optional()
            .dev();

        assert!(dep.optional);
        assert!(dep.dev);
        assert_eq!(dep.features, vec!["full".to_string()]);
    }

    #[test]
    fn test_dependency_build() {
        let dep = Dependency::new("proc-macro2".to_string(), "1.0".to_string()).build();
        assert!(dep.build);
    }

    #[test]
    fn test_dependency_graph_parse() {
        let toml_content = r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
serde = "1.0"
tokio = { version = "1.35", features = ["full"] }

[dev-dependencies]
tempfile = "3.9"

[features]
default = []
full = ["tokio/full"]
"#;

        let graph = DependencyGraph::parse(toml_content).unwrap();
        assert_eq!(graph.package_name, Some("test".to_string()));
        assert_eq!(graph.package_version, Some("0.1.0".to_string()));
        assert_eq!(graph.dependencies.len(), 2);
        assert_eq!(graph.dev_dependencies.len(), 1);
        assert!(graph.features.contains_key("full"));
    }

    #[test]
    fn test_dependency_graph_find() {
        let toml_content = r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
serde = "1.0"
"#;

        let graph = DependencyGraph::parse(toml_content).unwrap();
        assert!(graph.find("serde").is_some());
        assert!(graph.find("nonexistent").is_none());
    }

    #[test]
    fn test_dependency_graph_count() {
        let toml_content = r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
a = "1.0"
b = "1.0"

[dev-dependencies]
c = "1.0"
"#;

        let graph = DependencyGraph::parse(toml_content).unwrap();
        assert_eq!(graph.count(), 3);
    }

    #[test]
    fn test_git_state_new() {
        let state = GitState::new();
        assert!(state.branch.is_none());
        assert!(state.commit.is_none());
        assert!(!state.dirty);
    }

    #[test]
    fn test_git_state_summary() {
        let mut state = GitState::new();
        state.branch = Some("main".to_string());
        state.dirty = true;
        state.modified = vec![PathBuf::from("file.rs")];
        state.ahead = 2;

        let summary = state.summary();
        assert!(summary.contains("main"));
        assert!(summary.contains("changes"));
        assert!(summary.contains("↑2"));
    }

    #[test]
    fn test_detect_language() {
        assert_eq!(detect_language("rs"), Some("Rust".to_string()));
        assert_eq!(detect_language("py"), Some("Python".to_string()));
        assert_eq!(detect_language("js"), Some("JavaScript".to_string()));
        assert_eq!(detect_language("ts"), Some("TypeScript".to_string()));
        assert_eq!(detect_language("go"), Some("Go".to_string()));
        assert_eq!(detect_language("unknown"), None);
    }

    #[test]
    fn test_detect_language_case_insensitive() {
        assert_eq!(detect_language("RS"), Some("Rust".to_string()));
        assert_eq!(detect_language("Py"), Some("Python".to_string()));
    }

    #[test]
    fn test_file_entry_from_path() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.rs");
        std::fs::write(&file_path, "fn main() {}").unwrap();

        let entry = FileEntry::from_path(file_path).unwrap();
        assert_eq!(entry.extension, Some("rs".to_string()));
        assert_eq!(entry.language, Some("Rust".to_string()));
        assert!(entry.size > 0);
    }

    #[test]
    fn test_file_entry_count_lines() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.rs");
        std::fs::write(&file_path, "line1\nline2\nline3").unwrap();

        let mut entry = FileEntry::from_path(file_path).unwrap();
        let count = entry.count_lines().unwrap();
        assert_eq!(count, 3);
        assert_eq!(entry.lines, Some(3));
    }

    #[test]
    fn test_file_index_add_get() {
        let mut index = FileIndex::new();
        let entry = FileEntry {
            path: PathBuf::from("src/lib.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        };

        index.add(entry);
        assert_eq!(index.len(), 1);
        assert!(index.get(Path::new("src/lib.rs")).is_some());
    }

    #[test]
    fn test_file_index_by_extension() {
        let mut index = FileIndex::new();
        index.add(FileEntry {
            path: PathBuf::from("a.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        });
        index.add(FileEntry {
            path: PathBuf::from("b.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        });

        let rust_files = index.by_extension("rs");
        assert_eq!(rust_files.len(), 2);
    }

    #[test]
    fn test_file_index_by_language() {
        let mut index = FileIndex::new();
        index.add(FileEntry {
            path: PathBuf::from("a.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        });

        let rust_files = index.by_language("Rust");
        assert_eq!(rust_files.len(), 1);
    }

    #[test]
    fn test_file_index_remove() {
        let mut index = FileIndex::new();
        let path = PathBuf::from("test.rs");
        index.add(FileEntry {
            path: path.clone(),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        });

        assert_eq!(index.len(), 1);
        index.remove(&path);
        assert_eq!(index.len(), 0);
    }

    #[test]
    fn test_file_index_clear() {
        let mut index = FileIndex::new();
        index.add(FileEntry {
            path: PathBuf::from("test.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        });

        index.clear();
        assert!(index.is_empty());
    }

    #[test]
    fn test_file_index_language_stats() {
        let mut index = FileIndex::new();
        index.add(FileEntry {
            path: PathBuf::from("a.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        });
        index.add(FileEntry {
            path: PathBuf::from("b.py"),
            size: 100,
            modified: Utc::now(),
            extension: Some("py".to_string()),
            language: Some("Python".to_string()),
            lines: None,
        });

        let stats = index.language_stats();
        assert_eq!(stats.get("Rust"), Some(&1));
        assert_eq!(stats.get("Python"), Some(&1));
    }

    #[test]
    fn test_pattern_category_icons() {
        assert_eq!(PatternCategory::Design.icon(), "🏗️");
        assert_eq!(PatternCategory::AntiPattern.icon(), "⚠️");
        assert_eq!(PatternCategory::Convention.icon(), "📏");
        assert_eq!(PatternCategory::Security.icon(), "🔒");
        assert_eq!(PatternCategory::Performance.icon(), "");
        assert_eq!(PatternCategory::Testing.icon(), "🧪");
    }

    #[test]
    fn test_code_pattern_creation() {
        let mut pattern = CodePattern::new(
            "unwrap_usage".to_string(),
            "Direct unwrap calls".to_string(),
            PatternCategory::AntiPattern,
        );

        pattern.add_location(PathBuf::from("test.rs"), 10, ".unwrap()".to_string());
        assert_eq!(pattern.locations.len(), 1);
    }

    #[test]
    fn test_pattern_rule_creation() {
        let rule = PatternRule::new(
            "test_rule",
            PatternCategory::Convention,
            "Test description",
            r"fn\s+test",
        )
        .unwrap();

        assert_eq!(rule.name, "test_rule");
        assert!(rule.regex.is_match("fn test()"));
    }

    #[test]
    fn test_pattern_detector_new() {
        let detector = PatternDetector::new();
        assert!(!detector.rules.is_empty());
    }

    #[test]
    fn test_pattern_detector_analyze() {
        let mut detector = PatternDetector::new();
        let content = r#"
fn main() {
    let x = Some(1).unwrap();
    // TODO: fix this
}
"#;
        detector.analyze(Path::new("test.rs"), content);

        let patterns = detector.patterns();
        assert!(!patterns.is_empty());
    }

    #[test]
    fn test_pattern_detector_by_category() {
        let mut detector = PatternDetector::new();
        let content = "let x = val.unwrap();";
        detector.analyze(Path::new("test.rs"), content);

        let anti = detector.by_category(&PatternCategory::AntiPattern);
        assert!(!anti.is_empty());
    }

    #[test]
    fn test_pattern_detector_anti_patterns() {
        let mut detector = PatternDetector::new();
        detector.analyze(Path::new("test.rs"), ".unwrap()");

        let anti = detector.anti_patterns();
        assert!(!anti.is_empty());
    }

    #[test]
    fn test_pattern_detector_clear() {
        let mut detector = PatternDetector::new();
        detector.analyze(Path::new("test.rs"), ".unwrap()");
        detector.clear();
        assert!(detector.patterns().is_empty());
    }

    #[test]
    fn test_pattern_detector_add_rule() {
        let mut detector = PatternDetector::new();
        let rule = PatternRule::new(
            "custom",
            PatternCategory::Convention,
            "Custom rule",
            r"custom_pattern",
        )
        .unwrap();

        let initial_count = detector.rules.len();
        detector.add_rule(rule);
        assert_eq!(detector.rules.len(), initial_count + 1);
    }

    #[test]
    fn test_pattern_detector_summary() {
        let mut detector = PatternDetector::new();
        detector.analyze(Path::new("test.rs"), "val.unwrap(); // TODO: fix");

        let summary = detector.summary();
        assert!(summary.contains_key(&PatternCategory::AntiPattern));
        assert!(summary.contains_key(&PatternCategory::Convention));
    }

    #[test]
    fn test_project_intelligence_new() {
        let intel = ProjectIntelligence::new(PathBuf::from("/tmp/test"));
        assert_eq!(intel.root(), Path::new("/tmp/test"));
    }

    #[test]
    fn test_project_intelligence_accessors() {
        let intel = ProjectIntelligence::new(PathBuf::from("/tmp/test"));
        assert!(intel
            .symbols()
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .is_empty());
        assert!(intel
            .files()
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .is_empty());
    }

    #[test]
    fn test_project_intelligence_search_empty() {
        let intel = ProjectIntelligence::new(PathBuf::from("/tmp/test"));
        let results = intel.search("test");
        assert!(results.is_empty());
    }

    #[test]
    fn test_search_result_display() {
        let sym = Symbol::new(
            "test".to_string(),
            SymbolKind::Function,
            PathBuf::from("test.rs"),
            1,
        );
        let result = SearchResult::Symbol(sym);
        assert!(result.display().contains("test"));
    }

    #[test]
    fn test_search_result_file_display() {
        let entry = FileEntry {
            path: PathBuf::from("src/lib.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: None,
        };
        let result = SearchResult::File(entry);
        assert!(result.display().contains("lib.rs"));
    }

    #[test]
    fn test_search_result_pattern_display() {
        let pattern = CodePattern::new(
            "test_pattern".to_string(),
            "Test".to_string(),
            PatternCategory::Testing,
        );
        let result = SearchResult::Pattern(pattern);
        assert!(result.display().contains("test_pattern"));
    }

    #[test]
    fn test_project_intelligence_refresh_in_temp() {
        let temp = TempDir::new().unwrap();
        let cargo_path = temp.path().join("Cargo.toml");
        std::fs::write(
            &cargo_path,
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
serde = "1.0"
"#,
        )
        .unwrap();

        let src_dir = temp.path().join("src");
        std::fs::create_dir(&src_dir).unwrap();
        std::fs::write(src_dir.join("lib.rs"), "pub fn hello() {}").unwrap();

        let mut intel = ProjectIntelligence::new(temp.path().to_path_buf());
        intel.refresh().unwrap();

        // Check dependencies were parsed
        let deps = intel
            .dependencies()
            .read()
            .unwrap_or_else(|e| e.into_inner());
        assert!(deps.find("serde").is_some());

        // The refresh succeeded without error, which is the main check
        // File indexing depends on walkdir behavior with temp dirs
    }

    #[test]
    fn test_project_intelligence_index_files_manually() {
        let intel = ProjectIntelligence::new(PathBuf::from("/tmp/test"));

        // Test manual file addition
        let mut files = intel.files().write().unwrap_or_else(|e| e.into_inner());
        files.add(FileEntry {
            path: PathBuf::from("test.rs"),
            size: 100,
            modified: Utc::now(),
            extension: Some("rs".to_string()),
            language: Some("Rust".to_string()),
            lines: Some(10),
        });
        assert_eq!(files.len(), 1);
    }

    #[test]
    fn test_rust_symbol_indexing() {
        let intel = ProjectIntelligence::new(PathBuf::from("/tmp/test"));
        let mut index = SymbolIndex::new();
        let content = r#"
pub fn public_function() {}
fn private_function() {}
pub struct MyStruct {}
pub enum MyEnum {}
pub trait MyTrait {}
impl MyStruct {}
pub const MY_CONST: u32 = 1;
pub type MyType = u32;
macro_rules! my_macro { () => {} }
"#;
        intel.index_rust_symbols(&mut index, Path::new("test.rs"), content);

        assert!(!index.functions().is_empty());
        assert!(!index.structs().is_empty());
        assert!(index.get("MyEnum").is_some());
        assert!(index.get("MyTrait").is_some());
        assert!(index.get("MyStruct").is_some()); // Both struct and impl
    }
}