"""
Python security scanning logic for Storm Logger development
"""

import json
import re
import ast
import hashlib
import os
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple, Set
from urllib.parse import urlparse


def scan_security(
    file_path: str,
    scan_type: str = "comprehensive",
    severity_threshold: str = "medium",
    include_recommendations: bool = True
) -> str:
    """
    Comprehensive security scanning for Python code
    
    Args:
        file_path: Path to Python file or directory to scan
        scan_type: "code", "dependencies", "secrets", "permissions", "comprehensive"
        severity_threshold: "low", "medium", "high", "critical"
        include_recommendations: Whether to include security recommendations
        
    Returns:
        JSON string with security analysis and recommendations
    """
    path = Path(file_path)
    
    if not path.exists():
        return json.dumps({"error": f"Path {file_path} does not exist"}, indent=2)
    
    security_scan = {
        "file_path": str(path),
        "scan_type": scan_type,
        "severity_threshold": severity_threshold,
        "include_recommendations": include_recommendations,
        "timestamp": "2025-01-18",
        "vulnerabilities": [],
        "security_issues": [],
        "secrets_found": [],
        "permission_issues": [],
        "compliance_analysis": {},
        "storm_logger_security": {},
        "recommendations": [],
        "summary": {}
    }
    
    try:
        if path.is_file():
            if path.suffix == '.py':
                file_scan = scan_python_file(path, scan_type, severity_threshold)
                security_scan.update(file_scan)
            else:
                return json.dumps({"error": f"File {file_path} is not a Python file"}, indent=2)
        else:
            project_scan = scan_project_directory(path, scan_type, severity_threshold)
            security_scan.update(project_scan)
        
        # Storm Logger security analysis
        security_scan["storm_logger_security"] = analyze_storm_logger_security(security_scan)
        
        # Compliance analysis
        security_scan["compliance_analysis"] = analyze_security_compliance(security_scan)
        
        # Generate recommendations
        if include_recommendations:
            security_scan["recommendations"] = generate_security_recommendations(security_scan)
        
        # Generate summary
        security_scan["summary"] = generate_security_summary(security_scan)
        
        return json.dumps(security_scan, indent=2)
        
    except Exception as e:
        return json.dumps({"error": f"Security scan failed: {str(e)}"}, indent=2)


def scan_python_file(
    file_path: Path,
    scan_type: str,
    severity_threshold: str
) -> Dict[str, Any]:
    """
    Scan a single Python file for security issues
    
    Args:
        file_path: Path to Python file
        scan_type: Type of scan
        severity_threshold: Severity threshold
        
    Returns:
        File security scan results
    """
    try:
        content = file_path.read_text(encoding='utf-8')
        tree = ast.parse(content)
    except Exception as e:
        return {"error": f"Cannot parse file {file_path}: {str(e)}"}
    
    file_scan = {
        "file_name": file_path.name,
        "file_size": file_path.stat().st_size,
        "vulnerabilities": [],
        "security_issues": [],
        "secrets_found": [],
        "permission_issues": [],
        "code_patterns": []
    }
    
    # Code security analysis
    if scan_type in ["code", "comprehensive"]:
        file_scan["vulnerabilities"].extend(scan_code_vulnerabilities(tree, content, file_path))
        file_scan["security_issues"].extend(scan_security_patterns(tree, content, file_path))
    
    # Secret detection
    if scan_type in ["secrets", "comprehensive"]:
        file_scan["secrets_found"].extend(scan_secrets(content, file_path))
    
    # Permission analysis
    if scan_type in ["permissions", "comprehensive"]:
        file_scan["permission_issues"].extend(scan_file_permissions(file_path))
    
    # Filter by severity threshold
    file_scan = filter_by_severity(file_scan, severity_threshold)
    
    return file_scan


