File size: 31,735 Bytes
4fea3ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * PatternAnalyzer - Detects common code patterns and anti-patterns

 * Multi-language support for JavaScript, Python, Java, C#, Go, PHP, Ruby, SQL

 */

const EnhancedTokenizer = require('./enhanced-tokenizer');
const LanguageDetector = require('./language-detector');

class PatternAnalyzer {
    constructor() {
        this.patterns = this.initializePatterns();
        this.tokenizer = new EnhancedTokenizer();
        this.languageDetector = new LanguageDetector();
    }

    /**

     * Initialize pattern definitions

     */
    initializePatterns() {
        return {
            // Good Patterns
            goodPatterns: [
                {
                    name: 'Dependency Injection',
                    pattern: /constructor\s*\([^)]*\)\s*{\s*this\.\w+\s*=\s*\w+/,
                    benefit: 'Improves testability and modularity',
                    category: 'design'
                },
                {
                    name: 'Error Handling',
                    pattern: /try\s*{[^}]*}\s*catch\s*\(/,
                    benefit: 'Proper error handling',
                    category: 'reliability'
                },
                {
                    name: 'Async/Await',
                    pattern: /async\s+(?:function|\w+\s*\([^)]*\)\s*=>)/,
                    benefit: 'Modern asynchronous code',
                    category: 'modern'
                },
                {
                    name: 'Destructuring',
                    pattern: /(?:const|let|var)\s*{\s*\w+/,
                    benefit: 'Clean and readable code',
                    category: 'modern'
                },
                {
                    name: 'Template Literals',
                    pattern: /`[^`]*\$\{[^}]+\}[^`]*`/,
                    benefit: 'Better string interpolation',
                    category: 'modern'
                },
                {
                    name: 'Arrow Functions',
                    pattern: /\([^)]*\)\s*=>/,
                    benefit: 'Concise function syntax',
                    category: 'modern'
                },
                {
                    name: 'Optional Chaining',
                    pattern: /\?\./,
                    benefit: 'Safe property access',
                    category: 'modern'
                },
                {
                    name: 'Nullish Coalescing',
                    pattern: /\?\?/,
                    benefit: 'Better default value handling',
                    category: 'modern'
                },
                {
                    name: 'Spread Operator',
                    pattern: /\.\.\.\w+/,
                    benefit: 'Clean array/object manipulation',
                    category: 'modern'
                }
            ],

