"""
JavaScript File Filtering Module
"""

import re
from pathlib import Path
from typing import List, Dict
from urllib.parse import urlparse, parse_qs

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

class JSFilter:
    """Filter and prioritize JavaScript files"""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
        self.js_extensions = {'.js', '.jsx', '.ts', '.tsx', '.mjs'}
        self.js_patterns = [
            r'\.js(\?|$)',
            r'\.jsx(\?|$)', 
            r'\.ts(\?|$)',
            r'\.tsx(\?|$)',
            r'\.mjs(\?|$)',
            r'/js/',
            r'/javascript/',
            r'/assets/.*\.js',
            r'/static/.*\.js',
            r'application/javascript',
            r'text/javascript'
        ]
        
        # High-value JS file indicators
        self.high_value_patterns = [
            r'admin',
            r'api',
            r'auth',
            r'config',
            r'dashboard',
            r'login',
            r'panel',
            r'private',
            r'secure',
            r'user',
            r'account',
            r'profile',
            r'settings',
            r'management',
            r'internal'
        ]
        
        # Vendor/library patterns to deprioritize
        self.vendor_patterns = [
            r'jquery',
            r'bootstrap',
            r'angular',
            r'react',
            r'vue',
            r'lodash',
            r'moment',
            r'chart',
            r'google',
            r'facebook',
            r'twitter',
            r'analytics',
            r'gtm',
            r'cdn\.',
            r'unpkg',
            r'jsdelivr',
            r'cdnjs'
        ]
    
    def is_javascript_url(self, url: str) -> bool:
        """Check if URL points to JavaScript file"""
        url_lower = url.lower()
        
        # Check file extension
        parsed = urlparse(url)
        path = parsed.path.lower()
        
        if any(path.endswith(ext) for ext in self.js_extensions):
            return True
        
        # Check patterns
        for pattern in self.js_patterns:
            if re.search(pattern, url_lower):
                return True
        
        return False
    
    def calculate_priority_score(self, url: str) -> int:
        """Calculate priority score for JS file (higher = more important)"""
        score = 0
        url_lower = url.lower()
        
        # High-value indicators (+10 each)
        for pattern in self.high_value_patterns:
            if re.search(pattern, url_lower):
                score += 10
        
        # Vendor/library indicators (-5 each)
        for pattern in self.vendor_patterns:
            if re.search(pattern, url_lower):
                score -= 5
        
        # Shorter paths are often more important (+1 per missing slash)
        path_depth = url.count('/')
        if path_depth < 5:
            score += (5 - path_depth)
        
        # Non-minified files are more readable (+3)
        if '.min.' not in url_lower:
            score += 3
        
        # Files with version numbers might be less important (-2)
        if re.search(r'v\d+|version|\d+\.\d+', url_lower):
            score -= 2
        
        return max(0, score)  # Ensure non-negative
    
    def filter_javascript_urls(self, urls: List[str]) -> Dict[str, List[str]]:
        """
        Filter URLs to find JavaScript files and prioritize them
        
        Args:
            urls: List of URLs to filter
            
        Returns:
            Dictionary with 'all_js', 'high_priority', 'medium_priority', 'low_priority'
        """
        log_progress("Filtering JavaScript files...")
        
        js_urls = []
        
        # Filter JavaScript URLs
        for url in urls:
            if self.is_javascript_url(url):
                js_urls.append(url)
        
        log_progress(f"Found {len(js_urls)} JavaScript files")
        
        # Calculate priority scores
        scored_urls = []
        for url in js_urls:
            score = self.calculate_priority_score(url)
            scored_urls.append((url, score))
        
        # Sort by score (highest first)
        scored_urls.sort(key=lambda x: x[1], reverse=True)
        
        # Categorize by priority
        high_priority = []
        medium_priority = []
        low_priority = []
        
        for url, score in scored_urls:
            if score >= 15:
                high_priority.append(url)
            elif score >= 5:
                medium_priority.append(url)
            else:
                low_priority.append(url)
        
        results = {
            'all_js': [url for url, _ in scored_urls],
            'high_priority': high_priority,
            'medium_priority': medium_priority,
            'low_priority': low_priority
        }
        
        log_progress(f"Prioritized: {len(high_priority)} high, {len(medium_priority)} medium, {len(low_priority)} low")
        
        # Save results
        save_lines(results['all_js'], self.output_dir / "js_files_all.txt")
        save_lines(results['high_priority'], self.output_dir / "js_files_high_priority.txt")
        save_lines(results['medium_priority'], self.output_dir / "js_files_medium_priority.txt")
        save_lines(results['low_priority'], self.output_dir / "js_files_low_priority.txt")
        
        # Save detailed results with scores
        detailed_results = [
            {"url": url, "priority_score": score} 
            for url, score in scored_urls
        ]
        save_json(detailed_results, self.output_dir / "js_files_detailed.json")
        
        return results