unfault 1.0.11

Unfault — a cognitive context engine for thoughtful engineers
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
//! # Header Extractor
//!
//! Extracts import headers from source files for complete dependency graph building.
//!
//! The header section is the portion of a file that contains import/use statements,
//! typically at the top of the file. Extracting only headers allows us to build a
//! complete import graph without sending entire file contents.
//!
//! ## Supported Languages
//!
//! - **Python**: `import`, `from ... import`
//! - **Rust**: `use`, `mod`, `extern crate`
//! - **Go**: `import`
//! - **JavaScript/TypeScript**: `import`, `require`, `export ... from`
//! - **Java**: `import`, `package`

use rayon::prelude::*;
use std::fs;
use std::path::{Path, PathBuf};

use super::workspace::Language;

/// Extracted header from a source file.
#[derive(Debug, Clone)]
pub struct FileHeader {
    /// File path relative to workspace root
    pub path: String,
    /// Programming language
    pub language: String,
    /// Extracted header content (import section only)
    pub header: String,
}

/// Configuration for header extraction.
#[derive(Debug, Clone)]
pub struct HeaderExtractorConfig {
    /// Maximum number of lines to consider as header
    pub max_header_lines: usize,
    /// Maximum bytes per header (to prevent oversized headers)
    pub max_header_bytes: usize,
}

impl Default for HeaderExtractorConfig {
    fn default() -> Self {
        Self {
            max_header_lines: 100,      // Most imports should be within first 100 lines
            max_header_bytes: 8 * 1024, // 8KB max per header
        }
    }
}

/// Extractor for file headers (import sections).
pub struct HeaderExtractor {
    root: PathBuf,
    config: HeaderExtractorConfig,
}

impl HeaderExtractor {
    /// Create a new header extractor.
    ///
    /// # Arguments
    ///
    /// * `root` - Root directory of the workspace
    pub fn new(root: impl AsRef<Path>) -> Self {
        Self {
            root: root.as_ref().to_path_buf(),
            config: HeaderExtractorConfig::default(),
        }
    }

    /// Create a new header extractor with custom configuration.
    ///
    /// # Arguments
    ///
    /// * `root` - Root directory of the workspace
    /// * `config` - Extraction configuration
    pub fn with_config(root: impl AsRef<Path>, config: HeaderExtractorConfig) -> Self {
        Self {
            root: root.as_ref().to_path_buf(),
            config,
        }
    }

    /// Extract headers from all source files in parallel.
    ///
    /// # Arguments
    ///
    /// * `source_files` - List of (path, language) tuples from workspace scanning
    ///
    /// # Returns
    ///
    /// Vector of extracted file headers
    pub fn extract_all(&self, source_files: &[(PathBuf, Language)]) -> Vec<FileHeader> {
        source_files
            .par_iter()
            .filter_map(|(path, language)| {
                let relative_path = path
                    .strip_prefix(&self.root)
                    .unwrap_or(path)
                    .to_string_lossy()
                    .to_string();

                match fs::read_to_string(path) {
                    Ok(contents) => {
                        let header = self.extract_header(&contents, *language);

                        // Skip files with no imports
                        if header.is_empty() {
                            return None;
                        }

                        Some(FileHeader {
                            path: relative_path,
                            language: language.as_str().to_string(),
                            header,
                        })
                    }
                    Err(_) => None,
                }
            })
            .collect()
    }

    /// Extract the header (import section) from file contents.
    ///
    /// # Arguments
    ///
    /// * `contents` - Full file contents
    /// * `language` - Programming language
    ///
    /// # Returns
    ///
    /// Extracted header string containing only import statements
    pub fn extract_header(&self, contents: &str, language: Language) -> String {
        match language {
            Language::Python => self.extract_python_header(contents),
            Language::Rust => self.extract_rust_header(contents),
            Language::Go => self.extract_go_header(contents),
            Language::TypeScript | Language::JavaScript => self.extract_js_header(contents),
            Language::Java => self.extract_java_header(contents),
        }
    }

