selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
//! 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}"))
});

// std::sync::RwLock is intentional here. All ProjectIntelligence methods are synchronous,
// so std::sync::RwLock avoids requiring .await at every lock acquisition. Migrating to
// tokio::sync::RwLock would require making refresh(), search(), index_files(), and all
// accessor call-sites async (~50+ changes) with no functional benefit.

/// 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
    }

    /// 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().ok().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 Ok(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| {
                if e.depth() == 0 {
                    return true;
                }
                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)]
#[path = "../../tests/unit/cognitive/intelligence/intelligence_test.rs"]
mod tests;