            // Anti-Patterns
            antiPatterns: [
                {
                    name: 'Callback Hell',
                    pattern: /function\s*\([^)]*\)\s*{\s*\w+\([^,]*,\s*function\s*\([^)]*\)\s*{\s*\w+\([^,]*,\s*function/,
                    issue: 'Deeply nested callbacks',
                    suggestion: 'Use Promises or async/await',
                    severity: 'HIGH',
                    category: 'async'
                },
                {
                    name: 'Pyramid of Doom',
                    pattern: /\s{8,}if\s*\([^)]*\)\s*{\s*\s{12,}if\s*\([^)]*\)\s*{/,
                    issue: 'Deeply nested conditionals',
                    suggestion: 'Extract functions or use early returns',
                    severity: 'MEDIUM',
                    category: 'complexity'
                },
                {
                    name: 'Magic Numbers',
                    pattern: /[^a-zA-Z_]\d{2,}[^a-zA-Z_0-9]/,
                    issue: 'Hardcoded numeric values',
                    suggestion: 'Use named constants',
                    severity: 'LOW',
                    category: 'maintainability'
                },
                {
                    name: 'Global Variables',
                    pattern: /^(?:var|let)\s+\w+\s*=/m,
                    issue: 'Global scope pollution',
                    suggestion: 'Use modules or encapsulation',
                    severity: 'MEDIUM',
                    category: 'architecture'
                },
                {
                    name: 'Empty Catch',
                    pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*(?:pass\s*)?(?:}|$)/gm,
                    issue: 'Swallowing errors without handling (JS/Python/Java/C#/etc)',
                    suggestion: 'Log or handle errors properly',
                    severity: 'HIGH',
                    category: 'reliability'
                },
                {
                    name: 'Comment-Only Catch',
                    pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*(?:\/\/|#)[^\n]*\n\s*(?:}|$)/gm,
                    issue: 'Catch block only contains comments (multi-language)',
                    suggestion: 'Add proper error handling or logging',
                    severity: 'HIGH',
                    category: 'reliability'
                },
                {
                    name: 'Console-Only Error Handling',
                    pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*(?:console\.(?:log|error|warn)|print|echo|println|NSLog|Debug\.WriteLine)\([^)]*\);\s*(?:}|$)/gm,
                    issue: 'Error only logged without proper handling (multi-language)',
                    suggestion: 'Add error recovery, user notification, or monitoring',
                    severity: 'MEDIUM',
                    category: 'reliability'
                },
                {
                    name: 'Silent Return in Catch',
                    pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*return\s*;?\s*(?:}|$)/gm,
                    issue: 'Silently returning without error handling (multi-language)',
                    suggestion: 'Log error or notify user before returning',
                    severity: 'HIGH',
                    category: 'reliability'
                },
                {
                    name: 'Var Usage',
                    pattern: /\bvar\s+\w+/,
                    issue: 'Using var instead of const/let',
                    suggestion: 'Use const or let for block scoping',
                    severity: 'LOW',
                    category: 'modern'
                },
                {
                    name: 'Function Too Long',
                    pattern: null, // Checked by line count
                    issue: 'Function exceeds reasonable length',
                    suggestion: 'Break into smaller functions',
                    severity: 'MEDIUM',
                    category: 'complexity'
                },
                {
                    name: 'Too Many Parameters',
                    pattern: /function\s+\w+\s*\([^)]{80,}\)/,
                    issue: 'Function has too many parameters',
                    suggestion: 'Use object parameter or split function',
                    severity: 'MEDIUM',
                    category: 'design'
                },
                {
                    name: 'No Default Case',
                    pattern: /switch\s*\([^)]+\)\s*{(?:(?!default:)[^}])*}/,
                    issue: 'Switch without default case',
                    suggestion: 'Add default case for safety',
                    severity: 'LOW',
                    category: 'reliability'
                },
                {
                    name: 'Direct DOM Manipulation',
                    pattern: /document\.(?:getElementById|querySelector|createElement)/,
                    issue: 'Direct DOM access in framework code',
                    suggestion: 'Use framework methods',
                    severity: 'MEDIUM',
                    category: 'framework'
                },
                {
                    name: 'Emoji Usage',
                    pattern: /[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F000}-\u{1F02F}\u{1F0A0}-\u{1F0FF}\u{1F100}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2300}-\u{23FF}\u{2B50}\u{2934}\u{2935}\u{3030}\u{303D}\u{3297}\u{3299}\u{FE0F}]/gu,
                    issue: 'Emoji characters in source code',
                    suggestion: 'Remove emojis - use text labels or icons instead',
                    severity: 'MEDIUM',
                    category: 'maintainability'
                },
                // SQL Injection Risk
                {
                    name: 'SQL Injection Risk',
                    pattern: /(?:execute|query|exec|prepare)\s*\(\s*["`'](?:SELECT|INSERT|UPDATE|DELETE|DROP).*?\+.*?["`']\s*\)/gi,
                    issue: 'Potential SQL injection vulnerability (string concatenation)',
                    suggestion: 'Use parameterized queries or prepared statements',
                    severity: 'CRITICAL',
                    category: 'security'
                },
                // Hardcoded Credentials
                {
                    name: 'Hardcoded Credentials',
                    pattern: /(?:password|passwd|pwd|secret|api_key|apikey|token|auth)\s*=\s*["`'][^"`'\s]{8,}["`']/gi,
                    issue: 'Hardcoded credentials in source code',
                    suggestion: 'Use environment variables or secure credential storage',
                    severity: 'CRITICAL',
                    category: 'security'
                },
                // eval() Usage
                {
                    name: 'Dangerous eval Usage',
                    pattern: /\beval\s*\(/g,
                    issue: 'Use of eval() is dangerous and can lead to code injection',
                    suggestion: 'Use safer alternatives like JSON.parse() or Function constructor',
                    severity: 'CRITICAL',
                    category: 'security'
                },
                // TODO in Production Code
                {
                    name: 'TODO Comments',
                    pattern: /(?:\/\/|\/\*|#|\-\-)\s*TODO:?/gi,
                    issue: 'Unfinished work or technical debt',
                    suggestion: 'Complete implementation or create task ticket',
                    severity: 'LOW',
                    category: 'maintainability'
                },
                // FIXME in Production Code
                {
                    name: 'FIXME Comments',
                    pattern: /(?:\/\/|\/\*|#|\-\-)\s*FIXME:?/gi,
                    issue: 'Known bugs or issues that need fixing',
                    suggestion: 'Fix the issue or create bug ticket',
                    severity: 'HIGH',
                    category: 'reliability'
                },
                // XXX/HACK Comments
                {
                    name: 'HACK Comments',
                    pattern: /(?:\/\/|\/\*|#|\-\-)\s*(?:XXX|HACK):?/gi,
                    issue: 'Workarounds or hacky solutions',
                    suggestion: 'Refactor to use proper solution',
                    severity: 'MEDIUM',
                    category: 'maintainability'
                },
                // Debugger Statements
                {
                    name: 'Debugger Statements',
                    pattern: /\bdebugger\s*;/g,
                    issue: 'Debug breakpoints left in production code',
                    suggestion: 'Remove debugger statements',
                    severity: 'HIGH',
                    category: 'quality'
                },
                // console.log in Production
                {
                    name: 'Console Statements',
                    pattern: /console\.(?:log|debug|info|warn)\s*\(/g,
                    issue: 'Console statements may leak sensitive info or affect performance',
                    suggestion: 'Remove or replace with proper logging framework',
                    severity: 'LOW',
                    category: 'quality'
                },
                // Nested Try-Catch
                {
                    name: 'Nested Try-Catch',
                    pattern: /try\s*{[^}]*try\s*{/g,
                    issue: 'Nested try-catch blocks increase complexity',
                    suggestion: 'Refactor to single error handling layer',
                    severity: 'MEDIUM',
                    category: 'complexity'
                },
                // Multiple Returns
                {
                    name: 'Multiple Return Points',
                    pattern: /return\s+[^;]+;(?:[^}]*return\s+[^;]+;){3,}/g,
                    issue: 'Too many return statements in single function',
                    suggestion: 'Simplify logic or use early returns pattern consistently',
                    severity: 'LOW',
                    category: 'complexity'
                },
                // Deep Nesting (Generic)
                {
                    name: 'Deep Nesting',
                    pattern: /\s{16,}(?:if|for|while|switch)\s*\(/g,
                    issue: 'Code nested too deeply (4+ levels)',
                    suggestion: 'Extract nested logic into separate functions',
                    severity: 'MEDIUM',
                    category: 'complexity'
                },
                // Large File Size (will be checked separately)
                {
                    name: 'Large File',
                    pattern: null,
                    issue: 'File exceeds recommended size',
                    suggestion: 'Split into smaller modules',
                    severity: 'LOW',
                    category: 'maintainability'
                },
                // Python-specific
                {
                    name: 'Python pickle Usage',
                    pattern: /pickle\.loads?\s*\(/g,
                    issue: 'Unsafe deserialization with pickle',
                    suggestion: 'Use JSON or validate input',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['python']
                },
                {
                    name: 'Python exec/eval',
                    pattern: /\b(?:exec|eval)\s*\(/g,
                    issue: 'Dynamic code execution is dangerous',
                    suggestion: 'Avoid exec/eval or sanitize input',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['python']
                },
                // Java-specific
                {
                    name: 'Java Deserialization',
                    pattern: /ObjectInputStream|readObject/g,
                    issue: 'Unsafe deserialization vulnerability',
                    suggestion: 'Validate deserialized objects',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['java']
                },
                {
                    name: 'Java Reflection',
                    pattern: /Class\.forName|Method\.invoke/g,
                    issue: 'Reflection can bypass security',
                    suggestion: 'Use compile-time alternatives',
                    severity: 'HIGH',
                    category: 'security',
                    languages: ['java']
                },
                // PHP-specific
                {
                    name: 'PHP shell_exec',
                    pattern: /(?:shell_exec|exec|system|passthru|proc_open)\s*\(/g,
                    issue: 'Command injection vulnerability',
                    suggestion: 'Validate and escape all inputs',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['php']
                },
                {
                    name: 'PHP unserialize',
                    pattern: /unserialize\s*\(/g,
                    issue: 'Unsafe deserialization',
                    suggestion: 'Use JSON instead',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['php']
                },
                // Go-specific
                {
                    name: 'Go Command Injection',
                    pattern: /exec\.Command\s*\([^)]*\+/g,
                    issue: 'Command injection risk',
                    suggestion: 'Use exec.Command with separate arguments',
                    severity: 'HIGH',
                    category: 'security',
                    languages: ['go']
                },
                // Ruby-specific
                {
                    name: 'Ruby Marshal.load',
                    pattern: /Marshal\.load/g,
                    issue: 'Unsafe deserialization',
                    suggestion: 'Use JSON instead',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['ruby']
                },
                {
                    name: 'Ruby Command Execution',
                    pattern: /`[^`]*`|%x\{|system\s*\(|exec\s*\(/g,
                    issue: 'Command injection risk',
                    suggestion: 'Validate inputs',
                    severity: 'HIGH',
                    category: 'security',
                    languages: ['ruby']
                },
                // SQL-specific
                {
                    name: 'Dynamic SQL',
                    pattern: /EXECUTE\s+[@\w]+|EXEC\s*\(|sp_executesql/gi,
                    issue: 'Dynamic SQL can lead to injection',
                    suggestion: 'Use parameterized queries',
                    severity: 'HIGH',
                    category: 'security',
                    languages: ['sql']
                },
                {
                    name: 'xp_cmdshell',
                    pattern: /xp_cmdshell/gi,
                    issue: 'OS command execution from SQL',
                    suggestion: 'Avoid xp_cmdshell',
                    severity: 'CRITICAL',
                    category: 'security',
                    languages: ['sql']
                }
            ],

            // Code Smells
            codeSmells: [
                {
                    name: 'Duplicate Code',
                    check: 'duplication',
                    category: 'duplication'
                },
                {
                    name: 'Long Method',
                    check: 'longMethod',
                    category: 'complexity'
                },
                {
                    name: 'Large Class',
                    check: 'largeClass',
                    category: 'complexity'
                },
                {
                    name: 'Feature Envy',
                    pattern: /this\.\w+\.\w+\.\w+\.\w+/,
                    issue: 'Excessive chaining',
                    category: 'coupling'
                },
                {
                    name: 'Data Clumps',
                    check: 'repeatedParameters',
                    category: 'design'
                }
            ]
        };
    }

    /**

     * Analyze file for patterns

     */
    analyze(filePath, content) {
        // Detect language
        const langInfo = this.languageDetector.detectFromPath(filePath);
        
        const findings = {
            filePath,
            language: langInfo.language,
            goodPatterns: this.detectGoodPatterns(content, langInfo.language),
            antiPatterns: this.detectAntiPatterns(content, langInfo.language),
            codeSmells: this.detectCodeSmells(content, langInfo.language),
            annotations: this.detectAnnotations(content, filePath),
            score: 0,
            recommendations: []
        };

        findings.score = this.calculateScore(findings);
        findings.recommendations = this.generateRecommendations(findings);

        return findings;
    }

    /**

     * Detect annotations (TODO/FIXME/BUG) using Tokenizer

     * 100% accurate - no false positives from strings or commented-out code

     */
    detectAnnotations(content, filePath) {
        const tokens = this.tokenizer.tokenize(content, filePath);
        const annotations = this.tokenizer.findAnnotations(tokens);
        
        return annotations.map(ann => ({
            type: ann.type,
            text: ann.text,
            line: ann.line,
            author: ann.author || 'Unknown',
            context: ann.context || ''
        }));
    }

    /**

     * Detect good patterns

     */
    detectGoodPatterns(content, language = 'javascript') {
        const found = [];

        this.patterns.goodPatterns.forEach(pattern => {
            if (!pattern.pattern) return;
            
            // Filter language-specific patterns
            if (pattern.languages && !pattern.languages.includes(language)) {
                return; // Skip if not applicable to this language
            }
            
            const matches = content.match(pattern.pattern);
            if (matches) {
                found.push({
                    name: pattern.name,
                    count: matches.length,
                    benefit: pattern.benefit,
                    category: pattern.category
                });
            }
        });

        return found;
    }

    /**

     * Detect anti-patterns

     */
    detectAntiPatterns(content, language = 'javascript') {
        const found = [];

        this.patterns.antiPatterns.forEach(antiPattern => {
            if (!antiPattern.pattern) return;
            
            // Filter language-specific patterns
            if (antiPattern.languages && !antiPattern.languages.includes(language)) {
                return; // Skip if not applicable to this language
            }

            const matches = content.match(antiPattern.pattern);
            if (matches) {
                found.push({
                    name: antiPattern.name,
                    count: matches.length,
                    issue: antiPattern.issue,
                    suggestion: antiPattern.suggestion,
                    severity: antiPattern.severity,
                    category: antiPattern.category
                });
            }
        });

        // Check for long functions
        const functions = this.extractFunctions(content);
        const longFunctions = functions.filter(f => f.lines > 50);
        if (longFunctions.length > 0) {
            found.push({
                name: 'Function Too Long',
                count: longFunctions.length,
                issue: 'Functions exceed 50 lines',
                suggestion: 'Break into smaller functions',
                severity: 'MEDIUM',
                category: 'complexity'
            });
        }

        // Check for large files
        const lines = content.split('\n').length;
        if (lines > 500) {
            found.push({
                name: 'Large File',
                count: 1,
                issue: `File has ${lines} lines (recommended: < 500)`,
                suggestion: 'Split into smaller modules',
                severity: lines > 1000 ? 'HIGH' : 'MEDIUM',
                category: 'maintainability'
            });
        }

        return found;
    }

    /**

     * Detect code smells

     */
    detectCodeSmells(content, language = 'javascript') {
        const smells = [];

        // Feature Envy (excessive chaining)
        const chains = content.match(/this\.\w+\.\w+\.\w+\.\w+/g);
        if (chains && chains.length > 0) {
            smells.push({
                name: 'Feature Envy',
                count: chains.length,
                issue: 'Excessive method chaining',
                category: 'coupling'
            });
        }

        // Duplicate code (simple check for repeated lines)
        const lines = content.split('\n').filter(l => l.trim().length > 20);
        const duplicates = this.findDuplicateLines(lines);
        if (duplicates.length > 0) {
            smells.push({
                name: 'Duplicate Code',
                count: duplicates.length,
                issue: 'Code duplication detected',
                category: 'duplication'
            });
        }

        // Large class
        const classMatch = content.match(/class\s+\w+\s*{([^}]+)}/);
        if (classMatch) {
            const methods = (classMatch[1].match(/\w+\s*\([^)]*\)\s*{/g) || []).length;
            if (methods > 20) {
                smells.push({
                    name: 'Large Class',
                    count: methods,
                    issue: 'Class has too many methods',
                    category: 'complexity'
                });
            }
        }

        // Data clumps (repeated parameter patterns)
        const paramPatterns = {};
        const funcMatches = content.match(/function\s+\w+\s*\(([^)]+)\)/g) || [];
        funcMatches.forEach(match => {
            const params = match.match(/\(([^)]+)\)/)[1];
            paramPatterns[params] = (paramPatterns[params] || 0) + 1;
        });

        Object.entries(paramPatterns).forEach(([params, count]) => {
            if (count > 2 && params.split(',').length > 2) {
                smells.push({
                    name: 'Data Clumps',
                    count,
                    issue: 'Same parameters repeated across functions',
                    category: 'design'
                });
            }
        });

        return smells;
    }

    /**

     * Find duplicate lines

     */
    findDuplicateLines(lines) {
        const lineCount = {};
        const duplicates = [];

        lines.forEach(line => {
            const trimmed = line.trim();
            if (trimmed.length > 20) {
                lineCount[trimmed] = (lineCount[trimmed] || 0) + 1;
            }
        });

        Object.entries(lineCount).forEach(([line, count]) => {
            if (count > 1) {
                duplicates.push({ line, occurrences: count });
            }
        });

        return duplicates;
    }

    /**

     * Extract functions

     */
    extractFunctions(content) {
        const functions = [];
        const lines = content.split('\n');
        
        let inFunction = false;
        let braceCount = 0;
        let startLine = 0;
        let currentFunction = '';

        lines.forEach((line, index) => {
            if (/(?:function\s+\w+|(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\()/.test(line)) {
                inFunction = true;
                startLine = index;
                currentFunction = line.match(/(?:function\s+(\w+)|(?:const|let|var)\s+(\w+))/)?.[1] || 'anonymous';
            }

            if (inFunction) {
                braceCount += (line.match(/{/g) || []).length;
                braceCount -= (line.match(/}/g) || []).length;

                if (braceCount === 0 && index > startLine) {
                    functions.push({
                        name: currentFunction,
                        lines: index - startLine + 1
                    });
                    inFunction = false;
                }
            }
        });

        return functions;
    }

    /**

     * Calculate pattern score

     */
    calculateScore(findings) {
        let score = 100;

        // Add points for good patterns
        findings.goodPatterns.forEach(gp => {
            score += gp.count * 2;
        });

        // Deduct for anti-patterns
        findings.antiPatterns.forEach(ap => {
            if (ap.severity === 'HIGH') score -= ap.count * 10;
            else if (ap.severity === 'MEDIUM') score -= ap.count * 5;
            else score -= ap.count * 2;
        });

        // Deduct for code smells
        findings.codeSmells.forEach(cs => {
            score -= cs.count * 3;
        });

        return Math.max(0, Math.min(100, score));
    }

    /**

     * Generate recommendations

     */
    generateRecommendations(findings) {
        const recommendations = [];

        // Prioritize high severity anti-patterns
        const highSeverity = findings.antiPatterns.filter(ap => ap.severity === 'HIGH');
        if (highSeverity.length > 0) {
            recommendations.push({
                priority: 'HIGH',
                message: `Address ${highSeverity.length} high-severity anti-patterns`,
                actions: highSeverity.map(ap => ap.suggestion)
            });
        }

        // Code smell recommendations
        if (findings.codeSmells.length > 3) {
            recommendations.push({
                priority: 'MEDIUM',
                message: 'Refactor to address code smells',
                actions: findings.codeSmells.slice(0, 3).map(cs => `Fix ${cs.name}`)
            });
        }

        // Suggest modern patterns
        const modernPatterns = ['Async/Await', 'Optional Chaining', 'Nullish Coalescing'];
        const missingModern = modernPatterns.filter(mp => 
            !findings.goodPatterns.some(gp => gp.name === mp)
        );
        if (missingModern.length > 0) {
            recommendations.push({
                priority: 'LOW',
                message: 'Consider using modern JavaScript features',
                actions: missingModern.map(mp => `Adopt ${mp}`)
            });
        }

        return recommendations;
    }

    /**

     * Generate pattern report

     */
    generateReport(allFindings) {
        const summary = {
            totalFiles: allFindings.length,
            averageScore: 0,
            goodPatternUsage: {},
            antiPatternCount: {},
            codeSmellCount: {},
            topIssues: [],
            bestPractices: []
        };

        allFindings.forEach(finding => {
            summary.averageScore += finding.score;

            // Count good patterns
            finding.goodPatterns.forEach(gp => {
                summary.goodPatternUsage[gp.name] = (summary.goodPatternUsage[gp.name] || 0) + gp.count;
            });

            // Count anti-patterns
            finding.antiPatterns.forEach(ap => {
                summary.antiPatternCount[ap.name] = (summary.antiPatternCount[ap.name] || 0) + ap.count;
            });

            // Count code smells
            finding.codeSmells.forEach(cs => {
                summary.codeSmellCount[cs.name] = (summary.codeSmellCount[cs.name] || 0) + cs.count;
            });
        });

        summary.averageScore = Math.round(summary.averageScore / allFindings.length);

        // Top issues
        summary.topIssues = Object.entries(summary.antiPatternCount)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([name, count]) => ({ name, count }));

        // Best practices
        summary.bestPractices = Object.entries(summary.goodPatternUsage)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([name, count]) => ({ name, count }));

        return summary;
    }
}

module.exports = PatternAnalyzer;