    /// Extract Python import header.
    ///
    /// Includes:
    /// - `import x`
    /// - `from x import y`
    /// - Leading comments and docstrings (for context)
    fn extract_python_header(&self, contents: &str) -> String {
        let mut header_lines = Vec::new();
        let mut in_multiline_string = false;
        let mut multiline_delim = "";
        let mut header_started = false;

        for (i, line) in contents.lines().enumerate() {
            if i >= self.config.max_header_lines {
                break;
            }

            let trimmed = line.trim();

            // Handle multi-line strings (docstrings)
            if in_multiline_string {
                header_lines.push(line.to_string());
                if trimmed.contains(multiline_delim) && !trimmed.starts_with(multiline_delim) {
                    in_multiline_string = false;
                } else if trimmed.ends_with(multiline_delim) {
                    in_multiline_string = false;
                }
                continue;
            }

            // Check for multiline string start
            if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
                multiline_delim = if trimmed.starts_with("\"\"\"") {
                    "\"\"\""
                } else {
                    "'''"
                };
                header_lines.push(line.to_string());
                // Check if it ends on the same line
                let rest = &trimmed[3..];
                if !rest.contains(multiline_delim) {
                    in_multiline_string = true;
                }
                continue;
            }

            // Skip empty lines at the beginning
            if trimmed.is_empty() {
                if header_started {
                    header_lines.push(line.to_string());
                }
                continue;
            }

            // Include comments (only before imports)
            if trimmed.starts_with('#') {
                if !header_started {
                    header_lines.push(line.to_string());
                }
                continue;
            }

            // Include future imports and regular imports
            if trimmed.starts_with("from __future__")
                || trimmed.starts_with("from ")
                || trimmed.starts_with("import ")
            {
                header_started = true;
                header_lines.push(line.to_string());

                // Handle multi-line imports with parentheses
                if trimmed.contains('(') && !trimmed.contains(')') {
                    // Continue until we find closing paren
                    for next_line in contents.lines().skip(i + 1) {
                        header_lines.push(next_line.to_string());
                        if next_line.contains(')') {
                            break;
                        }
                    }
                }
                // Handle line continuation with backslash
                else if trimmed.ends_with('\\') {
                    for next_line in contents.lines().skip(i + 1) {
                        header_lines.push(next_line.to_string());
                        if !next_line.trim().ends_with('\\') {
                            break;
                        }
                    }
                }
                continue;
            }

            // Stop at first non-import code
            break;
        }

