"""
JavaScript File Filtering Module - Smart Early Prioritization
"""

import re
from pathlib import Path
from typing import List, Dict, Tuple
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 with early smart scoring"""
    
    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'
        ]
        
        # 🔥 SMART EARLY SCORING PATTERNS
        self.high_value_patterns = [
            # Critical business logic
            (r'/app/', 15),
            (r'/api/', 20),
            (r'/admin/', 25),
            (r'/dashboard/', 20),
            (r'/panel/', 18),
            (r'/manage/', 18),
            (r'/config/', 22),
            (r'/auth/', 20),
            (r'/login/', 18),
            (r'/user/', 15),
            (r'/account/', 15),
            (r'/profile/', 12),
            (r'/settings/', 15),
            (r'/internal/', 25),
            (r'/private/', 25),
            # Custom/business specific
            (r'[^/]+\.(js|jsx|ts|tsx)$', 10),  # Custom files
            (r'\?.*=.*', 8),  # Has query parameters
        ]
        
        # 🚫 VENDOR/NOISE PATTERNS (SKIP THESE)
        self.vendor_patterns = [
            # Major libraries (SKIP COMPLETELY)
            (r'jquery', -50),
            (r'bootstrap', -50),
            (r'angular', -40),
            (r'react', -40),
            (r'vue', -40),
            (r'lodash', -50),
            (r'moment', -50),
            (r'chart', -45),
            # Analytics/tracking (WASTE OF TIME)
            (r'google', -60),
            (r'facebook', -60),
            (r'twitter', -60),
            (r'analytics', -70),
            (r'gtm', -70),
            (r'gtag', -70),
            (r'tracking', -65),
            # CDNs (SKIP)
            (r'cdn\.', -60),
            (r'unpkg', -60),
            (r'jsdelivr', -60),
            (r'cdnjs', -60),
            # Build artifacts (USUALLY NOISE)
            (r'chunk', -30),
            (r'vendor', -40),
            (r'bundle', -25),
            (r'\.min\.', -20),
            # Version indicators (LESS IMPORTANT)
            (r'v\d+', -15),
            (r'version', -15),
            (r'\d+\.\d+', -10),
        ]
    
    def calculate_smart_score(self, url: str) -> Tuple[int, str]:
        """
        🔥 SMART SCORING ALGORITHM
        Returns (score, reason) - Higher score = more important
        """
        score = 0
        reasons = []
        url_lower = url.lower()
        
        # High-value patterns (BUSINESS LOGIC)
        for pattern, points in self.high_value_patterns:
            if re.search(pattern, url_lower):
                score += points
                reasons.append(f"+{points} ({pattern})")
        
        # Vendor/noise patterns (SKIP THESE)
        for pattern, points in self.vendor_patterns:
            if re.search(pattern, url_lower):
                score += points  # These are negative
                reasons.append(f"{points} ({pattern})")
        
        # Path depth bonus (shorter = more important)
        path_depth = url.count('/')
        if path_depth < 4:
            depth_bonus = (4 - path_depth) * 3
            score += depth_bonus
            reasons.append(f"+{depth_bonus} (short path)")
        
        # Query parameters bonus (dynamic content)
        if '?' in url and '=' in url:
            score += 8
            reasons.append("+8 (has params)")
        
        # File extension analysis
        if url_lower.endswith(('.min.js', '.min.jsx')):
            score -= 15
            reasons.append("-15 (minified)")
        elif url_lower.endswith(('.js', '.jsx', '.ts', '.tsx')):
            score += 5
            reasons.append("+5 (js file)")
        
        reason = "; ".join(reasons) if reasons else "default"
        return max(-100, min(100, score)), reason
    
    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 filter_javascript_urls(self, urls: List[str]) -> Dict[str, List[str]]:
        """
        >> SMART FILTER: Early prioritization to save massive time
        
        Args:
            urls: List of URLs to filter
            
        Returns:
            Dictionary with tiered JS files for different analysis levels
        """
        log_progress(">> Smart filtering JavaScript files with early prioritization...")
        
        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")
        
        # 🔥 SMART SCORING
        scored_urls = []
        vendor_skipped = 0
        
        for url in js_urls:
            score, reason = self.calculate_smart_score(url)
            
            # SKIP VENDOR/NOISE COMPLETELY (HUGE TIME SAVER)
            if score < -30:
                vendor_skipped += 1
                continue
            
            scored_urls.append({
                'url': url,
                'score': score,
                'reason': reason
            })
        
        # Sort by score (highest first)
        scored_urls.sort(key=lambda x: x['score'], reverse=True)
        
        # >> TIERED ANALYSIS ASSIGNMENT
        total_js = len(scored_urls)
        
        # Tier 1: TOP 20% - Full analysis (AST + Regex + Secrets)
        tier1_count = max(5, int(total_js * 0.2))
        tier1_urls = scored_urls[:tier1_count]
        
        # Tier 2: NEXT 30% - Medium analysis (Regex + LinkFinder)
        tier2_count = int(total_js * 0.3)
        tier2_urls = scored_urls[tier1_count:tier1_count + tier2_count]
        
        # Tier 3: REMAINING 50% - Light analysis (Regex only)
        tier3_urls = scored_urls[tier1_count + tier2_count:]
        
        results = {
            'tier1_full': [item['url'] for item in tier1_urls],
            'tier2_medium': [item['url'] for item in tier2_urls],
            'tier3_light': [item['url'] for item in tier3_urls],
            'all_js': [item['url'] for item in scored_urls],
            'vendor_skipped': vendor_skipped
        }
        
        log_progress(f">> Smart tiers: T1({len(tier1_urls)}) T2({len(tier2_urls)}) T3({len(tier3_urls)}) Skipped({vendor_skipped})")
        
        # Save tiered results
        save_lines(results['tier1_full'], self.output_dir / "js_tier1_full.txt")
        save_lines(results['tier2_medium'], self.output_dir / "js_tier2_medium.txt")
        save_lines(results['tier3_light'], self.output_dir / "js_tier3_light.txt")
        save_lines(results['all_js'], self.output_dir / "js_files_all.txt")
        
        # Save detailed scoring
        detailed_results = {
            'summary': {
                'total_js_found': len(js_urls),
                'vendor_skipped': vendor_skipped,
                'tier1_count': len(tier1_urls),
                'tier2_count': len(tier2_urls),
                'tier3_count': len(tier3_urls),
                'time_saved_estimate': f"{vendor_skipped * 2 + len(tier3_urls) * 1.5:.1f} seconds"
            },
            'tier1_details': tier1_urls,
            'tier2_details': tier2_urls,
            'tier3_details': tier3_urls
        }
        save_json(detailed_results, self.output_dir / "js_smart_analysis.json")
        
        return results