#!/usr/bin/env python3

"""
Project: BRS-XSS Knowledge Base Manager
Company: EasyProTech LLC (www.easypro.tech)
Dev: Brabus
Date: Fri 26 Oct 2025 15:35:00 MSK
Status: Modified
Telegram: https://t.me/EasyProTech
"""

import os
import importlib
import json
import hashlib
import tempfile
import urllib.request
from typing import Dict, Any, List, Optional

# Import version from central version management
from brsxss.version import KB_VERSION, KB_BUILD, KB_REVISION, update_knowledge_base_version
KB_MODULES_COUNT = 17

# --- Private variables ---
_KNOWLEDGE_BASE: Dict[str, Dict[str, str]] = {}
_initialized = False

# --- Private functions ---
def _initialize_knowledge_base():
    """Dynamically load all vulnerability details from this directory."""
    global _KNOWLEDGE_BASE, _initialized
    if _initialized:
        return

    current_dir = os.path.dirname(__file__)
    
    for filename in os.listdir(current_dir):
        if filename.endswith('.py') and not filename.startswith('__'):
            module_name = filename[:-3]
            
            try:
                module = importlib.import_module(f".{module_name}", package=__name__)
                if hasattr(module, 'DETAILS'):
                    # The key for the dictionary is the filename itself
                    _KNOWLEDGE_BASE[module_name] = module.DETAILS
            except ImportError:
                # Handle potential import errors gracefully
                continue
    
    _initialized = True

# --- Public API ---
def get_vulnerability_details(context: str) -> Dict[str, str]:
    """
    Retrieves the title, description, attack vector, and remediation
    for a given vulnerability context.
    """
    _initialize_knowledge_base()
    
    context = context.lower()
    return _KNOWLEDGE_BASE.get(context, _KNOWLEDGE_BASE.get("default", {}))

# --- Public API Extensions ---
def get_kb_version() -> str:
    """Get Knowledge Base version."""
    return KB_VERSION

def get_kb_info() -> Dict[str, Any]:
    """Get KB information."""
    _initialize_knowledge_base()
    return {
        "version": KB_VERSION,
        "build": KB_BUILD,
        "revision": KB_REVISION,
        "total_contexts": len(_KNOWLEDGE_BASE),
        "available_contexts": list(_KNOWLEDGE_BASE.keys())
    }

def list_contexts() -> List[str]:
    """List all available contexts."""
    _initialize_knowledge_base()
    return sorted(_KNOWLEDGE_BASE.keys())

def _get_kb_repo_info() -> Optional[Dict[str, Any]]:
    """Get latest KB information from GitHub repository"""
    try:
        # URL to BRS-KB repository API
        api_url = "https://api.github.com/repos/EPTLLC/BRS-KB/releases/latest"

        # Create request with timeout
        req = urllib.request.Request(api_url)
        from ...version import get_user_agent
        req.add_header('User-Agent', get_user_agent())

        with urllib.request.urlopen(req, timeout=10) as response:
            if response.status == 200:
                data = json.loads(response.read().decode('utf-8'))
                return {
                    'version': data.get('tag_name', '').strip('v'),
                    'build': data.get('published_at', '')[:10].replace('-', '.'),
                    'revision': 'stable',
                    'download_url': data.get('zipball_url')
                }
    except Exception as e:
        print(f"Warning: Could not fetch KB updates: {e}")

    return None

def _calculate_file_hash(file_path: str) -> str:
    """Calculate SHA256 hash of a file"""
    try:
        with open(file_path, 'rb') as f:
            return hashlib.sha256(f.read()).hexdigest()
    except Exception:
        return ""

def check_and_update_knowledge_base(auto_update: bool = True) -> bool:
    """
    Check for KB updates and optionally update

    Args:
        auto_update: If True, automatically update KB if newer version available

    Returns:
        bool: True if update was performed or KB is up to date
    """
    try:
        # Get current KB info
        current_info = get_kb_info()

        # Fetch latest info from repository
        latest_info = _get_kb_repo_info()

        if not latest_info:
            return False

        # Compare versions
        current_version = current_info.get('version', '0.0.0')
        latest_version = latest_info.get('version', '0.0.0')

        if latest_version > current_version:
            if auto_update:
                print(f"Updating Knowledge Base from v{current_version} to v{latest_version}...")
                # TODO: Implement actual KB update logic
                # For now, just update the version info
                update_knowledge_base_version(latest_info)
                print("Knowledge Base updated successfully!")
                return True
            else:
                print(f"Knowledge Base update available: v{current_version} -> v{latest_version}")
                return False
        else:
            return True  # Already up to date

    except Exception as e:
        print(f"Warning: Error checking KB updates: {e}")
        return False

# --- Pre-initialize on module load ---
_initialize_knowledge_base()

# Auto-check for updates on import (but don't auto-update)
try:
    check_and_update_knowledge_base(auto_update=False)
except Exception:
    pass  # Silently fail if no internet or other issues