        self.truncate_to_max_bytes(header_lines.join("\n"))
    }

    /// Extract Rust use/mod header.
    ///
    /// Includes:
    /// - `use x;`
    /// - `mod x;`
    /// - `extern crate x;`
    /// - Module-level attributes
    fn extract_rust_header(&self, contents: &str) -> String {
        let mut header_lines = Vec::new();
        let mut in_block_comment = false;
        let mut brace_depth = 0;

        for (i, line) in contents.lines().enumerate() {
            if i >= self.config.max_header_lines {
                break;
            }

            let trimmed = line.trim();

            // Handle block comments
            if in_block_comment {
                header_lines.push(line.to_string());
                if trimmed.contains("*/") {
                    in_block_comment = false;
                }
                continue;
            }

            if trimmed.starts_with("/*") {
                header_lines.push(line.to_string());
                if !trimmed.contains("*/") {
                    in_block_comment = true;
                }
                continue;
            }

            // Skip empty lines at the beginning
            if trimmed.is_empty() {
                if !header_lines.is_empty() {
                    header_lines.push(line.to_string());
                }
                continue;
            }

            // Include line comments
            if trimmed.starts_with("//") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include attributes
            if trimmed.starts_with("#[") || trimmed.starts_with("#![") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include use statements (handle multi-line with braces)
            if trimmed.starts_with("use ") {
                header_lines.push(line.to_string());

                // Count braces for multi-line use
                for c in trimmed.chars() {
                    if c == '{' {
                        brace_depth += 1;
                    } else if c == '}' {
                        brace_depth -= 1;
                    }
                }

                // Continue if braces not balanced
                if brace_depth > 0 {
                    for next_line in contents.lines().skip(i + 1) {
                        header_lines.push(next_line.to_string());
                        for c in next_line.chars() {
                            if c == '{' {
                                brace_depth += 1;
                            } else if c == '}' {
                                brace_depth -= 1;
                            }
                        }
                        if brace_depth == 0 {
                            break;
                        }
                    }
                }
                continue;
            }

            // Include mod declarations (external modules)
            if (trimmed.starts_with("mod ") || trimmed.starts_with("pub mod "))
                && trimmed.ends_with(';')
            {
                header_lines.push(line.to_string());
                continue;
            }

            // Include extern crate
            if trimmed.starts_with("extern crate ") {
                header_lines.push(line.to_string());
                continue;
            }

            // Stop at first non-header content (fn, struct, impl, etc.)
            if trimmed.starts_with("fn ")
                || trimmed.starts_with("pub fn ")
                || trimmed.starts_with("struct ")
                || trimmed.starts_with("pub struct ")
                || trimmed.starts_with("enum ")
                || trimmed.starts_with("pub enum ")
                || trimmed.starts_with("impl ")
                || trimmed.starts_with("trait ")
                || trimmed.starts_with("pub trait ")
                || trimmed.starts_with("const ")
                || trimmed.starts_with("pub const ")
                || trimmed.starts_with("static ")
                || trimmed.starts_with("pub static ")
                || trimmed.starts_with("type ")
                || trimmed.starts_with("pub type ")
                || (trimmed.starts_with("mod ") && trimmed.contains('{'))
            {
                break;
            }
        }

        self.truncate_to_max_bytes(header_lines.join("\n"))
    }

    /// Extract Go import header.
    ///
    /// Includes:
    /// - `package x`
    /// - `import "x"`
    /// - `import (...)` block
    fn extract_go_header(&self, contents: &str) -> String {
        let mut header_lines = Vec::new();
        let mut in_import_block = false;
        let mut in_block_comment = false;

        for (i, line) in contents.lines().enumerate() {
            if i >= self.config.max_header_lines {
                break;
            }

            let trimmed = line.trim();

            // Handle block comments
            if in_block_comment {
                header_lines.push(line.to_string());
                if trimmed.contains("*/") {
                    in_block_comment = false;
                }
                continue;
            }

            if trimmed.starts_with("/*") {
                header_lines.push(line.to_string());
                if !trimmed.contains("*/") {
                    in_block_comment = true;
                }
                continue;
            }

            // Handle import block
            if in_import_block {
                header_lines.push(line.to_string());
                if trimmed == ")" {
                    in_import_block = false;
                }
                continue;
            }

            // Skip empty lines at the beginning
            if trimmed.is_empty() {
                if !header_lines.is_empty() {
                    header_lines.push(line.to_string());
                }
                continue;
            }

            // Include line comments
            if trimmed.starts_with("//") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include package declaration
            if trimmed.starts_with("package ") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include single-line imports
            if trimmed.starts_with("import \"") || trimmed.starts_with("import `") {
                header_lines.push(line.to_string());
                continue;
            }

            // Start of import block
            if trimmed.starts_with("import (") {
                header_lines.push(line.to_string());
                if !trimmed.ends_with(')') {
                    in_import_block = true;
                }
                continue;
            }

            // Stop at first non-header content
            if trimmed.starts_with("func ")
                || trimmed.starts_with("type ")
                || trimmed.starts_with("var ")
                || trimmed.starts_with("const ")
            {
                break;
            }
        }

        self.truncate_to_max_bytes(header_lines.join("\n"))
    }

    /// Extract JavaScript/TypeScript import header.
    ///
    /// Includes:
    /// - `import x from "y"`
    /// - `import { x } from "y"`
    /// - `import * as x from "y"`
    /// - `const x = require("y")`
    /// - `export { x } from "y"`
    fn extract_js_header(&self, contents: &str) -> String {
        let mut header_lines = Vec::new();
        let mut in_block_comment = false;

        for (i, line) in contents.lines().enumerate() {
            if i >= self.config.max_header_lines {
                break;
            }

            let trimmed = line.trim();

            // Handle block comments
            if in_block_comment {
                header_lines.push(line.to_string());
                if trimmed.contains("*/") {
                    in_block_comment = false;
                }
                continue;
            }

            if trimmed.starts_with("/*") {
                header_lines.push(line.to_string());
                if !trimmed.contains("*/") {
                    in_block_comment = true;
                }
                continue;
            }

            // Skip empty lines at the beginning
            if trimmed.is_empty() {
                if !header_lines.is_empty() {
                    header_lines.push(line.to_string());
                }
                continue;
            }

            // Include line comments
            if trimmed.starts_with("//") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include 'use strict' and 'use client' directives
            if trimmed.starts_with("'use ") || trimmed.starts_with("\"use ") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include import statements
            if trimmed.starts_with("import ") {
                header_lines.push(line.to_string());

                // Handle multi-line imports
                if (trimmed.contains('{') && !trimmed.contains('}'))
                    || (!trimmed.contains("from") && !trimmed.ends_with(';'))
                {
                    for next_line in contents.lines().skip(i + 1) {
                        header_lines.push(next_line.to_string());
                        let next_trimmed = next_line.trim();
                        if next_trimmed.contains("from") || next_trimmed.ends_with(';') {
                            break;
                        }
                    }
                }
                continue;
            }

            // Include require statements
            if trimmed.contains("require(")
                && (trimmed.starts_with("const ")
                    || trimmed.starts_with("let ")
                    || trimmed.starts_with("var "))
            {
                header_lines.push(line.to_string());
                continue;
            }

            // Include re-exports
            if trimmed.starts_with("export ") && trimmed.contains(" from ") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include export * from
            if trimmed.starts_with("export *") {
                header_lines.push(line.to_string());
                continue;
            }

            // Stop at first non-import content
            if trimmed.starts_with("function ")
                || trimmed.starts_with("async function ")
                || trimmed.starts_with("class ")
                || trimmed.starts_with("export default ")
                || trimmed.starts_with("export class ")
                || trimmed.starts_with("export function ")
                || trimmed.starts_with("export async ")
                || trimmed.starts_with("export const ")
                || trimmed.starts_with("export let ")
                || trimmed.starts_with("export interface ")
                || trimmed.starts_with("export type ")
                || trimmed.starts_with("interface ")
                || trimmed.starts_with("type ")
                || (trimmed.starts_with("const ") && !trimmed.contains("require("))
                || (trimmed.starts_with("let ") && !trimmed.contains("require("))
            {
                break;
            }
        }

        self.truncate_to_max_bytes(header_lines.join("\n"))
    }

    /// Extract Java import header.
    ///
    /// Includes:
    /// - `package x.y.z;`
    /// - `import x.y.z;`
    /// - `import static x.y.z;`
    fn extract_java_header(&self, contents: &str) -> String {
        let mut header_lines = Vec::new();
        let mut in_block_comment = false;

        for (i, line) in contents.lines().enumerate() {
            if i >= self.config.max_header_lines {
                break;
            }

            let trimmed = line.trim();

            // Handle block comments / javadoc
            if in_block_comment {
                header_lines.push(line.to_string());
                if trimmed.contains("*/") {
                    in_block_comment = false;
                }
                continue;
            }

            if trimmed.starts_with("/*") {
                header_lines.push(line.to_string());
                if !trimmed.contains("*/") {
                    in_block_comment = true;
                }
                continue;
            }

            // Skip empty lines at the beginning
            if trimmed.is_empty() {
                if !header_lines.is_empty() {
                    header_lines.push(line.to_string());
                }
                continue;
            }

            // Include line comments
            if trimmed.starts_with("//") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include package declaration
            if trimmed.starts_with("package ") {
                header_lines.push(line.to_string());
                continue;
            }

            // Include import statements
            if trimmed.starts_with("import ") {
                header_lines.push(line.to_string());
                continue;
            }

            // Stop at first non-header content (class, interface, annotation)
            if trimmed.starts_with("public ")
                || trimmed.starts_with("private ")
                || trimmed.starts_with("protected ")
                || trimmed.starts_with("class ")
                || trimmed.starts_with("interface ")
                || trimmed.starts_with("enum ")
                || trimmed.starts_with("@")
                || trimmed.starts_with("abstract ")
                || trimmed.starts_with("final ")
            {
                break;
            }
        }

        self.truncate_to_max_bytes(header_lines.join("\n"))
    }

    /// Truncate header to maximum bytes.
    fn truncate_to_max_bytes(&self, header: String) -> String {
        if header.len() <= self.config.max_header_bytes {
            header
        } else {
            // Find a safe truncation point (end of line)
            let truncated = &header[..self.config.max_header_bytes];
            if let Some(last_newline) = truncated.rfind('\n') {
                truncated[..last_newline].to_string()
            } else {
                truncated.to_string()
            }
        }
    }
}

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

    fn create_test_file(dir: &Path, name: &str, contents: &str) -> PathBuf {
        let path = dir.join(name);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn test_python_simple_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"import os
import sys
from typing import List, Dict
from myapp.utils import helper

def main():
    pass
"#;
        let header = extractor.extract_header(contents, Language::Python);
        assert!(header.contains("import os"));
        assert!(header.contains("import sys"));
        assert!(header.contains("from typing import"));
        assert!(header.contains("from myapp.utils"));
        assert!(!header.contains("def main"));
    }

    #[test]
    fn test_python_multiline_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"from mymodule import (
    ClassA,
    ClassB,
    ClassC,
)

class MyClass:
    pass
"#;
        let header = extractor.extract_header(contents, Language::Python);
        assert!(header.contains("from mymodule import"));
        assert!(header.contains("ClassA"));
        assert!(header.contains("ClassC"));
        assert!(!header.contains("class MyClass"));
    }

    #[test]
    fn test_python_with_docstring() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"#!/usr/bin/env python
"""
Module docstring here.
"""
import os

def func():
    pass
"#;
        let header = extractor.extract_header(contents, Language::Python);
        assert!(header.contains("#!/usr/bin/env python"));
        assert!(header.contains("import os"));
        assert!(!header.contains("def func"));
    }

    #[test]
    fn test_rust_use_statements() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"use std::collections::HashMap;
use crate::utils::helper;
use super::parent_mod;

fn main() {
    println!("Hello");
}
"#;
        let header = extractor.extract_header(contents, Language::Rust);
        assert!(header.contains("use std::collections::HashMap"));
        assert!(header.contains("use crate::utils::helper"));
        assert!(header.contains("use super::parent_mod"));
        assert!(!header.contains("fn main"));
    }

    #[test]
    fn test_rust_multiline_use() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"use std::{
    collections::HashMap,
    sync::Arc,
};

fn main() {}
"#;
        let header = extractor.extract_header(contents, Language::Rust);
        assert!(header.contains("use std::"));
        assert!(header.contains("collections::HashMap"));
        assert!(header.contains("sync::Arc"));
        assert!(!header.contains("fn main"));
    }

    #[test]
    fn test_rust_mod_declarations() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"mod utils;