def scan_project_directory(
    project_path: Path,
    scan_type: str,
    severity_threshold: str
) -> Dict[str, Any]:
    """
    Scan a project directory for security issues
    
    Args:
        project_path: Path to project directory
        scan_type: Type of scan
        severity_threshold: Severity threshold
        
    Returns:
        Project security scan results
    """
    python_files = list(project_path.glob("**/*.py"))
    
    if not python_files:
        return {"error": f"No Python files found in {project_path}"}
    
    project_scan = {
        "project_name": project_path.name,
        "total_files": len(python_files),
        "files_scanned": [],
        "vulnerabilities": [],
        "security_issues": [],
        "secrets_found": [],
        "permission_issues": [],
        "dependency_vulnerabilities": []
    }
    
    # Scan each Python file
    for py_file in python_files[:20]:  # Limit to first 20 files for performance
        try:
            file_scan = scan_python_file(py_file, scan_type, severity_threshold)
            if "error" not in file_scan:
                project_scan["files_scanned"].append({
                    "file_path": str(py_file.relative_to(project_path)),
                    "vulnerabilities": len(file_scan["vulnerabilities"]),
                    "security_issues": len(file_scan["security_issues"]),
                    "secrets_found": len(file_scan["secrets_found"])
                })
                
                # Aggregate results
                project_scan["vulnerabilities"].extend(file_scan["vulnerabilities"])
                project_scan["security_issues"].extend(file_scan["security_issues"])
                project_scan["secrets_found"].extend(file_scan["secrets_found"])
                project_scan["permission_issues"].extend(file_scan["permission_issues"])
            
        except Exception as e:
            project_scan["files_scanned"].append({
                "file_path": str(py_file.relative_to(project_path)),
                "error": str(e)
            })
    
    # Dependency security analysis
    if scan_type in ["dependencies", "comprehensive"]:
        project_scan["dependency_vulnerabilities"] = scan_dependency_vulnerabilities(project_path)
    
    return project_scan


def scan_code_vulnerabilities(
    tree: ast.AST,
    content: str,
    file_path: Path
) -> List[Dict[str, Any]]:
    """
    Scan for code-level security vulnerabilities
    
    Args:
        tree: AST tree
        content: File content
        file_path: Path to file
        
    Returns:
        List of vulnerabilities found
    """
    vulnerabilities = []
    
    # SQL Injection vulnerabilities
    sql_injections = detect_sql_injection(tree, content)
    vulnerabilities.extend(sql_injections)
    
    # Command injection vulnerabilities
    command_injections = detect_command_injection(tree, content)
    vulnerabilities.extend(command_injections)
    
    # Path traversal vulnerabilities
    path_traversals = detect_path_traversal(tree, content)
    vulnerabilities.extend(path_traversals)
    
    # Insecure deserialization
    deserialization_issues = detect_insecure_deserialization(tree, content)
    vulnerabilities.extend(deserialization_issues)
    
    # Weak cryptography
    crypto_issues = detect_weak_cryptography(tree, content)
    vulnerabilities.extend(crypto_issues)
    
    # Add file path to all vulnerabilities
    for vuln in vulnerabilities:
        vuln["file_path"] = str(file_path)
    
    return vulnerabilities


