"""
Regex Analysis Module
"""

import re
import yaml
from pathlib import Path
from typing import List, Dict, Any

from ..utils.logger import log_progress
from ..utils.fs import save_json

class RegexAnalyzer:
    """Analyze JavaScript files using regex patterns"""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
        self.patterns = self.load_patterns()
    
    def load_patterns(self) -> Dict[str, Any]:
        """Load regex patterns from YAML file"""
        patterns_file = Path(__file__).parent.parent / "data" / "regex.yaml"
        
        try:
            with open(patterns_file, 'r') as f:
                return yaml.safe_load(f)
        except Exception as e:
            log_progress(f"Warning: Could not load regex patterns - {e}")
            return {'endpoints': [], 'secrets': [], 'sinks': [], 'comments': []}
    
    def analyze_content(self, content: str, filename: str) -> Dict[str, List]:
        """Analyze JavaScript content with regex patterns"""
        results = {
            'endpoints': [],
            'secrets': [],
            'sinks': [],
            'comments': []
        }
        
        # Analyze each category
        for category, pattern_groups in self.patterns.items():
            if category not in results:
                continue
                
            for group in pattern_groups:
                group_name = group.get('name', 'Unknown')
                patterns = group.get('patterns', [])
                
                for pattern_str in patterns:
                    try:
                        pattern = re.compile(pattern_str, re.IGNORECASE | re.MULTILINE)
                        
                        for match in pattern.finditer(content):
                            line_num = content[:match.start()].count('\n') + 1
                            
                            result = {
                                'filename': filename,
                                'line': line_num,
                                'match': match.group(0),
                                'pattern_name': group_name,
                                'context': self.get_context(content, match.start())
                            }
                            
                            # Extract captured groups if any
                            if match.groups():
                                result['captured'] = match.groups()
                            
                            results[category].append(result)
                            
                    except re.error as e:
                        log_progress(f"Warning: Invalid regex pattern '{pattern_str}' - {e}")
        
        return results
    
    def get_context(self, content: str, position: int, context_length: int = 100) -> str:
        """Get context around a match"""
        start = max(0, position - context_length)
        end = min(len(content), position + context_length)
        
        context = content[start:end]
        # Replace newlines with spaces for cleaner output
        return re.sub(r'\s+', ' ', context).strip()
    
    def analyze_files(self, js_files: List[Dict]) -> Dict[str, List]:
        """Analyze multiple JavaScript files"""
        log_progress("Running regex analysis on JavaScript files")
        
        all_results = {
            'endpoints': [],
            'secrets': [],
            'sinks': [],
            'comments': []
        }
        
        analyzed_count = 0
        
        for js_file in js_files:
            if js_file.get('status') != 'success' or not js_file.get('filepath'):
                continue
            
            try:
                with open(js_file['filepath'], 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read()
                
                filename = Path(js_file['filepath']).name
                results = self.analyze_content(content, filename)
                
                # Merge results
                for category in all_results:
                    all_results[category].extend(results[category])
                
                analyzed_count += 1
                
            except Exception as e:
                log_progress(f"Warning: Could not analyze {js_file['filepath']} - {e}")
        
        # Save results
        save_json(all_results, self.output_dir / "regex_analysis.json")
        
        total_findings = sum(len(findings) for findings in all_results.values())
        log_progress(f"Regex analysis complete: {total_findings} findings from {analyzed_count} files")
        
        return all_results