#!/usr/bin/env python3

"""
BRS-XSS Exploitability Calculator

Calculates vulnerability exploitability scores.

Company: EasyProTech LLC (www.easypro.tech)
Dev: Brabus
Modified: Sat 02 Aug 2025 11:25:00 MSK
Telegram: https://t.me/EasyProTech
"""

from typing import Dict, Any
from ..utils.logger import Logger

logger = Logger("core.exploitability_calculator")


class ExploitabilityCalculator:
    """Calculates vulnerability exploitability scores"""
    
    def __init__(self):
        """Initialize exploitability calculator"""
        self.exploitability_factors = self._load_exploitability_factors()
    
    def calculate_exploitability_score(
        self,
        payload: str,
        reflection_result: Any,
        context_info: Dict[str, Any]
    ) -> float:
        """
        Calculate exploitability score (0-10).
        
        Args:
            payload: XSS payload
            reflection_result: Reflection analysis result
            context_info: Context information
            
        Returns:
            Exploitability score
        """
        base_score = 5.0
        
        # Reflection quality affects exploitability
        reflection_type = getattr(reflection_result, 'reflection_type', None)
        
        if reflection_type:
            reflection_scores = {
                'exact': 10.0,
                'partial': 7.0,
                'encoded': 5.0,
                'filtered': 3.0,
                'obfuscated': 4.0,
                'not_reflected': 0.0
            }
            
            reflection_value = (
                reflection_type.value 
                if hasattr(reflection_type, 'value') 
                else str(reflection_type)
            )
            base_score = reflection_scores.get(reflection_value, 5.0)
        
        # Context affects exploitability
        context_type = context_info.get('context_type', 'unknown')
        
        context_multipliers = {
            'html_content': 1.0,
            'html_attribute': 0.8,
            'javascript': 1.2,
            'js_string': 0.9,
            'css_style': 0.6,
            'html_comment': 0.3,
            'unknown': 0.5
        }
        
        multiplier = context_multipliers.get(context_type, 0.5)
        
        # Filters and encoding reduce exploitability
        filters_detected = context_info.get('filters_detected', [])
        encoding_detected = context_info.get('encoding_detected', 'none')
        
        if filters_detected:
            multiplier *= (0.8 ** len(filters_detected))  # Each filter reduces score
        
        if encoding_detected != 'none':
            multiplier *= 0.7
        
        # Payload complexity affects exploitability
        if len(payload) > 100:  # Complex payloads are harder to exploit
            multiplier *= 0.9
        
        # Browser compatibility affects exploitability
        multiplier *= self._analyze_browser_compatibility(payload)
        
        # Evasion techniques in payload
        multiplier *= self._analyze_evasion_techniques(payload)
        
        final_score = min(10.0, base_score * multiplier)
        logger.debug(f"Exploitability score: {final_score:.2f} (base: {base_score}, multiplier: {multiplier:.2f})")
        
        return final_score
    
    def _analyze_browser_compatibility(self, payload: str) -> float:
        """Analyze browser compatibility of payload"""
        compatibility_score = 1.0
        payload_lower = payload.lower()
        
        # Modern JS features (lower compatibility)
        modern_features = [
            'fetch(',
            'async ',
            'await ',
            'arrow functions',
            'template literals',
            'destructuring',
            'spread operator'
        ]
        
        for feature in modern_features:
            if feature in payload_lower:
                compatibility_score *= 0.95
        
        # Legacy browser issues
        legacy_issues = [
            'activexobject',
            'attachEvent',
            'innertext'
        ]
        
        for issue in legacy_issues:
            if issue in payload_lower:
                compatibility_score *= 0.9
        
        return max(0.5, compatibility_score)  # Minimum 50% compatibility
    
    def _analyze_evasion_techniques(self, payload: str) -> float:
        """Analyze evasion techniques used in payload"""
        evasion_multiplier = 1.0
        payload_lower = payload.lower()
        
        # Common evasion techniques
        evasion_patterns = [
            'fromcharcode',
            'eval(',
            'unescape(',
            'decodeuri',
            'string.replace',
            'split(',
            'reverse(',
            'join(',
            '\\x',  # Hex encoding
            '\\u',  # Unicode encoding
            '%',    # URL encoding
            '&',    # HTML entities
        ]
        
        evasion_count = 0
        for pattern in evasion_patterns:
            if pattern in payload_lower:
                evasion_count += 1
        
        # More evasion techniques make exploitation harder
        if evasion_count > 0:
            evasion_multiplier = 1.0 - (evasion_count * 0.05)
            evasion_multiplier = max(0.7, evasion_multiplier)  # Min 70%
        
        return evasion_multiplier
    
    def _load_exploitability_factors(self) -> Dict[str, float]:
        """Load exploitability factors configuration"""
        return {
            'user_interaction': 0.8,    # Requires user interaction
            'authentication': 0.9,     # Requires authentication
            'network_access': 1.0,     # Network accessible
            'local_access': 0.7,       # Local access only
            'social_engineering': 0.6, # Requires social engineering
            'technical_knowledge': 0.5, # Requires technical knowledge
            'automated_tools': 1.2,    # Can be automated
            'public_exploit': 1.5      # Public exploit available
        }