# app/utils/helpers.py
import os
import json
import logging

logger = logging.getLogger(__name__)

def load_configs(config_dir='configs'):
    """
    Lädt alle .json-Konfigurationsdateien aus dem configs-Ordner,
    außer default_sounds.json (die wird separat geladen).
    """
    configs = []
    if not os.path.exists(config_dir):
        logger.warning(f"Config-Verzeichnis nicht gefunden: {config_dir}")
        return configs

    for filename in os.listdir(config_dir):
        if not filename.lower().endswith('.json'):
            continue
        if filename == 'default_sounds.json':
            continue  # globale Sounds separat laden

        path = os.path.join(config_dir, filename)
        try:
            with open(path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                data['filename'] = filename
                data.setdefault('name', filename.replace('.json', '').replace('_', ' ').title())
                configs.append(data)
        except json.JSONDecodeError as e:
            logger.error(f"Ungültiges JSON in {filename}: {e}")
        except FileNotFoundError:
            logger.error(f"Datei nicht gefunden (trotz listdir): {path}")
        except Exception as e:
            logger.error(f"Fehler beim Laden von {filename}: {e}")

    return sorted(configs, key=lambda x: x.get('name', ''))


def load_default_sounds(config_dir='configs'):
    """
    Lädt die globalen Standard-Sounds aus configs/default_sounds.json
    Wird immer geladen, unabhängig von der aktuellen Lok-Konfiguration
    """
    path = os.path.join(config_dir, 'default_sounds.json')
    data = json.load(f)
    
    if not os.path.exists(path):
        logger.info("Keine default_sounds.json gefunden → keine globalen Sounds")
        return []

    try:
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)
            # Flexibel: entweder 'global_sounds' oder direkt 'sounds'
            sounds = data.get('global_sounds', data.get('sounds', []))
            logger.info(f"Globale Default-Sounds geladen: {len(sounds)} Einträge")
            return sounds
    except json.JSONDecodeError as e:
        logger.error(f"Ungültiges JSON in default_sounds.json: {e}")
        return []
    except Exception as e:
        logger.error(f"Fehler beim Laden default_sounds.json: {e}")
        return []
