import os
import sys
from pathlib import Path


# Carregar pastas raiz da variável de ambiente ou usar padrão
# Formato da variável PYBROWSER_ROOTS: caminhos separados por vírgula
# Exemplo: PYBROWSER_ROOTS=C:\Users\p0666678\Downloads,C:\Users\p0666678\Documents,D:\Projetos
# O nome de cada pasta será extraído automaticamente do caminho
def load_root_dirs():
    env_roots = os.environ.get("PYBROWSER_ROOTS")

    # SE O USUARIO COLOCOU O PARAMETRO EM SYS ARGS -r
    if "-r" in sys.argv:
        index = sys.argv.index("-r")
        if index + 1 < len(sys.argv):
            env_roots = sys.argv[index + 1]

    if env_roots:
        # Formato simples: caminhos separados por vírgula
        paths = [p.strip() for p in env_roots.split(";") if p.strip()]

        if paths:
            result = []
            for path_str in paths:
                # Resolver o caminho completo
                path_obj = Path(path_str).resolve()
                # Usar o nome da pasta como nome de exibição
                folder_name = Path(
                    path_obj
                ).name  # Passamos novamente por PAth caso a pasta original nao tenha nome
                result.append((folder_name, str(path_obj)))

            if result:
                print(f"Usando pastas raiz: {', '.join([name for name, _ in result])}")
                return result

    # Detectar automaticamente a pasta Downloads do usuário atual
    downloads_path = os.path.join(os.path.expanduser("~"), "Downloads")
    return [
        ("Downloads", downloads_path),
    ]


def get_root_dir(root_name, ROOT_DIRS):
    """Retorna o caminho completo de uma pasta raiz pelo nome"""
    for name, path in ROOT_DIRS:
        if name == root_name:
            return path
    return None


def get_root_name_from_path(subpath):
    """Extrai o nome da raiz do subpath"""
    if not subpath:
        return None
    parts = subpath.split("/", 1)
    return parts[0] if parts else None


def remove_root_from_path(subpath):
    """Remove o nome da raiz do subpath"""
    if not subpath:
        return ""
    parts = subpath.split("/", 1)
    return parts[1] if len(parts) > 1 else ""


def get_file_icon(filename, is_dir):
    """Retorna o emoji apropriado baseado no tipo de arquivo"""
    if is_dir:
        return "📁"

    ext = os.path.splitext(filename)[1].lower()

    # Imagens
    if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp", ".ico"]:
        return "🖼️"
    # Vídeos
    elif ext in [".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm"]:
        return "🎬"
    # Áudio
    elif ext in [".mp3", ".wav", ".flac", ".aac", ".ogg", ".m4a", ".wma"]:
        return "🎵"
    # Documentos
    elif ext in [".pdf"]:
        return "📕"
    elif ext in [".doc", ".docx"]:
        return "📘"
    elif ext in [".xls", ".xlsx", ".csv"]:
        return "📊"
    elif ext in [".ppt", ".pptx"]:
        return "📙"
    # Compactados
    elif ext in [".zip", ".rar", ".7z", ".tar", ".gz", ".bz2"]:
        return "🗜️"
    # Código
    elif ext in [".py"]:
        return "🐍"
    elif ext in [".js", ".jsx", ".ts", ".tsx"]:
        return "📜"
    elif ext in [".html", ".htm"]:
        return "🌐"
    elif ext in [".css", ".scss", ".sass"]:
        return "🎨"
    elif ext in [".java"]:
        return "☕"
    elif ext in [".c", ".cpp", ".h", ".hpp"]:
        return "⚙️"
    elif ext in [".json", ".xml", ".yaml", ".yml"]:
        return "📋"
    # Texto
    elif ext in [".txt", ".md", ".log"]:
        return "📝"
    # Executáveis
    elif ext in [".exe", ".msi", ".app", ".dmg"]:
        return "⚡"
    # Padrão
    else:
        return "📄"
