File size: 27,284 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
#!/usr/bin/env node
// Smart Roadmap - Main Scanner
// AI-Powered Development Roadmap Generator
// Version: 1.0.0
// Author: Chahua Development Co., Ltd.

const fs = require('fs');
const path = require('path');

// Security
const {
    validateInput,
    isPathSafe,
    sanitizePath,
    checkFilePermissions,
    isAllowedExtension,
    checkFileSize
} = require('./security/path-validator');
const { SecurityError } = require('./security/security-config');
const SymlinkChecker = require('./security/symlink-checker');
const ReDoSProtector = require('./security/redos-protector');

// Scanners
const CodeQualityScanner = require('./scanners/code-quality-scanner');
const DependencyScanner = require('./scanners/dependency-scanner');
const SecurityScanner = require('./scanners/security-scanner');
const ArchitectureScanner = require('./scanners/architecture-scanner');
const TestCoverageScanner = require('./scanners/test-coverage-scanner');

// Analyzers
const ComplexityAnalyzer = require('./analyzers/complexity-analyzer');
const PriorityAnalyzer = require('./analyzers/priority-analyzer');
const PatternAnalyzer = require('./analyzers/pattern-analyzer');
const PhaseAnalyzer = require('./analyzers/phase-analyzer');
const BugTracker = require('./analyzers/bug-tracker');
const ProgressCalculator = require('./analyzers/progress-calculator');
const RiskAnalyzer = require('./analyzers/risk-analyzer');
const CodeContextAnalyzer = require('./analyzers/code-context-analyzer');
const DependencyAnalyzer = require('./analyzers/dependency-analyzer'); // NEW
const DuplicationDetector = require('./analyzers/duplication-detector'); // NEW
const PerformanceAnalyzer = require('./analyzers/performance-analyzer'); // NEW
const GitContextAnalyzer = require('./analyzers/git-context-analyzer'); // NEW - Zero-Dependency Git Integration

// Reporters
const JSONReporter = require('./reporters/json-reporter');
const MarkdownReporter = require('./reporters/markdown-reporter');
const HTMLReporter = require('./reporters/html-reporter');

// Configuration
const defaultConfig = require('./config/default-config');


// Configuration
const DEFAULT_CONFIG = {
    scanDirs: ['.'],  // Scan entire project from root
    ignorePatterns: [
        'node_modules',
        '.git',
        'dist',
        'build',
        'coverage',
        'logs',
        '.next',
        '.nuxt',
        'out',
        'tmp',
        'docs',                         // Ignore docs output folder
        '*.log',                        // Ignore log files
        'project-analysis.json',        // Ignore output files
        'DEVELOPMENT_ROADMAP*.md',      // Ignore generated roadmaps
        'dashboard.html'                // Ignore generated dashboards
    ],
    fileExtensions: [
        '.js', '.ts', '.jsx', '.tsx', '.mjs',  // JavaScript/TypeScript
        '.py',                                  // Python
        '.java',                                // Java
        '.cs',                                  // C#
        '.go',                                  // Go
        '.php',                                 // PHP
        '.rb',                                  // Ruby
        '.cpp', '.cc', '.cxx', '.c', '.h',     // C/C++
        '.swift',                               // Swift
        '.kt', '.kts',                          // Kotlin
        '.rs',                                  // Rust
        '.scala',                               // Scala
        '.sql',                                 // SQL
        '.css', '.scss', '.sass', '.less',     // CSS
        '.html', '.htm',                        // HTML
        '.xml',                                 // XML
        '.yaml', '.yml',                        // YAML
        '.json',                                // JSON
        '.md', '.markdown'                      // Markdown
    ],
    outputDir: './',
    enableSecurity: true,
    complexityThreshold: 10,
    verbose: false
};

