"""Detector de lenguajes de programación"""

from pathlib import Path
from typing import Dict, Any


class LanguageDetector:
    """Detector de lenguajes de programación"""
    
    LANGUAGE_EXTENSIONS = {
        "Python": [".py"],
        "JavaScript": [".js", ".jsx"],
        "TypeScript": [".ts", ".tsx"],
        "Java": [".java"],
        "C": [".c"],
        "C++": [".cpp", ".cc"],
        "C#": [".cs"],
        "PHP": [".php"],
        "Ruby": [".rb"],
        "Go": [".go"],
        "Rust": [".rs"],
        "Swift": [".swift"],
        "Kotlin": [".kt"],
        "R": [".r"],
        "Lua": [".lua"],
        "Perl": [".pl"],
        "Scala": [".scala"],
        "Shell": [".sh"],
        "CSS": [".css"],
        "HTML": [".html"],
        "JSON": [".json"],
        "YAML": [".yaml", ".yml"],
        "XML": [".xml"],
        "SQL": [".sql"],
        "Markdown": [".md"],
    }
    
    def __init__(self, directory_path: str):
        self.directory_path = Path(directory_path)
    
    def detect_language(self, file_path: str) -> str:
        """Detecta el lenguaje basado en la extensión"""
        extension = Path(file_path).suffix.lower()
        for language, extensions in self.LANGUAGE_EXTENSIONS.items():
            if extension in extensions:
                return language
        return "Unknown"
    
    def analyze_directory(self) -> Dict[str, Any]:
        """Analiza un directorio y detecta lenguajes"""
        if not self.directory_path.exists():
            return {"error": f"Directorio no encontrado"}
        
        language_count = {}
        total_files = 0
        
        for file_path in self.directory_path.rglob("*"):
            if file_path.is_dir() or file_path.name.startswith("."):
                continue
            
            total_files += 1
            language = self.detect_language(str(file_path))
            
            if language not in language_count:
                language_count[language] = 0
            language_count[language] += 1
        
        return {
            "directory": str(self.directory_path),
            "total_files": total_files,
            "summary": dict(sorted(language_count.items(), key=lambda x: x[1], reverse=True))
        }