def detect_sql_injection(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect SQL injection vulnerabilities
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of SQL injection issues
    """
    sql_issues = []
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            # Check for string formatting in SQL queries
            if isinstance(node.func, ast.Attribute):
                if node.func.attr in ['execute', 'executemany', 'query']:
                    # Check if SQL query uses string formatting
                    if node.args:
                        first_arg = node.args[0]
                        if isinstance(first_arg, ast.BinOp) and isinstance(first_arg.op, ast.Mod):
                            sql_issues.append({
                                "type": "sql_injection",
                                "severity": "high",
                                "line": node.lineno,
                                "message": "Potential SQL injection via string formatting",
                                "description": "SQL query uses string formatting which can lead to SQL injection",
                                "cwe": "CWE-89",
                                "remediation": "Use parameterized queries instead of string formatting"
                            })
                        elif isinstance(first_arg, ast.JoinedStr):  # f-string
                            sql_issues.append({
                                "type": "sql_injection",
                                "severity": "high",
                                "line": node.lineno,
                                "message": "Potential SQL injection via f-string",
                                "description": "SQL query uses f-string which can lead to SQL injection",
                                "cwe": "CWE-89",
                                "remediation": "Use parameterized queries instead of f-strings"
                            })
    
    return sql_issues


def detect_command_injection(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect command injection vulnerabilities
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of command injection issues
    """
    command_issues = []
    
    # Dangerous functions
    dangerous_functions = {
        'os.system': 'high',
        'os.popen': 'high',
        'subprocess.call': 'medium',
        'subprocess.run': 'medium',
        'subprocess.Popen': 'medium',
        'eval': 'critical',
        'exec': 'critical'
    }
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            func_name = get_function_name(node.func)
            
            if func_name in dangerous_functions:
                severity = dangerous_functions[func_name]
                
                # Check if using shell=True
                shell_true = False
                if node.keywords:
                    for keyword in node.keywords:
                        if keyword.arg == 'shell' and isinstance(keyword.value, ast.Constant):
                            if keyword.value.value is True:
                                shell_true = True
                                severity = 'high'
                
                command_issues.append({
                    "type": "command_injection",
                    "severity": severity,
                    "line": node.lineno,
                    "message": f"Potential command injection via {func_name}",
                    "description": f"Use of {func_name} can lead to command injection",
                    "cwe": "CWE-78",
                    "remediation": "Validate and sanitize all user input, avoid shell=True",
                    "shell_true": shell_true
                })
    
    return command_issues


def detect_path_traversal(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect path traversal vulnerabilities
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of path traversal issues
    """
    path_issues = []
    
    # File operations that could be vulnerable
    file_operations = {
        'open': 'medium',
        'os.path.join': 'low',
        'pathlib.Path': 'low'
    }
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            func_name = get_function_name(node.func)
            
            if func_name in file_operations or (isinstance(node.func, ast.Name) and node.func.id == 'open'):
                # Check if path includes user input patterns
                if node.args:
                    first_arg = node.args[0]
                    if contains_user_input_pattern(first_arg):
                        path_issues.append({
                            "type": "path_traversal",
                            "severity": "medium",
                            "line": node.lineno,
                            "message": f"Potential path traversal via {func_name}",
                            "description": "File path may contain user input without proper validation",
                            "cwe": "CWE-22",
                            "remediation": "Validate and sanitize file paths, use absolute paths"
                        })
    
    return path_issues


def detect_insecure_deserialization(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect insecure deserialization vulnerabilities
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of deserialization issues
    """
    deserialization_issues = []
    
    # Dangerous deserialization functions
    dangerous_deserializers = {
        'pickle.load': 'critical',
        'pickle.loads': 'critical',
        'yaml.load': 'high',
        'marshal.load': 'high',
        'marshal.loads': 'high'
    }
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            func_name = get_function_name(node.func)
            
            if func_name in dangerous_deserializers:
                severity = dangerous_deserializers[func_name]
                
                deserialization_issues.append({
                    "type": "insecure_deserialization",
                    "severity": severity,
                    "line": node.lineno,
                    "message": f"Insecure deserialization via {func_name}",
                    "description": f"Use of {func_name} can lead to arbitrary code execution",
                    "cwe": "CWE-502",
                    "remediation": "Use safe deserialization methods like json.loads or yaml.safe_load"
                })
    
    return deserialization_issues


def detect_weak_cryptography(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect weak cryptography usage
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of cryptography issues
    """
    crypto_issues = []
    
    # Weak cryptographic functions
    weak_crypto = {
        'hashlib.md5': 'medium',
        'hashlib.sha1': 'medium',
        'random.random': 'low',
        'random.randint': 'low'
    }
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            func_name = get_function_name(node.func)
            
            if func_name in weak_crypto:
                severity = weak_crypto[func_name]
                
                crypto_issues.append({
                    "type": "weak_cryptography",
                    "severity": severity,
                    "line": node.lineno,
                    "message": f"Weak cryptographic function: {func_name}",
                    "description": f"Use of {func_name} is cryptographically weak",
                    "cwe": "CWE-327",
                    "remediation": "Use strong cryptographic functions like hashlib.sha256 or secrets module"
                })
    
    return crypto_issues


def scan_security_patterns(
    tree: ast.AST,
    content: str,
    file_path: Path
) -> List[Dict[str, Any]]:
    """
    Scan for security anti-patterns
    
    Args:
        tree: AST tree
        content: File content
        file_path: Path to file
        
    Returns:
        List of security issues
    """
    security_issues = []
    
    # Hard-coded credentials
    hardcoded_creds = detect_hardcoded_credentials(content)
    security_issues.extend(hardcoded_creds)
    
    # Debug code left in production
    debug_code = detect_debug_code(tree, content)
    security_issues.extend(debug_code)
    
    # Unsafe HTTP usage
    unsafe_http = detect_unsafe_http(tree, content)
    security_issues.extend(unsafe_http)
    
    # Insecure random usage
    insecure_random = detect_insecure_random(tree, content)
    security_issues.extend(insecure_random)
    
    # Add file path to all issues
    for issue in security_issues:
        issue["file_path"] = str(file_path)
    
    return security_issues


def detect_hardcoded_credentials(content: str) -> List[Dict[str, Any]]:
    """
    Detect hardcoded credentials in code
    
    Args:
        content: File content
        
    Returns:
        List of credential issues
    """
    credential_issues = []
    
    # Patterns for common credential variables
    credential_patterns = [
        (r'password\s*=\s*["\'][^"\']+["\']', 'password'),
        (r'api_key\s*=\s*["\'][^"\']+["\']', 'api_key'),
        (r'secret\s*=\s*["\'][^"\']+["\']', 'secret'),
        (r'token\s*=\s*["\'][^"\']+["\']', 'token'),
        (r'private_key\s*=\s*["\'][^"\']+["\']', 'private_key'),
        (r'access_token\s*=\s*["\'][^"\']+["\']', 'access_token')
    ]
    
    lines = content.splitlines()
    for line_num, line in enumerate(lines, 1):
        for pattern, cred_type in credential_patterns:
            if re.search(pattern, line, re.IGNORECASE):
                credential_issues.append({
                    "type": "hardcoded_credentials",
                    "severity": "high",
                    "line": line_num,
                    "message": f"Hardcoded {cred_type} detected",
                    "description": f"Hardcoded {cred_type} found in source code",
                    "cwe": "CWE-798",
                    "remediation": "Use environment variables or secure configuration files"
                })
    
    return credential_issues


def detect_debug_code(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect debug code that might be left in production
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of debug code issues
    """
    debug_issues = []
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            func_name = get_function_name(node.func)
            
            # Debug functions
            if func_name in ['print', 'pprint.pprint', 'pdb.set_trace', 'breakpoint']:
                debug_issues.append({
                    "type": "debug_code",
                    "severity": "low",
                    "line": node.lineno,
                    "message": f"Debug code detected: {func_name}",
                    "description": f"Debug function {func_name} found in code",
                    "cwe": "CWE-489",
                    "remediation": "Remove debug code before production deployment"
                })
    
    return debug_issues


def detect_unsafe_http(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect unsafe HTTP usage
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of HTTP security issues
    """
    http_issues = []
    
    # Check for HTTP URLs in strings
    http_pattern = re.compile(r'http://[^\s"\']+', re.IGNORECASE)
    lines = content.splitlines()
    
    for line_num, line in enumerate(lines, 1):
        if http_pattern.search(line):
            http_issues.append({
                "type": "unsafe_http",
                "severity": "medium",
                "line": line_num,
                "message": "Insecure HTTP URL detected",
                "description": "HTTP URL found, should use HTTPS for security",
                "cwe": "CWE-319",
                "remediation": "Use HTTPS URLs instead of HTTP"
            })
    
    return http_issues


def detect_insecure_random(tree: ast.AST, content: str) -> List[Dict[str, Any]]:
    """
    Detect insecure random number generation
    
    Args:
        tree: AST tree
        content: File content
        
    Returns:
        List of random generation issues
    """
    random_issues = []
    
    # Insecure random functions for security contexts
    insecure_random_funcs = [
        'random.random',
        'random.randint',
        'random.choice',
        'random.shuffle'
    ]
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            func_name = get_function_name(node.func)
            
            if func_name in insecure_random_funcs:
                random_issues.append({
                    "type": "insecure_random",
                    "severity": "medium",
                    "line": node.lineno,
                    "message": f"Insecure random function: {func_name}",
                    "description": f"Use of {func_name} is not cryptographically secure",
                    "cwe": "CWE-338",
                    "remediation": "Use secrets module for cryptographically secure random numbers"
                })
    
    return random_issues


def scan_secrets(content: str, file_path: Path) -> List[Dict[str, Any]]:
    """
    Scan for secrets and sensitive information
    
    Args:
        content: File content
        file_path: Path to file
        
    Returns:
        List of secrets found
    """
    secrets_found = []
    
    # Secret patterns
    secret_patterns = [
        (r'-----BEGIN PRIVATE KEY-----', 'private_key', 'critical'),
        (r'-----BEGIN RSA PRIVATE KEY-----', 'rsa_private_key', 'critical'),
        (r'[A-Za-z0-9+/]{40,}', 'base64_encoded_data', 'medium'),
        (r'AKIA[0-9A-Z]{16}', 'aws_access_key', 'high'),
        (r'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', 'uuid', 'low'),
        (r'sk-[a-zA-Z0-9]{48}', 'openai_api_key', 'high'),
        (r'xoxb-[0-9]{11}-[0-9]{11}-[a-zA-Z0-9]{24}', 'slack_bot_token', 'high'),
        (r'ghp_[a-zA-Z0-9]{36}', 'github_token', 'high')
    ]
    
    lines = content.splitlines()
    for line_num, line in enumerate(lines, 1):
        for pattern, secret_type, severity in secret_patterns:
            matches = re.finditer(pattern, line)
            for match in matches:
                # Skip if it's in a comment and looks like an example
                if '#' in line and 'example' in line.lower():
                    continue
                
                secrets_found.append({
                    "type": "secret_detection",
                    "secret_type": secret_type,
                    "severity": severity,
                    "line": line_num,
                    "message": f"Potential {secret_type} detected",
                    "description": f"Found pattern matching {secret_type}",
                    "match": match.group()[:20] + "..." if len(match.group()) > 20 else match.group(),
                    "file_path": str(file_path),
                    "remediation": "Remove secrets from code and use environment variables"
                })
    
    return secrets_found


def scan_file_permissions(file_path: Path) -> List[Dict[str, Any]]:
    """
    Scan file permissions for security issues
    
    Args:
        file_path: Path to file
        
    Returns:
        List of permission issues
    """
    permission_issues = []
    
    try:
        # Check file permissions
        stat_info = file_path.stat()
        file_mode = stat_info.st_mode
        
        # Check if file is world-readable
        if file_mode & 0o004:
            permission_issues.append({
                "type": "file_permissions",
                "severity": "medium",
                "message": "File is world-readable",
                "description": "File can be read by any user on the system",
                "file_path": str(file_path),
                "current_permissions": oct(file_mode)[-3:],
                "remediation": "Restrict file permissions to owner and group only"
            })
        
        # Check if file is world-writable
        if file_mode & 0o002:
            permission_issues.append({
                "type": "file_permissions",
                "severity": "high",
                "message": "File is world-writable",
                "description": "File can be modified by any user on the system",
                "file_path": str(file_path),
                "current_permissions": oct(file_mode)[-3:],
                "remediation": "Remove world-write permissions"
            })
    
    except Exception:
        pass
    
    return permission_issues


def scan_dependency_vulnerabilities(project_path: Path) -> List[Dict[str, Any]]:
    """
    Scan for dependency vulnerabilities
    
    Args:
        project_path: Path to project directory
        
    Returns:
        List of dependency vulnerabilities
    """
    # This would integrate with the dependency manager
    # For now, return mock data
    return [
        {
            "type": "dependency_vulnerability",
            "severity": "high",
            "package": "requests",
            "version": "2.28.1",
            "vulnerability_id": "CVE-2023-32681",
            "description": "Potential vulnerability in certificate verification",
            "remediation": "Update to version 2.31.0 or later"
        }
    ]


def get_function_name(node: ast.AST) -> str:
    """
    Get function name from AST node
    
    Args:
        node: AST node
        
    Returns:
        Function name string
    """
    if isinstance(node, ast.Name):
        return node.id
    elif isinstance(node, ast.Attribute):
        value_name = get_function_name(node.value) if hasattr(node.value, 'id') else str(node.value)
        return f"{value_name}.{node.attr}"
    else:
        return str(node)


def contains_user_input_pattern(node: ast.AST) -> bool:
    """
    Check if AST node contains patterns suggesting user input
    
    Args:
        node: AST node
        
    Returns:
        True if contains user input patterns
    """
    # Simple heuristic - look for variable names that suggest user input
    user_input_vars = ['request', 'input', 'user', 'param', 'arg', 'data']
    
    if isinstance(node, ast.Name):
        return any(var in node.id.lower() for var in user_input_vars)
    elif isinstance(node, ast.Attribute):
        return any(var in node.attr.lower() for var in user_input_vars)
    
    return False


def filter_by_severity(scan_results: Dict[str, Any], severity_threshold: str) -> Dict[str, Any]:
    """
    Filter scan results by severity threshold
    
    Args:
        scan_results: Scan results
        severity_threshold: Minimum severity to include
        
    Returns:
        Filtered scan results
    """
    severity_levels = {"low": 0, "medium": 1, "high": 2, "critical": 3}
    threshold_level = severity_levels.get(severity_threshold, 1)
    
    filtered_results = scan_results.copy()
    
    for key in ["vulnerabilities", "security_issues", "secrets_found", "permission_issues"]:
        if key in filtered_results:
            filtered_results[key] = [
                item for item in filtered_results[key]
                if severity_levels.get(item.get("severity", "medium"), 1) >= threshold_level
            ]
    
    return filtered_results


def analyze_storm_logger_security(security_scan: Dict[str, Any]) -> Dict[str, Any]:
    """
    Analyze Storm Logger security integration
    
    Args:
        security_scan: Security scan results
        
    Returns:
        Storm Logger security analysis
    """
    storm_security = {
        "logging_security": {
            "pii_detection": False,
            "sanitization_enabled": False,
            "secure_logging": False
        },
        "configuration_security": {
            "secure_config": False,
            "environment_variables": False,
            "encrypted_storage": False
        },
        "audit_trail": {
            "security_events": False,
            "access_logging": False,
            "compliance_logging": False
        },
        "recommendations": []
    }
    
    # Check for Storm Logger usage patterns
    all_issues = []
    if "vulnerabilities" in security_scan:
        all_issues.extend(security_scan["vulnerabilities"])
    if "security_issues" in security_scan:
        all_issues.extend(security_scan["security_issues"])
    
    # Recommend Storm Logger security features
    if any("credential" in issue.get("type", "") for issue in all_issues):
        storm_security["recommendations"].append({
            "feature": "credential_sanitization",
            "description": "Use Storm Logger's built-in credential sanitization",
            "implementation": "Enable sanitization in Storm Logger configuration"
        })
    
    if any("debug" in issue.get("type", "") for issue in all_issues):
        storm_security["recommendations"].append({
            "feature": "production_logging",
            "description": "Use Storm Logger's production-safe logging",
            "implementation": "Configure appropriate log levels for production"
        })
    
    return storm_security


def analyze_security_compliance(security_scan: Dict[str, Any]) -> Dict[str, Any]:
    """
    Analyze security compliance
    
    Args:
        security_scan: Security scan results
        
    Returns:
        Compliance analysis
    """
    compliance = {
        "owasp_top_10": {},
        "pci_dss": {},
        "gdpr": {},
        "hipaa": {},
        "overall_compliance": "partial"
    }
    
    # OWASP Top 10 analysis
    all_issues = []
    if "vulnerabilities" in security_scan:
        all_issues.extend(security_scan["vulnerabilities"])
    if "security_issues" in security_scan:
        all_issues.extend(security_scan["security_issues"])
    
    owasp_categories = {
        "A01_Broken_Access_Control": [],
        "A02_Cryptographic_Failures": [],
        "A03_Injection": [],
        "A04_Insecure_Design": [],
        "A05_Security_Misconfiguration": [],
        "A06_Vulnerable_Components": [],
        "A07_Identity_Authentication_Failures": [],
        "A08_Software_Data_Integrity_Failures": [],
        "A09_Security_Logging_Failures": [],
        "A10_Server_Side_Request_Forgery": []
    }
    
    for issue in all_issues:
        issue_type = issue.get("type", "")
        if "injection" in issue_type:
            owasp_categories["A03_Injection"].append(issue)
        elif "crypto" in issue_type:
            owasp_categories["A02_Cryptographic_Failures"].append(issue)
        elif "deserialization" in issue_type:
            owasp_categories["A08_Software_Data_Integrity_Failures"].append(issue)
    
    compliance["owasp_top_10"] = owasp_categories
    
    # Overall compliance assessment
    total_issues = len(all_issues)
    if total_issues == 0:
        compliance["overall_compliance"] = "excellent"
    elif total_issues < 5:
        compliance["overall_compliance"] = "good"
    elif total_issues < 10:
        compliance["overall_compliance"] = "fair"
    else:
        compliance["overall_compliance"] = "poor"
    
    return compliance


def generate_security_recommendations(security_scan: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    Generate security recommendations
    
    Args:
        security_scan: Security scan results
        
    Returns:
        List of security recommendations
    """
    recommendations = []
    
    # Count issues by severity
    all_issues = []
    if "vulnerabilities" in security_scan:
        all_issues.extend(security_scan["vulnerabilities"])
    if "security_issues" in security_scan:
        all_issues.extend(security_scan["security_issues"])
    
    critical_issues = [i for i in all_issues if i.get("severity") == "critical"]
    high_issues = [i for i in all_issues if i.get("severity") == "high"]
    medium_issues = [i for i in all_issues if i.get("severity") == "medium"]
    
    # Critical issues
    if critical_issues:
        recommendations.append({
            "priority": "critical",
            "category": "vulnerability_management",
            "title": "Address Critical Security Vulnerabilities",
            "description": f"Found {len(critical_issues)} critical security vulnerabilities",
            "action_items": [
                "Immediately address all critical vulnerabilities",
                "Implement security patches",
                "Review and test fixes",
                "Deploy security updates"
            ],
            "timeline": "Immediate (within 24 hours)"
        })
    
    # High severity issues
    if high_issues:
        recommendations.append({
            "priority": "high",
            "category": "security_hardening",
            "title": "Fix High-Priority Security Issues",
            "description": f"Found {len(high_issues)} high-severity security issues",
            "action_items": [
                "Review and fix SQL injection vulnerabilities",
                "Address command injection issues",
                "Remove hardcoded credentials",
                "Implement input validation"
            ],
            "timeline": "Within 1 week"
        })
    
    # Secrets found
    secrets = security_scan.get("secrets_found", [])
    if secrets:
        recommendations.append({
            "priority": "high",
            "category": "secrets_management",
            "title": "Implement Secrets Management",
            "description": f"Found {len(secrets)} potential secrets in code",
            "action_items": [
                "Remove all secrets from source code",
                "Use environment variables for configuration",
                "Implement secure secrets management",
                "Add secrets scanning to CI/CD pipeline"
            ],
            "timeline": "Within 3 days"
        })
    
    # Medium severity issues
    if medium_issues:
        recommendations.append({
            "priority": "medium",
            "category": "security_improvements",
            "title": "Improve Security Posture",
            "description": f"Found {len(medium_issues)} medium-severity security issues",
            "action_items": [
                "Implement HTTPS everywhere",
                "Use secure random number generation",
                "Add input validation",
                "Improve error handling"
            ],
            "timeline": "Within 2 weeks"
        })
    
    # Storm Logger integration
    storm_security = security_scan.get("storm_logger_security", {})
    storm_recommendations = storm_security.get("recommendations", [])
    
    if storm_recommendations:
        recommendations.append({
            "priority": "low",
            "category": "storm_logger_integration",
            "title": "Enhance Storm Logger Security Features",
            "description": "Leverage Storm Logger's security features",
            "action_items": [
                "Enable Storm Logger sanitization",
                "Configure security event logging",
                "Implement audit trail",
                "Add compliance reporting"
            ],
            "timeline": "Within 1 month"
        })
    
    return recommendations


def generate_security_summary(security_scan: Dict[str, Any]) -> Dict[str, Any]:
    """
    Generate security scan summary
    
    Args:
        security_scan: Security scan results
        
    Returns:
        Security summary
    """
    summary = {
        "total_vulnerabilities": 0,
        "critical_issues": 0,
        "high_issues": 0,
        "medium_issues": 0,
        "low_issues": 0,
        "secrets_found": 0,
        "security_score": 0,
        "compliance_status": "unknown",
        "priority_actions": []
    }
    
    # Count all issues
    all_issues = []
    if "vulnerabilities" in security_scan:
        all_issues.extend(security_scan["vulnerabilities"])
    if "security_issues" in security_scan:
        all_issues.extend(security_scan["security_issues"])
    
    summary["total_vulnerabilities"] = len(all_issues)
    
    # Count by severity
    for issue in all_issues:
        severity = issue.get("severity", "medium")
        if severity == "critical":
            summary["critical_issues"] += 1
        elif severity == "high":
            summary["high_issues"] += 1
        elif severity == "medium":
            summary["medium_issues"] += 1
        else:
            summary["low_issues"] += 1
    
    # Count secrets
    secrets = security_scan.get("secrets_found", [])
    summary["secrets_found"] = len(secrets)
    
    # Calculate security score (0-100)
    total_issues = summary["total_vulnerabilities"] + summary["secrets_found"]
    if total_issues == 0:
        summary["security_score"] = 100
    else:
        # Weighted scoring
        score_deduction = (
            summary["critical_issues"] * 25 +
            summary["high_issues"] * 15 +
            summary["medium_issues"] * 10 +
            summary["low_issues"] * 5 +
            summary["secrets_found"] * 20
        )
        summary["security_score"] = max(0, 100 - score_deduction)
    
    # Compliance status
    compliance = security_scan.get("compliance_analysis", {})
    summary["compliance_status"] = compliance.get("overall_compliance", "unknown")
    
    # Priority actions
    if summary["critical_issues"] > 0:
        summary["priority_actions"].append("Address critical vulnerabilities immediately")
    if summary["secrets_found"] > 0:
        summary["priority_actions"].append("Remove secrets from code")
    if summary["high_issues"] > 0:
        summary["priority_actions"].append("Fix high-severity security issues")
    
    return summary