scribe-patterns 0.5.1

Advanced pattern matching and search algorithms for Scribe
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
//! Gitignore pattern handling with proper precedence and syntax support.
//!
//! This module provides comprehensive gitignore functionality including:
//! - Full gitignore syntax support (negation, directory matching, etc.)
//! - Proper precedence handling for multiple gitignore files
//! - Integration with the ignore crate for performance
//! - Support for .gitignore, .ignore, and custom ignore files

use scribe_core::{Result, ScribeError};
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
// use std::collections::HashMap; // Not needed currently
use ignore::{overrides::OverrideBuilder, WalkBuilder};
use serde::{Deserialize, Serialize};

/// Gitignore pattern matcher with full syntax support
#[derive(Debug)]
pub struct GitignoreMatcher {
    patterns: Vec<GitignorePattern>,
    ignore_files: Vec<IgnoreFile>,
    overrides: Option<ignore::overrides::Override>,
    case_sensitive: bool,
    require_literal_separator: bool,
}

/// Individual gitignore pattern with parsing and matching
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitignorePattern {
    pub original: String,
    pub pattern: String,
    pub negated: bool,
    pub directory_only: bool,
    pub anchored: bool,
    pub rule_type: GitignoreRule,
}

/// Type of gitignore rule
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GitignoreRule {
    Include,
    Exclude,
    Comment,
    Empty,
}

/// Information about a loaded ignore file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IgnoreFile {
    pub path: PathBuf,
    pub ignore_type: IgnoreType,
    pub patterns: Vec<GitignorePattern>,
    pub line_count: usize,
}

/// Type of ignore file
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum IgnoreType {
    Gitignore,
    GlobalGitignore,
    CustomIgnore,
    DotIgnore,
}

/// Match result for gitignore patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IgnoreMatchResult {
    pub ignored: bool,
    pub matched_pattern: Option<String>,
    pub matched_file: Option<PathBuf>,
    pub rule_type: GitignoreRule,
    pub line_number: Option<usize>,
}

impl GitignorePattern {
    /// Create a new gitignore pattern from a line
    pub fn new(line: &str) -> Result<Self> {
        let trimmed = line.trim();

        // Handle empty lines and comments
        if trimmed.is_empty() {
            return Ok(Self {
                original: line.to_string(),
                pattern: String::new(),
                negated: false,
                directory_only: false,
                anchored: false,
                rule_type: GitignoreRule::Empty,
            });
        }

        if trimmed.starts_with('#') {
            return Ok(Self {
                original: line.to_string(),
                pattern: trimmed.to_string(),
                negated: false,
                directory_only: false,
                anchored: false,
                rule_type: GitignoreRule::Comment,
            });
        }

        let mut pattern = trimmed.to_string();
        let mut negated = false;
        let mut directory_only = false;
        let mut anchored = false;

        // Handle negation
        if pattern.starts_with('!') {
            negated = true;
            pattern = pattern[1..].to_string();
        }

        // Handle directory-only patterns
        if pattern.ends_with('/') {
            directory_only = true;
            pattern = pattern.trim_end_matches('/').to_string();
        }

        // Handle anchoring
        if pattern.starts_with('/') {
            anchored = true;
            pattern = pattern[1..].to_string();
        }

        // Determine rule type
        let rule_type = if negated {
            GitignoreRule::Include
        } else {
            GitignoreRule::Exclude
        };

        Ok(Self {
            original: line.to_string(),
            pattern,
            negated,
            directory_only,
            anchored,
            rule_type,
        })
    }

    /// Check if this pattern matches a path
    pub fn matches<P: AsRef<Path>>(
        &self,
        path: P,
        is_directory: bool,
        case_sensitive: bool,
    ) -> bool {
        if matches!(
            self.rule_type,
            GitignoreRule::Comment | GitignoreRule::Empty
        ) {
            return false;
        }

        let path_str = path.as_ref().to_string_lossy();
        self.matches_glob(&self.pattern, &path_str, is_directory, case_sensitive)
    }

    /// Convert gitignore pattern to glob pattern
    fn to_glob_pattern(&self) -> String {
        let pattern = self.pattern.clone();

        // Handle anchored vs unanchored patterns
        if self.anchored {
            // Anchored patterns match from the root
            pattern
        } else {
            // Unanchored patterns can match anywhere
            if pattern.contains('/') {
                // If pattern contains '/', it's treated as a path pattern
                format!("**/{}", pattern)
            } else {
                // If no '/', it matches files/directories with that name anywhere
                format!("**/{}", pattern)
            }
        }
    }

    /// Simple glob-like matching (simplified implementation)
    fn matches_glob(
        &self,
        pattern: &str,
        path: &str,
        is_directory: bool,
        case_sensitive: bool,
    ) -> bool {
        // This is a simplified implementation
        // A full implementation would use proper gitignore pattern matching

        if pattern.contains("**") {
            // Handle recursive patterns
            let parts: Vec<&str> = pattern.split("**").collect();
            if parts.len() == 2 {
                let prefix = parts[0];
                let suffix = parts[1].trim_start_matches('/');

                if prefix.is_empty() {
                    // Pattern like **/suffix
                    if suffix.contains('*') {
                        // If suffix has wildcards, match it against path components
                        let path_parts: Vec<&str> = path.split('/').collect();
                        return path_parts
                            .iter()
                            .any(|part| self.wildcard_match(suffix, part, case_sensitive));
                    } else {
                        return path.ends_with(suffix) || path.contains(&format!("/{}", suffix));
                    }
                } else if suffix.is_empty() {
                    // Pattern like prefix/**
                    return path.starts_with(prefix.trim_end_matches('/'));
                } else {
                    // Pattern like prefix/**/suffix
                    return path.starts_with(prefix.trim_end_matches('/'))
                        && (path.ends_with(suffix) || path.contains(&format!("/{}", suffix)));
                }
            }
        }

        // Simple wildcard matching
        if pattern.contains('*') {
            return self.wildcard_match(pattern, path, case_sensitive);
        }

        // For directory patterns, only match directories or paths inside directories
        if self.directory_only {
            // Directory-only patterns (ending with /) should only match:
            // 1. If the path is a directory AND matches the pattern exactly (anywhere in path for unanchored)
            // 2. If the path is inside a directory that matches the pattern

            if case_sensitive {
                if self.anchored {
                    // Anchored: must start with pattern/ or be exactly pattern (if directory)
                    let dir_pattern = format!("{}/", pattern);
                    path.starts_with(&dir_pattern) || (path == pattern && is_directory)
                } else {
                    // Unanchored: can match anywhere in the path
                    let dir_pattern = format!("{}/", pattern);
                    let component_pattern = format!("/{}", pattern);
                    path.starts_with(&dir_pattern)
                        || (path == pattern && is_directory)
                        || path.contains(&dir_pattern)
                        || (path.ends_with(&component_pattern) && is_directory)
                }
            } else {
                let path_lower = path.to_ascii_lowercase();
                let pattern_lower = pattern.to_ascii_lowercase();
                let dir_pattern_lower = format!("{}/", pattern_lower);
                let component_pattern_lower = format!("/{}", pattern_lower);

                if self.anchored {
                    path_lower.starts_with(&dir_pattern_lower)
                        || (path_lower == pattern_lower && is_directory)
                } else {
                    path_lower.starts_with(&dir_pattern_lower)
                        || (path_lower == pattern_lower && is_directory)
                        || path_lower.contains(&dir_pattern_lower)
                        || (path_lower.ends_with(&component_pattern_lower) && is_directory)
                }
            }
        } else {
            // Exact match or path component match
            let component_pattern = format!("/{}", pattern);
            if case_sensitive {
                path == pattern || path.ends_with(&component_pattern)
            } else {
                path.to_ascii_lowercase() == pattern.to_ascii_lowercase()
                    || path
                        .to_ascii_lowercase()
                        .ends_with(&component_pattern.to_ascii_lowercase())
            }
        }
    }

    /// Simple wildcard matching
    fn wildcard_match(&self, pattern: &str, text: &str, case_sensitive: bool) -> bool {
        let pattern_chars: Vec<char> = pattern.chars().collect();
        let text_chars: Vec<char> = text.chars().collect();

        self.wildcard_match_recursive(&pattern_chars, &text_chars, 0, 0, case_sensitive)
    }

    fn wildcard_match_recursive(
        &self,
        pattern: &[char],
        text: &[char],
        p: usize,
        t: usize,
        case_sensitive: bool,
    ) -> bool {
        if p == pattern.len() {
            return t == text.len();
        }

        if pattern[p] == '*' {
            // In gitignore, * matches any character except '/'
            // Try matching zero characters
            if self.wildcard_match_recursive(pattern, text, p + 1, t, case_sensitive) {
                return true;
            }
            // Try matching one or more characters (but not '/')
            for i in t..text.len() {
                if text[i] == '/' {
                    break; // Stop at directory separator
                }
                if self.wildcard_match_recursive(pattern, text, p + 1, i + 1, case_sensitive) {
                    return true;
                }
            }
            false
        } else if pattern[p] == '?' {
            if t < text.len() {
                self.wildcard_match_recursive(pattern, text, p + 1, t + 1, case_sensitive)
            } else {
                false
            }
        } else {
            if t < text.len() {
                let chars_match = if case_sensitive {
                    pattern[p] == text[t]
                } else {
                    pattern[p].to_ascii_lowercase() == text[t].to_ascii_lowercase()
                };
                if chars_match {
                    self.wildcard_match_recursive(pattern, text, p + 1, t + 1, case_sensitive)
                } else {
                    false
                }
            } else {
                false
            }
        }
    }

    /// Check if this pattern is a comment
    pub fn is_comment(&self) -> bool {
        self.rule_type == GitignoreRule::Comment
    }

    /// Check if this pattern is empty
    pub fn is_empty(&self) -> bool {
        self.rule_type == GitignoreRule::Empty
    }

    /// Get the effective pattern (without gitignore syntax)
    pub fn effective_pattern(&self) -> &str {
        &self.pattern
    }
}

impl GitignoreMatcher {
    /// Create a new gitignore matcher
    pub fn new() -> Self {
        Self {
            patterns: Vec::new(),
            ignore_files: Vec::new(),
            overrides: None,
            case_sensitive: true,
            require_literal_separator: false,
        }
    }

    /// Create a case-insensitive matcher
    pub fn case_insensitive() -> Self {
        Self {
            patterns: Vec::new(),
            ignore_files: Vec::new(),
            overrides: None,
            case_sensitive: false,
            require_literal_separator: false,
        }
    }

    /// Add a gitignore pattern directly
    pub fn add_pattern(&mut self, pattern: &str) -> Result<()> {
        let gitignore_pattern = GitignorePattern::new(pattern)?;
        self.patterns.push(gitignore_pattern);
        self.invalidate_overrides();
        Ok(())
    }

    /// Add multiple patterns
    pub fn add_patterns<I, S>(&mut self, patterns: I) -> Result<()>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for pattern in patterns {
            self.add_pattern(pattern.as_ref())?;
        }
        Ok(())
    }

    /// Load patterns from a gitignore file
    pub fn add_gitignore_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let path = path.as_ref();
        let ignore_type = self.determine_ignore_type(path);
        let ignore_file = self.load_ignore_file(path, ignore_type)?;

        // Add patterns to the main list
        for pattern in &ignore_file.patterns {
            self.patterns.push(pattern.clone());
        }

        self.ignore_files.push(ignore_file);
        self.invalidate_overrides();
        Ok(())
    }

    /// Load patterns from multiple gitignore files
    pub fn add_gitignore_files<P, I>(&mut self, paths: I) -> Result<()>
    where
        P: AsRef<Path>,
        I: IntoIterator<Item = P>,
    {
        for path in paths {
            self.add_gitignore_file(path)?;
        }
        Ok(())
    }

    /// Check if a path should be ignored
    pub fn is_ignored<P: AsRef<Path>>(&mut self, path: P) -> Result<bool> {
        let result = self.match_path(path)?;
        Ok(result.ignored)
    }

    /// Get detailed match information for a path
    pub fn match_path<P: AsRef<Path>>(&mut self, path: P) -> Result<IgnoreMatchResult> {
        let path = path.as_ref();
        // For gitignore patterns, we need to work with theoretical paths that may not exist
        // A path ending with '/' is considered a directory, otherwise check filesystem if it exists
        let path_str = path.to_string_lossy();
        let is_directory = path_str.ends_with('/') || path.is_dir();

        // Process patterns in reverse order (later patterns override earlier ones)
        let mut result = IgnoreMatchResult {
            ignored: false,
            matched_pattern: None,
            matched_file: None,
            rule_type: GitignoreRule::Exclude,
            line_number: None,
        };

        for (index, pattern) in self.patterns.iter().enumerate().rev() {
            if pattern.matches(path, is_directory, self.case_sensitive) {
                result.matched_pattern = Some(pattern.original.clone());
                result.rule_type = pattern.rule_type.clone();

                // Find which file this pattern came from
                let mut line_count = 0;
                for ignore_file in &self.ignore_files {
                    if index < line_count + ignore_file.patterns.len() {
                        result.matched_file = Some(ignore_file.path.clone());
                        result.line_number = Some(index - line_count + 1);
                        break;
                    }
                    line_count += ignore_file.patterns.len();
                }

                // Set ignore status based on rule type
                match pattern.rule_type {
                    GitignoreRule::Exclude => {
                        result.ignored = true;
                    }
                    GitignoreRule::Include => {
                        result.ignored = false; // Negation pattern
                    }
                    _ => continue, // Comments and empty lines don't affect matching
                }

                // Stop at first match (patterns are processed in reverse order)
                break;
            }
        }

        Ok(result)
    }

    /// Check multiple paths efficiently using ignore crate integration
    pub fn filter_paths<P>(&mut self, paths: &[P]) -> Result<Vec<P>>
    where
        P: AsRef<Path> + Clone,
    {
        if self.overrides.is_none() {
            self.build_overrides()?;
        }

        let mut result = Vec::new();

        for path in paths {
            if !self.is_ignored(path)? {
                result.push(path.clone());
            }
        }

        Ok(result)
    }

    /// Get all loaded ignore files
    pub fn ignore_files(&self) -> &[IgnoreFile] {
        &self.ignore_files
    }

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

    /// Clear all patterns and files
    pub fn clear(&mut self) {
        self.patterns.clear();
        self.ignore_files.clear();
        self.invalidate_overrides();
    }

    /// Get statistics about loaded patterns
    pub fn stats(&self) -> GitignoreStats {
        let total_patterns = self.patterns.len();
        let exclude_patterns = self
            .patterns
            .iter()
            .filter(|p| p.rule_type == GitignoreRule::Exclude)
            .count();
        let include_patterns = self
            .patterns
            .iter()
            .filter(|p| p.rule_type == GitignoreRule::Include)
            .count();
        let comment_lines = self
            .patterns
            .iter()
            .filter(|p| p.rule_type == GitignoreRule::Comment)
            .count();

        GitignoreStats {
            total_patterns,
            exclude_patterns,
            include_patterns,
            comment_lines,
            ignore_files: self.ignore_files.len(),
        }
    }

    /// Load patterns from an ignore file
    fn load_ignore_file(&self, path: &Path, ignore_type: IgnoreType) -> Result<IgnoreFile> {
        if !path.exists() {
            return Err(ScribeError::path(
                format!("Ignore file does not exist: {}", path.display()),
                path,
            ));
        }

        let file = fs::File::open(path).map_err(|e| {
            ScribeError::io(
                format!("Failed to open ignore file {}: {}", path.display(), e),
                e,
            )
        })?;

        let reader = BufReader::new(file);
        let mut patterns = Vec::new();
        let mut line_count = 0;

        for line in reader.lines() {
            let line =
                line.map_err(|e| ScribeError::io(format!("Failed to read ignore file: {}", e), e))?;
            line_count += 1;

            match GitignorePattern::new(&line) {
                Ok(pattern) => patterns.push(pattern),
                Err(e) => {
                    log::warn!(
                        "Invalid gitignore pattern in {} line {}: {} ({})",
                        path.display(),
                        line_count,
                        line,
                        e
                    );
                }
            }
        }

        Ok(IgnoreFile {
            path: path.to_path_buf(),
            ignore_type,
            patterns,
            line_count,
        })
    }

    /// Determine the type of ignore file based on its path
    fn determine_ignore_type(&self, path: &Path) -> IgnoreType {
        if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
            match filename {
                ".gitignore" => IgnoreType::Gitignore,
                ".ignore" => IgnoreType::DotIgnore,
                _ => IgnoreType::CustomIgnore,
            }
        } else {
            IgnoreType::CustomIgnore
        }
    }

    /// Build override patterns for the ignore crate
    fn build_overrides(&mut self) -> Result<()> {
        let mut builder = OverrideBuilder::new(".");

        for pattern in &self.patterns {
            if matches!(
                pattern.rule_type,
                GitignoreRule::Exclude | GitignoreRule::Include
            ) {
                let glob_pattern = pattern.to_glob_pattern();
                let override_pattern = if pattern.negated {
                    format!("!{}", glob_pattern)
                } else {
                    glob_pattern
                };

                if let Err(e) = builder.add(&override_pattern) {
                    log::warn!("Failed to add override pattern {}: {}", override_pattern, e);
                }
            }
        }

        self.overrides = Some(builder.build()?);
        Ok(())
    }

    /// Invalidate compiled overrides
    fn invalidate_overrides(&mut self) {
        self.overrides = None;
    }

    /// Find gitignore files in a directory tree
    pub fn discover_gitignore_files<P: AsRef<Path>>(root: P) -> Result<Vec<PathBuf>> {
        let root = root.as_ref();
        let mut gitignore_files = Vec::new();

        // Use WalkBuilder from ignore crate to respect existing gitignore rules
        let walker = WalkBuilder::new(root)
            .hidden(false) // Include hidden files to find .gitignore
            .git_ignore(false) // Don't apply gitignore during discovery
            .build();

        for entry in walker {
            match entry {
                Ok(entry) => {
                    let path = entry.path();
                    if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                        if matches!(filename, ".gitignore" | ".ignore") {
                            gitignore_files.push(path.to_path_buf());
                        }
                    }
                }
                Err(e) => {
                    log::warn!("Error walking directory tree: {}", e);
                }
            }
        }

        Ok(gitignore_files)
    }

    /// Load all gitignore files from a directory tree
    pub fn from_directory<P: AsRef<Path>>(root: P) -> Result<Self> {
        let mut matcher = Self::new();
        let gitignore_files = Self::discover_gitignore_files(&root)?;

        for file in gitignore_files {
            if let Err(e) = matcher.add_gitignore_file(&file) {
                log::warn!("Failed to load gitignore file {}: {}", file.display(), e);
            }
        }

        Ok(matcher)
    }

    /// Create a matcher with commonly ignored patterns
    pub fn with_defaults() -> Self {
        let mut matcher = Self::new();

        // Add common ignore patterns
        let default_patterns = [
            ".DS_Store",
            "Thumbs.db",
            "*.tmp",
            "*.temp",
            ".git/",
            ".svn/",
            ".hg/",
            "node_modules/",
            "target/",
            "build/",
            "dist/",
            "__pycache__/",
            "*.pyc",
            "*.pyo",
        ];

        for pattern in &default_patterns {
            if let Err(e) = matcher.add_pattern(pattern) {
                log::warn!("Failed to add default pattern {}: {}", pattern, e);
            }
        }

        matcher
    }
}

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

/// Statistics about gitignore patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitignoreStats {
    pub total_patterns: usize,
    pub exclude_patterns: usize,
    pub include_patterns: usize,
    pub comment_lines: usize,
    pub ignore_files: usize,
}

// Note: From<ignore::Error> for ScribeError needs to be implemented in scribe-core

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

    #[test]
    fn test_gitignore_pattern_parsing() {
        // Basic pattern
        let pattern = GitignorePattern::new("*.rs").unwrap();
        assert_eq!(pattern.pattern, "*.rs");
        assert!(!pattern.negated);
        assert!(!pattern.directory_only);
        assert!(!pattern.anchored);
        assert_eq!(pattern.rule_type, GitignoreRule::Exclude);

        // Negated pattern
        let pattern = GitignorePattern::new("!important.rs").unwrap();
        assert_eq!(pattern.pattern, "important.rs");
        assert!(pattern.negated);
        assert_eq!(pattern.rule_type, GitignoreRule::Include);

        // Directory pattern
        let pattern = GitignorePattern::new("build/").unwrap();
        assert_eq!(pattern.pattern, "build");
        assert!(pattern.directory_only);
        assert_eq!(pattern.rule_type, GitignoreRule::Exclude);

        // Anchored pattern
        let pattern = GitignorePattern::new("/root-only").unwrap();
        assert_eq!(pattern.pattern, "root-only");
        assert!(pattern.anchored);
        assert_eq!(pattern.rule_type, GitignoreRule::Exclude);

        // Comment
        let pattern = GitignorePattern::new("# This is a comment").unwrap();
        assert_eq!(pattern.rule_type, GitignoreRule::Comment);

        // Empty line
        let pattern = GitignorePattern::new("   ").unwrap();
        assert_eq!(pattern.rule_type, GitignoreRule::Empty);
    }

    #[test]
    fn test_gitignore_pattern_matching() {
        let pattern = GitignorePattern::new("*.rs").unwrap();
        assert!(pattern.matches("lib.rs", false, true));
        assert!(!pattern.matches("src/lib.rs", false, true)); // Single * doesn't match across directories
        assert!(!pattern.matches("lib.py", false, true));

        // For recursive matching, use **
        let pattern = GitignorePattern::new("**/*.rs").unwrap();
        assert!(pattern.matches("lib.rs", false, true));
        assert!(pattern.matches("src/lib.rs", false, true));

        let pattern = GitignorePattern::new("build/").unwrap();
        assert!(pattern.matches("build", true, true)); // Directory
        assert!(!pattern.matches("build", false, true)); // File
        assert!(pattern.matches("src/build", true, true));

        let pattern = GitignorePattern::new("/root-only").unwrap();
        assert!(pattern.matches("root-only", false, true));
        // Note: Full anchoring logic would be more complex in a real implementation

        let pattern = GitignorePattern::new("!*.rs").unwrap();
        assert!(pattern.negated);
        assert_eq!(pattern.rule_type, GitignoreRule::Include);
    }

    #[test]
    fn test_gitignore_matcher_basic() {
        let mut matcher = GitignoreMatcher::new();
        matcher.add_pattern("**/*.rs").unwrap(); // Use ** for recursive matching
        matcher.add_pattern("build/").unwrap();
        matcher.add_pattern("!important.rs").unwrap();

        assert!(matcher.is_ignored("lib.rs").unwrap());
        assert!(matcher.is_ignored("src/lib.rs").unwrap());
        assert!(!matcher.is_ignored("lib.py").unwrap());

        // Negation should override exclude
        assert!(!matcher.is_ignored("important.rs").unwrap());
    }

    #[test]
    fn test_gitignore_file_loading() {
        let temp_dir = TempDir::new().unwrap();
        let gitignore_path = temp_dir.path().join(".gitignore");

        let gitignore_content = r#"
# Ignore compiled files
*.o
*.so
*.dylib

# Ignore build directory
build/

# Don't ignore important files
!important.txt

# Empty line above
"#;

        fs::write(&gitignore_path, gitignore_content).unwrap();

        let mut matcher = GitignoreMatcher::new();
        matcher.add_gitignore_file(&gitignore_path).unwrap();

        // Check statistics
        let stats = matcher.stats();
        assert_eq!(stats.ignore_files, 1);
        assert!(stats.exclude_patterns > 0);
        assert!(stats.include_patterns > 0);
        assert!(stats.comment_lines > 0);

        // Test matching
        assert!(matcher.is_ignored("test.o").unwrap());
        assert!(matcher.is_ignored("libtest.so").unwrap());
        assert!(matcher.is_ignored("build/").unwrap()); // Directory indicated by trailing slash
        assert!(!matcher.is_ignored("important.txt").unwrap()); // Negated
        assert!(!matcher.is_ignored("source.c").unwrap()); // Not matched
    }

    #[test]
    fn test_gitignore_match_details() {
        let mut matcher = GitignoreMatcher::new();
        matcher.add_pattern("*.tmp").unwrap();
        matcher.add_pattern("!keep.tmp").unwrap();

        let result = matcher.match_path("test.tmp").unwrap();
        assert!(result.ignored);
        assert!(result.matched_pattern.is_some());
        assert_eq!(result.rule_type, GitignoreRule::Exclude);

        let result = matcher.match_path("keep.tmp").unwrap();
        assert!(!result.ignored);
        assert!(result.matched_pattern.is_some());
        assert_eq!(result.rule_type, GitignoreRule::Include);

        let result = matcher.match_path("test.rs").unwrap();
        assert!(!result.ignored);
        assert!(result.matched_pattern.is_none());
    }

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

        // Create directory structure with multiple .gitignore files
        fs::create_dir_all(root.join("src")).unwrap();
        fs::create_dir_all(root.join("tests")).unwrap();
        fs::create_dir_all(root.join("docs")).unwrap();

        fs::write(root.join(".gitignore"), "*.tmp\nbuild/").unwrap();
        fs::write(root.join("src/.gitignore"), "*.o").unwrap();
        fs::write(root.join("tests/.gitignore"), "fixtures/").unwrap();

        let gitignore_files = GitignoreMatcher::discover_gitignore_files(root).unwrap();
        assert_eq!(gitignore_files.len(), 3);

        // Check that all expected files are found
        let filenames: Vec<String> = gitignore_files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(filenames.iter().all(|name| name == ".gitignore"));
    }

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

        // Create .gitignore files
        fs::write(root.join(".gitignore"), "*.tmp\n*.log").unwrap();
        fs::create_dir_all(root.join("subdir")).unwrap();
        fs::write(root.join("subdir/.gitignore"), "*.bak").unwrap();

        let matcher = GitignoreMatcher::from_directory(root).unwrap();
        let stats = matcher.stats();

        assert_eq!(stats.ignore_files, 2);
        assert!(stats.total_patterns >= 3); // At least the 3 patterns we added
    }

    #[test]
    fn test_gitignore_defaults() {
        let matcher = GitignoreMatcher::with_defaults();
        let stats = matcher.stats();

        assert!(stats.total_patterns > 0);
        assert!(stats.exclude_patterns > 0);

        // Test some common patterns
        let mut matcher = matcher;
        assert!(matcher.is_ignored("node_modules/package.json").unwrap());
        assert!(matcher.is_ignored("target/debug/main").unwrap());
        assert!(matcher.is_ignored(".DS_Store").unwrap());
        assert!(matcher.is_ignored("__pycache__/module.pyc").unwrap());
    }

    #[test]
    fn test_gitignore_case_sensitivity() {
        let mut matcher = GitignoreMatcher::new();
        matcher.add_pattern("*.TMP").unwrap();

        // Case-sensitive by default
        assert!(matcher.is_ignored("file.TMP").unwrap());
        assert!(!matcher.is_ignored("file.tmp").unwrap());

        let mut matcher = GitignoreMatcher::case_insensitive();
        matcher.add_pattern("*.TMP").unwrap();

        // Case-insensitive matcher
        assert!(matcher.is_ignored("file.TMP").unwrap());
        assert!(matcher.is_ignored("file.tmp").unwrap());
        assert!(matcher.is_ignored("file.Tmp").unwrap());
    }

    #[test]
    fn test_gitignore_pattern_precedence() {
        let mut matcher = GitignoreMatcher::new();

        // Add patterns in order - later ones should override earlier ones
        matcher.add_pattern("*.txt").unwrap(); // Exclude all .txt files
        matcher.add_pattern("!important.txt").unwrap(); // But include important.txt
        matcher.add_pattern("important.txt").unwrap(); // But exclude it again

        // The last pattern should win
        assert!(matcher.is_ignored("important.txt").unwrap());
        assert!(matcher.is_ignored("other.txt").unwrap());
    }

    #[test]
    fn test_complex_gitignore_patterns() {
        let mut matcher = GitignoreMatcher::new();

        // Test various gitignore pattern types
        matcher.add_pattern("**/*.tmp").unwrap(); // Recursive pattern
        matcher.add_pattern("build/**/output").unwrap(); // Pattern with ** in middle
        matcher.add_pattern("logs/*.log").unwrap(); // Single level wildcard
        matcher.add_pattern("cache/*/data").unwrap(); // Single directory wildcard

        assert!(matcher.is_ignored("file.tmp").unwrap());
        assert!(matcher.is_ignored("deep/nested/file.tmp").unwrap());
        assert!(matcher.is_ignored("logs/error.log").unwrap());
        assert!(!matcher.is_ignored("logs/nested/error.log").unwrap()); // Single level only
    }

    #[test]
    fn test_gitignore_filter_paths() {
        let mut matcher = GitignoreMatcher::new();
        matcher.add_pattern("*.tmp").unwrap();
        matcher.add_pattern("build/").unwrap();

        let paths = vec![
            "src/lib.rs",
            "temp.tmp",
            "build/output",
            "README.md",
            "test.tmp",
        ];

        let filtered = matcher.filter_paths(&paths).unwrap();

        assert_eq!(filtered.len(), 2);
        assert!(filtered.contains(&"src/lib.rs"));
        assert!(filtered.contains(&"README.md"));
        assert!(!filtered.contains(&"temp.tmp"));
        assert!(!filtered.contains(&"test.tmp"));
        assert!(!filtered.contains(&"build/output"));
    }

    #[test]
    fn test_gitignore_empty_and_comments() {
        let mut matcher = GitignoreMatcher::new();
        matcher.add_pattern("").unwrap(); // Empty line
        matcher.add_pattern("   ").unwrap(); // Whitespace only
        matcher.add_pattern("# Comment").unwrap(); // Comment
        matcher.add_pattern("*.rs").unwrap(); // Actual pattern

        let stats = matcher.stats();
        assert_eq!(stats.exclude_patterns, 1); // Only *.rs counts
        assert!(stats.comment_lines >= 1);

        assert!(matcher.is_ignored("test.rs").unwrap());
        assert!(!matcher.is_ignored("test.py").unwrap());
    }
}