class SmartRoadmapScanner {
    constructor(options = {}) {
        this.config = { ...DEFAULT_CONFIG, ...defaultConfig, ...options };
        this.projectRoot = path.resolve(this.config.projectPath || process.cwd());
        
        // Initialize Git context analyzer (Zero-Dependency)
        this.gitContext = new GitContextAnalyzer(this.projectRoot);
        
        // Initialize all scanners
        this.scanners = {
            quality: new CodeQualityScanner(),
            dependency: new DependencyScanner(),
            security: new SecurityScanner(),
            architecture: new ArchitectureScanner(),
            testCoverage: new TestCoverageScanner()
        };

        // Initialize analyzers (pass projectRoot to PriorityAnalyzer for Git context)
        this.analyzers = {
            complexity: new ComplexityAnalyzer(),
            priority: new PriorityAnalyzer(this.projectRoot),
            pattern: new PatternAnalyzer(),
            phase: new PhaseAnalyzer(),
            bugTracker: new BugTracker(),
            progress: new ProgressCalculator(),
            risk: new RiskAnalyzer(),
            context: new CodeContextAnalyzer(),
            dependency: new DependencyAnalyzer(), // NEW - Deep dependency analysis
            duplication: new DuplicationDetector(), // NEW - Code duplication detection
            performance: new PerformanceAnalyzer() // NEW - Performance bottleneck detection
        };

        // Initialize reporters
        this.reporters = {
            json: new JSONReporter(),
            markdown: new MarkdownReporter(),
            html: new HTMLReporter()
        };

        // Initialize security
        this.symlinkChecker = new SymlinkChecker();
        this.redosProtector = new ReDoSProtector();
        
        this.stats = {
            filesScanned: 0,
            linesOfCode: 0,
            completedFeatures: [],
            todoItems: [],
            fixmeItems: [],
            bugItems: [],
            unimplementedItems: [],
            imports: new Map(),
            exports: new Map(),
            testFiles: [],
            allFindings: []
        };

        // Patterns for detection
        this.patterns = {
            todo: /(?:\/\/|\/\*|\*|#)\s*TODO:?\s*(.+?)(?:\*\/|$)/gi,
            fixme: /(?:\/\/|\/\*|\*|#)\s*FIXME:?\s*(.+?)(?:\*\/|$)/gi,
            bug: /(?:\/\/|\/\*|\*|#)\s*BUG:?\s*(.+?)(?:\*\/|$)/gi,
            completed: /(?:function|class|const|let|export)\s+(\w+)/g,
            emptyFunction: /(?:function|const|let)\s+(\w+)\s*(?:=\s*)?(?:\([^)]*\))?\s*(?:=>)?\s*\{\s*\}/g,
            notImplemented: /throw\s+new\s+(?:Error|NotImplementedError)\s*\(\s*['"](?:Not implemented|TODO|FIXME)/gi,
            imports: /import\s+.*?from\s+['"]([^'"]+)['"]/g,
            exports: /export\s+(?:default\s+)?(?:class|function|const|let|var)\s+(\w+)/g
        };
    }

    // Scan entire project
    async scan() {
        console.log('[SCAN] Starting comprehensive project analysis...\n');
        
        const startTime = Date.now();

        // Scan configured directories
        for (const dir of this.config.scanDirs) {
            const dirPath = path.join(this.projectRoot, dir);
            if (fs.existsSync(dirPath)) {
                await this.scanDirectory(dirPath, dir);
            }
        }

        const duration = ((Date.now() - startTime) / 1000).toFixed(2);

        // Collect all tasks from findings
        const allTasks = this.collectTasks();

        // Run priority analyzer
        const prioritizedTasks = this.analyzers.priority.analyze(allTasks);

        // Run deep code context analysis
        const contextAnalysis = this.analyzers.context.analyze(this.stats.allFindings);

        // Run NEW advanced analyzers (before clearing content)
        console.log('[ANALYZING] Running advanced dependency analysis...');
        const dependencyAnalysis = this.analyzers.dependency.analyze(this.stats.allFindings);
        
        console.log('[ANALYZING] Running code duplication detection...');
        const duplicationAnalysis = this.analyzers.duplication.analyze(this.stats.allFindings);
        
        console.log('[ANALYZING] Running performance pattern detection...');
        const performanceAnalysis = this.analyzers.performance.analyze(this.stats.allFindings);

        // Clear content from findings to save memory (keep only analysis results)
        this.stats.allFindings.forEach(finding => {
            delete finding.content; // Remove content after analysis
        });

        // Run new analyzers
        const phaseAnalysis = this.analyzers.phase.analyze(prioritizedTasks, this.stats.allFindings);
        const bugAnalysis = this.analyzers.bugTracker.track(prioritizedTasks, this.stats.allFindings);
        
        // Analyze Git project history (Zero-Dependency)
        console.log('[ANALYZING] Analyzing Git project history...');
        let gitHistory = null;
        try {
            gitHistory = this.gitContext.analyzeProjectHistory();
        } catch (error) {
            console.warn('[WARNING] Git analysis failed (not a Git repository or Git not available)');
        }
        
        // Generate comprehensive reports
        const analysis = {
            metadata: {
                projectPath: this.projectRoot,
                projectName: path.basename(this.projectRoot),
                scannedAt: new Date().toISOString(),
                duration: `${duration}s`,
                scanner: 'smart-roadmap v1.0.0',
                parserUsed: this.analyzers.complexity.getParserUsed() || 'built-in'
            },
            summary: this.generateSummary(prioritizedTasks),
            files: this.stats.allFindings,
            tasks: prioritizedTasks,
            phases: phaseAnalysis,
            bugs: bugAnalysis,
            context: contextAnalysis, // Deep code context
            git: gitHistory, // NEW - Git project history (commits, authors, change frequency)
            dependencies: dependencyAnalysis, // NEW - Dependency graph analysis
            duplication: duplicationAnalysis, // NEW - Code duplication detection
            performance: performanceAnalysis, // NEW - Performance bottleneck detection
            metrics: this.generateMetrics(),
            issues: this.generateIssues(prioritizedTasks)
        };

        // Calculate progress and risk after we have all data
        analysis.progress = this.analyzers.progress.calculate(analysis);
        analysis.risk = this.analyzers.risk.analyze(analysis);

        if (this.config.verbose) {
            console.log('[DEBUG] Phases:', analysis.phases ? 'YES' : 'NO');
            console.log('[DEBUG] Bugs:', analysis.bugs ? 'YES' : 'NO');
            console.log('[DEBUG] Progress:', analysis.progress ? 'YES' : 'NO');
            console.log('[DEBUG] Risk:', analysis.risk ? 'YES' : 'NO');
        }

        this.printSummary(analysis.summary);

        // Save reports
        await this.saveReports(analysis);

        return analysis;
    }

    // Collect all tasks from findings
    collectTasks() {
        const tasks = [];

        this.stats.allFindings.forEach(finding => {
            // Add security issues as tasks
            if (finding.security) {
                ['critical', 'high', 'medium', 'low'].forEach(severity => {
                    if (finding.security[severity]) {
                        finding.security[severity].forEach(issue => {
                            tasks.push({
                                title: issue.message,
                                message: issue.message,
                                type: 'security',
                                severity: severity.toUpperCase(),
                                filePath: finding.filePath,
                                line: issue.line,
                                completed: false
                            });
                        });
                    }
                });
            }

            // Add quality issues as tasks
            if (finding.quality && finding.quality.codeSmells) {
                finding.quality.codeSmells.forEach(smell => {
                    tasks.push({
                        title: smell.type,
                        message: `${smell.type}: ${smell.count} occurrences`,
                        type: 'code-smell',
                        severity: smell.severity || 'MEDIUM',
                        filePath: finding.filePath,
                        completed: false
                    });
                });
            }

            // Add architecture issues as tasks
            if (finding.architecture && finding.architecture.antiPatterns) {
                finding.architecture.antiPatterns.forEach(ap => {
                    tasks.push({
                        title: ap.type,
                        message: ap.message || ap.type,
                        type: 'architecture',
                        severity: ap.severity,
                        filePath: finding.filePath,
                        completed: false
                    });
                });
            }
        });

        // Add legacy TODO/FIXME items
        this.stats.todoItems.forEach(todo => {
            tasks.push({
                title: todo.message,
                message: todo.message,
                type: 'todo',
                severity: 'MEDIUM',
                filePath: todo.file,
                line: todo.line,
                completed: false
            });
        });

        this.stats.fixmeItems.forEach(fixme => {
            tasks.push({
                title: fixme.message,
                message: fixme.message,
                type: 'bug',
                severity: 'CRITICAL',
                filePath: fixme.file,
                line: fixme.line,
                completed: false
            });
        });

        return tasks;
    }

    // Generate summary statistics
    generateSummary(prioritizedTasks) {
        return {
            totalFiles: this.stats.filesScanned,
            totalLines: this.stats.linesOfCode,
            totalTasks: prioritizedTasks.length,
            completedTasks: prioritizedTasks.filter(t => t.completed).length,
            pendingTasks: prioritizedTasks.filter(t => !t.completed).length,
            criticalIssues: prioritizedTasks.filter(t => t.priorityLevel === 'CRITICAL').length,
            highIssues: prioritizedTasks.filter(t => t.priorityLevel === 'HIGH').length,
            mediumIssues: prioritizedTasks.filter(t => t.priorityLevel === 'MEDIUM').length,
            lowIssues: prioritizedTasks.filter(t => t.priorityLevel === 'LOW').length,
            qualityScore: this.calculateQualityScore(prioritizedTasks)
        };
    }

    // Generate metrics summary
    generateMetrics() {
        const complexityMetrics = this.stats.allFindings
            .filter(f => f.complexity)
            .map(f => f.complexity);

        const patternMetrics = this.stats.allFindings
            .filter(f => f.patterns)
            .map(f => f.patterns);

        return {
            complexity: this.analyzers.complexity.generateReport(complexityMetrics),
            patterns: this.analyzers.pattern.generateReport(patternMetrics),
            architecture: this.scanners.architecture.generateReport(
                this.stats.allFindings.filter(f => f.architecture).map(f => f.architecture)
            ),
            testCoverage: this.scanners.testCoverage.generateReport(
                this.stats.allFindings.filter(f => f.testCoverage).map(f => f.testCoverage)
            )
        };
    }

    // Generate issues list
    generateIssues(prioritizedTasks) {
        return prioritizedTasks.slice(0, 50); // Top 50 issues
    }

    // Calculate overall quality score
    calculateQualityScore(tasks) {
        let score = 100;
        
        tasks.forEach(task => {
            if (task.priorityLevel === 'CRITICAL') score -= 10;
            else if (task.priorityLevel === 'HIGH') score -= 5;
            else if (task.priorityLevel === 'MEDIUM') score -= 2;
        });

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

    // Save all report formats
    async saveReports(analysis) {
        const outputDir = this.config.outputDir;

        try {
            // Save JSON report
            await this.reporters.json.save(analysis, path.join(outputDir, 'project-analysis.json'));
            console.log('\n[SAVED] project-analysis.json');

            // Save Markdown roadmap
            await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.md'), 'roadmap');
            console.log('[SAVED] DEVELOPMENT_ROADMAP.md');

        // Save HTML dashboard
        await this.reporters.html.save(analysis, path.join(outputDir, 'dashboard.html'));
        console.log('[SAVED] dashboard.html');        } catch (error) {
            console.error('[ERROR] Failed to save reports:', error.message);
        }
    }

    // Scan directory recursively
    async scanDirectory(dirPath, relativePath = '') {
        try {
            if (this.config.enableSecurity) {
                isPathSafe(dirPath);
            }

            const entries = fs.readdirSync(dirPath, { withFileTypes: true });

            for (const entry of entries) {
                const fullPath = path.join(dirPath, entry.name);
                const relPath = path.join(relativePath, entry.name);

                // Check ignore patterns
                if (this.shouldIgnore(relPath, entry.name)) {
                    continue;
                }

                if (entry.isDirectory()) {
                    await this.scanDirectory(fullPath, relPath);
                } else if (entry.isFile() && this.shouldScanFile(entry.name)) {
                    await this.scanFile(fullPath, relPath);
                }
            }
        } catch (error) {
            if (error instanceof SecurityError) {
                console.warn(`[WARNING] Security: ${error.message}`);
            } else {
                console.warn(`[WARNING] Cannot scan ${dirPath}: ${error.message}`);
            }
        }
    }

    // Check if path should be ignored
    shouldIgnore(relPath, name) {
        const normalizedPath = relPath.replace(/\\/g, '/');
        
        return this.config.ignorePatterns.some(pattern => {
            return name.includes(pattern) || normalizedPath.includes(pattern);
        });
    }

    // Check if file should be scanned
    shouldScanFile(filename) {
        return this.config.fileExtensions.some(ext => filename.endsWith(ext));
    }

    // Scan individual file
    async scanFile(filePath, relativePath) {
        try {
            if (this.config.enableSecurity) {
                sanitizePath(filePath);
                checkFilePermissions(filePath, false);
                checkFileSize(filePath);
            }

            const content = fs.readFileSync(filePath, 'utf8');
            const lines = content.split('\n');

            this.stats.filesScanned++;
            this.stats.linesOfCode += lines.length;

            // Run all scanners
            const findings = {
                filePath: relativePath,
                content: content, // Store content for deep analysis
                language: '', // Will be set from patterns analyzer
                linesOfCode: lines.length,
                quality: this.scanners.quality.scan(content, filePath),
                dependencies: this.scanners.dependency.scan(content, filePath),
                security: this.scanners.security.scan(content, filePath),
                architecture: this.scanners.architecture.scan(filePath, content),
                testCoverage: this.scanners.testCoverage.scan(filePath, content),
                complexity: this.analyzers.complexity.analyze(filePath, content),
                patterns: this.analyzers.pattern.analyze(filePath, content)
            };
            
            // Set language from patterns analyzer
            findings.language = findings.patterns?.language || 'unknown';

            // Store findings
            this.stats.allFindings.push(findings);

            // Legacy pattern scanning (for backwards compatibility)
            this.scanCompletedFeatures(content, relativePath, lines);
            this.scanIssues(content, relativePath, lines);
            this.scanUnimplemented(content, relativePath);
            this.scanDependencies(content, relativePath);

            // Detect test files
            if (relativePath.includes('test') || relativePath.includes('spec')) {
                this.stats.testFiles.push(relativePath);
            }

        } catch (error) {
            if (this.config.verbose) {
                console.warn(`[WARNING] Error scanning ${relativePath}: ${error.message}`);
            }
        }
    }

    // Scan for completed features
    scanCompletedFeatures(content, relativePath, lines) {
        let match;
        while ((match = this.patterns.completed.exec(content)) !== null) {
            const lineNumber = content.substring(0, match.index).split('\n').length;
            this.stats.completedFeatures.push({
                name: match[1],
                file: relativePath,
                line: lineNumber,
                type: 'completed'
            });
        }
    }

    // Scan for issues (TODO, FIXME, BUG)
    scanIssues(content, relativePath, lines) {
        // TODO comments
        let match;
        while ((match = this.patterns.todo.exec(content)) !== null) {
            const lineNumber = content.substring(0, match.index).split('\n').length;
            this.stats.todoItems.push({
                file: relativePath,
                line: lineNumber,
                message: (match[1] || '').trim(),
                priority: 'MEDIUM'
            });
        }

        // FIXME comments
        while ((match = this.patterns.fixme.exec(content)) !== null) {
            const lineNumber = content.substring(0, match.index).split('\n').length;
            this.stats.fixmeItems.push({
                file: relativePath,
                line: lineNumber,
                message: (match[1] || '').trim(),
                priority: 'CRITICAL'
            });
        }

        // BUG comments
        while ((match = this.patterns.bug.exec(content)) !== null) {
            const lineNumber = content.substring(0, match.index).split('\n').length;
            this.stats.bugItems.push({
                file: relativePath,
                line: lineNumber,
                message: (match[1] || '').trim(),
                priority: 'CRITICAL'
            });
        }
    }

    // Scan for unimplemented code
    scanUnimplemented(content, relativePath) {
        // Empty functions
        let match;
        while ((match = this.patterns.emptyFunction.exec(content)) !== null) {
            const lineNumber = content.substring(0, match.index).split('\n').length;
            this.stats.unimplementedItems.push({
                type: 'empty-function',
                name: match[1],
                file: relativePath,
                line: lineNumber,
                priority: 'MEDIUM'
            });
        }

        // Not implemented throws
        while ((match = this.patterns.notImplemented.exec(content)) !== null) {
            const lineNumber = content.substring(0, match.index).split('\n').length;
            this.stats.unimplementedItems.push({
                type: 'not-implemented',
                name: 'unknown',
                file: relativePath,
                line: lineNumber,
                priority: 'HIGH'
            });
        }
    }

    // Scan dependencies
    scanDependencies(content, relativePath) {
        // Imports
        let match;
        while ((match = this.patterns.imports.exec(content)) !== null) {
            const imported = match[1];
            if (!this.stats.imports.has(imported)) {
                this.stats.imports.set(imported, []);
            }
            this.stats.imports.get(imported).push(relativePath);
        }

        // Exports
        while ((match = this.patterns.exports.exec(content)) !== null) {
            const exported = match[1];
            if (!this.stats.exports.has(exported)) {
                this.stats.exports.set(exported, []);
            }
            this.stats.exports.get(exported).push(relativePath);
        }
    }

    // Print summary
    printSummary(summary) {
        console.log('\n' + '='.repeat(70));
        console.log('[SUMMARY] Smart Roadmap Analysis');
        console.log('='.repeat(70));
        console.log(`Files Scanned:         ${summary.totalFiles}`);
        console.log(`Lines of Code:         ${summary.totalLines.toLocaleString()}`);
        console.log(`Quality Score:         ${summary.qualityScore}/100`);
        console.log(`\nTasks:`);
        console.log(`  Total:               ${summary.totalTasks}`);
        console.log(`  Completed:           ${summary.completedTasks}`);
        console.log(`  Pending:             ${summary.pendingTasks}`);
        console.log(`\nPriority Breakdown:`);
        console.log(`  Critical:            ${summary.criticalIssues}`);
        console.log(`  High:                ${summary.highIssues}`);
        console.log(`  Medium:              ${summary.mediumIssues}`);
        console.log(`  Low:                 ${summary.lowIssues}`);
        console.log('='.repeat(70) + '\n');
    }

    // Save reports to files
    async saveReports(analysis) {
        const outputDir = this.config.outputDir || './docs';
        
        try {
            // Save JSON analysis
            await this.reporters.json.save(analysis, path.join(outputDir, 'project-analysis.json'));
            console.log('[SAVED] project-analysis.json');

            // Save Markdown roadmap - ENGLISH
            await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.md'), 'roadmap', 'en');
            console.log('[SAVED] DEVELOPMENT_ROADMAP.md (English)');

            // Save Markdown roadmap - THAI
            await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.th.md'), 'roadmap', 'th');
            console.log('[SAVED] DEVELOPMENT_ROADMAP.th.md (Thai)');

            // Save HTML dashboard
            await this.reporters.html.save(analysis, path.join(outputDir, 'dashboard.html'));
            console.log('[SAVED] dashboard.html');
        } catch (error) {
            console.error('[ERROR] Failed to save reports:', error.message);
            throw error;
        }
    }
}

module.exports = SmartRoadmapScanner;