import os
from typing import List

from bastion.analyzers.python_analyzer import PythonAnalyzer
from bastion.analyzers.js_analyzer import JavaScriptAnalyzer
from bastion.analyzers.base import BaseAnalyzer
from bastion.models import Capability, ScanResult

ANALYZERS = {
    '.py': PythonAnalyzer,
    '.js': JavaScriptAnalyzer,
    '.ts': JavaScriptAnalyzer,
    '.jsx': JavaScriptAnalyzer,
    '.tsx': JavaScriptAnalyzer,
}

def get_analyzer(file_extension):
    return ANALYZERS.get(file_extension)


def analyze_plugin(plugin, timestamp: str) -> ScanResult:
    all_capabilities: List[Capability] = []

    if plugin.type == "folder":
        for root, dirs, files in os.walk(plugin.path):
            for fname in sorted(files):
                ext = os.path.splitext(fname)[1].lower()
                analyzer_cls = get_analyzer(ext)
                if analyzer_cls:
                    fpath = os.path.join(root, fname)
                    analyzer = analyzer_cls()
                    all_capabilities.extend(analyzer.analyze(fpath))
    else:
        ext = os.path.splitext(plugin.path)[1].lower()
        analyzer_cls = get_analyzer(ext)
        if analyzer_cls:
            analyzer = analyzer_cls()
            all_capabilities.extend(analyzer.analyze(plugin.path))

    severity_order = {"Low": 0, "Medium": 1, "High": 2, "Critical": 3}
    risk_level = "Low"
    for cap in all_capabilities:
        if severity_order.get(cap.severity, 0) > severity_order.get(risk_level, 0):
            risk_level = cap.severity

    return ScanResult(
        plugin_id=plugin.id,
        capabilities=all_capabilities,
        risk_level=risk_level,
        timestamp=timestamp,
    )