pub mod config;

use crate::utils::helper;

fn main() {}
"#;
        let header = extractor.extract_header(contents, Language::Rust);
        assert!(header.contains("mod utils;"));
        assert!(header.contains("pub mod config;"));
        assert!(header.contains("use crate::utils::helper"));
        assert!(!header.contains("fn main"));
    }

    #[test]
    fn test_go_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"package main

import (
	"fmt"
	"net/http"
	
	"github.com/gin-gonic/gin"
)

func main() {
	fmt.Println("Hello")
}
"#;
        let header = extractor.extract_header(contents, Language::Go);
        assert!(header.contains("package main"));
        assert!(header.contains("\"fmt\""));
        assert!(header.contains("\"net/http\""));
        assert!(header.contains("github.com/gin-gonic/gin"));
        assert!(!header.contains("func main"));
    }

    #[test]
    fn test_go_single_import() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"package utils

import "fmt"

func Helper() {}
"#;
        let header = extractor.extract_header(contents, Language::Go);
        assert!(header.contains("package utils"));
        assert!(header.contains("import \"fmt\""));
        assert!(!header.contains("func Helper"));
    }

    #[test]
    fn test_js_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"import React from 'react';
import { useState, useEffect } from 'react';
import * as utils from './utils';

const Component = () => {
    return null;
};
"#;
        let header = extractor.extract_header(contents, Language::JavaScript);
        assert!(header.contains("import React from 'react'"));
        assert!(header.contains("import { useState, useEffect }"));
        assert!(header.contains("import * as utils"));
        assert!(!header.contains("const Component"));
    }

    #[test]
    fn test_js_require() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"const express = require('express');
const { Router } = require('express');
let config = require('./config');

function main() {}
"#;
        let header = extractor.extract_header(contents, Language::JavaScript);
        assert!(header.contains("const express = require('express')"));
        assert!(header.contains("const { Router } = require('express')"));
        assert!(header.contains("let config = require('./config')"));
        assert!(!header.contains("function main"));
    }

    #[test]
    fn test_js_multiline_import() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"import {
    ComponentA,
    ComponentB,
    ComponentC
} from './components';

export default function App() {}
"#;
        let header = extractor.extract_header(contents, Language::JavaScript);
        assert!(header.contains("import {"));
        assert!(header.contains("ComponentA"));
        assert!(header.contains("from './components'"));
        assert!(!header.contains("export default function"));
    }

    #[test]
    fn test_ts_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"import type { FC } from 'react';
import { useState } from 'react';

interface Props {}

const Component: FC<Props> = () => null;
"#;
        let header = extractor.extract_header(contents, Language::TypeScript);
        assert!(header.contains("import type { FC }"));
        assert!(header.contains("import { useState }"));
        assert!(!header.contains("interface Props"));
        assert!(!header.contains("const Component"));
    }

    #[test]
    fn test_java_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = r#"package com.example.app;

import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyList;

public class Main {
    public static void main(String[] args) {}
}
"#;
        let header = extractor.extract_header(contents, Language::Java);
        assert!(header.contains("package com.example.app"));
        assert!(header.contains("import java.util.List"));
        assert!(header.contains("import java.util.Map"));
        assert!(header.contains("import static java.util.Collections.emptyList"));
        assert!(!header.contains("public class Main"));
    }

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

        let py_path = create_test_file(temp_dir.path(), "main.py", "import os\n\ndef main(): pass");
        let rs_path = create_test_file(temp_dir.path(), "main.rs", "use std::io;\n\nfn main() {}");
        let no_import_path = create_test_file(temp_dir.path(), "empty.py", "def func(): pass");

        let source_files = vec![
            (py_path, Language::Python),
            (rs_path, Language::Rust),
            (no_import_path, Language::Python),
        ];

        let extractor = HeaderExtractor::new(temp_dir.path());
        let headers = extractor.extract_all(&source_files);

        // Should have 2 headers (empty.py has no imports)
        assert_eq!(headers.len(), 2);

        let py_header = headers.iter().find(|h| h.path == "main.py");
        assert!(py_header.is_some());
        assert!(py_header.unwrap().header.contains("import os"));

        let rs_header = headers.iter().find(|h| h.path == "main.rs");
        assert!(rs_header.is_some());
        assert!(rs_header.unwrap().header.contains("use std::io"));
    }

    #[test]
    fn test_max_header_lines() {
        let config = HeaderExtractorConfig {
            max_header_lines: 3,
            max_header_bytes: 8 * 1024,
        };
        let extractor = HeaderExtractor::with_config("/tmp", config);

        let contents = "import a\nimport b\nimport c\nimport d\nimport e\n";
        let header = extractor.extract_header(contents, Language::Python);

        // Should only get first 3 lines
        assert!(header.contains("import a"));
        assert!(header.contains("import b"));
        assert!(header.contains("import c"));
        assert!(!header.contains("import d"));
    }

    #[test]
    fn test_max_header_bytes() {
        let config = HeaderExtractorConfig {
            max_header_lines: 100,
            max_header_bytes: 20, // Very small limit
        };
        let extractor = HeaderExtractor::with_config("/tmp", config);

        let contents = "import verylongmodulename\nimport another\n";
        let header = extractor.extract_header(contents, Language::Python);

        // Should be truncated
        assert!(header.len() <= 20);
    }

    #[test]
    fn test_empty_file() {
        let extractor = HeaderExtractor::new("/tmp");
        let header = extractor.extract_header("", Language::Python);
        assert!(header.is_empty());
    }

    #[test]
    fn test_no_imports() {
        let extractor = HeaderExtractor::new("/tmp");
        let contents = "def main():\n    print('hello')\n";
        let header = extractor.extract_header(contents, Language::Python);
        assert!(header.is_empty());
    }
}