#!/usr/bin/env bash
# Wrapper script pour le service Skull Voice
set -euo pipefail

# Configuration
SKULL_ROOT="/opt/Skull"
VENV_PATH="${SKULL_ROOT}/venv"
APP_PATH="${SKULL_ROOT}/apps"
LOG_FILE="${SKULL_ROOT}/logs/voice.log"

# Couleurs pour les logs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Fonction de logging
log() {
    local level=$1
    shift
    local message="$*"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    case $level in
        "INFO")
            echo -e "${GREEN}[INFO]${NC} ${timestamp} - $message" >&2
            ;;
        "WARN")
            echo -e "${YELLOW}[WARN]${NC} ${timestamp} - $message" >&2
            ;;
        "ERROR")
            echo -e "${RED}[ERROR]${NC} ${timestamp} - $message" >&2
            ;;
    esac
}

# Vérification environnement
check_environment() {
    log "INFO" "Vérification environnement Skull Voice..."
    
    # Vérif directories
    for dir in "$SKULL_ROOT" "$APP_PATH" "$(dirname "$LOG_FILE")"; do
        if [[ ! -d "$dir" ]]; then
            log "ERROR" "Répertoire manquant: $dir"
            exit 1
        fi
    done
    
    # Vérif virtual env
    if [[ ! -d "$VENV_PATH" ]]; then
        log "ERROR" "Virtual environment manquant: $VENV_PATH"
        exit 1
    fi
    
    # Vérif espeak-ng
    if ! command -v espeak-ng &> /dev/null; then
        log "WARN" "eSpeak-NG non trouvé dans PATH"
    fi
    
    # Vérif ffmpeg pour pydub
    if ! command -v ffmpeg &> /dev/null; then
        log "WARN" "FFmpeg non trouvé - certaines fonctions MP3 pourraient échouer"
    fi
    
    # Test MQTT
    if command -v mosquitto_pub &> /dev/null; then
        if timeout 2 mosquitto_pub -h "${MQTT_HOST:-127.0.0.1}" -p "${MQTT_PORT:-1883}" -t "test/connection" -m "test" -q 0 &>/dev/null; then
            log "INFO" "Connexion MQTT OK"
        else
            log "WARN" "Impossible de se connecter à MQTT"
        fi
    fi
    
    log "INFO" "Vérifications terminées"
}

# Signal handlers pour arrêt propre
shutdown_handler() {
    log "INFO" "Signal reçu - arrêt du service Voice"
    if [[ -n "${VOICE_PID:-}" ]] && kill -0 "$VOICE_PID" 2>/dev/null; then
        kill -TERM "$VOICE_PID"
        wait "$VOICE_PID"
    fi
    exit 0
}

# Configuration signals
trap shutdown_handler SIGTERM SIGINT SIGHUP

# Fonction principale
main() {
    log "INFO" "Démarrage du service Skull Voice"
    
    # Variables d'environnement par défaut
    export PYTHONPATH="${APP_PATH}:${PYTHONPATH:-}"
    export MQTT_HOST="${MQTT_HOST:-127.0.0.1}"
    export MQTT_PORT="${MQTT_PORT:-1883}"
    export LOG_LEVEL="${LOG_LEVEL:-INFO}"
    
    # Vérifications
    check_environment
    
    # Activation venv
    log "INFO" "Activation environnement virtuel: $VENV_PATH"
    source "${VENV_PATH}/bin/activate"
    
    # Change working directory
    cd "$APP_PATH"
    
    # Lance le service
    log "INFO" "Lancement du module voice..."
    log "INFO" "MQTT: ${MQTT_HOST}:${MQTT_PORT}"
    log "INFO" "Log level: ${LOG_LEVEL}"
    
    # Exec avec capture PID pour signal handling
    python -m voice.main &
    VOICE_PID=$!
    
    log "INFO" "Service Voice démarré (PID: $VOICE_PID)"
    
    # Attend le processus
    wait "$VOICE_PID"
    
    local exit_code=$?
    if [[ $exit_code -eq 0 ]]; then
        log "INFO" "Service Voice arrêté normalement"
    else
        log "ERROR" "Service Voice arrêté avec code: $exit_code"
    fi
    
    return $exit_code
}

# Point d'entrée
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi