#!/bin/bash
# BQAS Scheduler Installation Script
# Installiert launchd Job fuer taegliche BQAS Tests um 7:00 Uhr

set -e

# Konfiguration
VOICE_SERVICE_DIR="/Users/benjaminadmin/Projekte/breakpilot-pwa/voice-service"
PLIST_NAME="com.breakpilot.bqas"
PLIST_PATH="${HOME}/Library/LaunchAgents/${PLIST_NAME}.plist"
LOG_DIR="/var/log/bqas"
GIT_HOOKS_DIR="/Users/benjaminadmin/Projekte/breakpilot-pwa/.git/hooks"

# Farben
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
    local level=$1
    local message=$2
    case $level in
        INFO)    echo -e "${BLUE}[INFO]${NC} ${message}" ;;
        SUCCESS) echo -e "${GREEN}[SUCCESS]${NC} ${message}" ;;
        WARNING) echo -e "${YELLOW}[WARNING]${NC} ${message}" ;;
        ERROR)   echo -e "${RED}[ERROR]${NC} ${message}" ;;
    esac
}

# Argumente
ACTION=${1:-install}

show_usage() {
    echo "Usage: $0 [install|uninstall|status|test]"
    echo ""
    echo "Commands:"
    echo "  install     Installiert launchd Job und Git Hook"
    echo "  uninstall   Entfernt launchd Job und Git Hook"
    echo "  status      Zeigt aktuellen Status"
    echo "  test        Fuehrt BQAS Tests manuell aus"
}

create_log_directory() {
    log "INFO" "Erstelle Log-Verzeichnis..."

    if [ ! -d "$LOG_DIR" ]; then
        sudo mkdir -p "$LOG_DIR"
        sudo chown "$USER" "$LOG_DIR"
        log "SUCCESS" "Log-Verzeichnis erstellt: $LOG_DIR"
    else
        log "INFO" "Log-Verzeichnis existiert bereits"
    fi
}

create_plist() {
    log "INFO" "Erstelle launchd plist..."

    cat > "$PLIST_PATH" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>${PLIST_NAME}</string>

    <key>ProgramArguments</key>
    <array>
        <string>${VOICE_SERVICE_DIR}/scripts/run_bqas.sh</string>
    </array>

    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>7</integer>
        <key>Minute</key>
        <integer>0</integer>
    </dict>

    <key>StandardOutPath</key>
    <string>${LOG_DIR}/stdout.log</string>

    <key>StandardErrorPath</key>
    <string>${LOG_DIR}/stderr.log</string>

    <key>RunAtLoad</key>
    <false/>

    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        <key>HOME</key>
        <string>${HOME}</string>
    </dict>

    <key>WorkingDirectory</key>
    <string>${VOICE_SERVICE_DIR}</string>
</dict>
</plist>
EOF

    log "SUCCESS" "plist erstellt: $PLIST_PATH"
}

load_plist() {
    log "INFO" "Lade launchd Job..."

    # Entlade falls bereits geladen
    launchctl unload "$PLIST_PATH" 2>/dev/null || true

    # Lade den Job
    launchctl load "$PLIST_PATH"
    log "SUCCESS" "launchd Job geladen"
}

unload_plist() {
    log "INFO" "Entlade launchd Job..."

    if [ -f "$PLIST_PATH" ]; then
        launchctl unload "$PLIST_PATH" 2>/dev/null || true
        rm -f "$PLIST_PATH"
        log "SUCCESS" "launchd Job entfernt"
    else
        log "INFO" "Kein launchd Job gefunden"
    fi
}

create_git_hook() {
    log "INFO" "Erstelle Git post-commit Hook..."

    # Prüfe ob .git/hooks existiert
    if [ ! -d "$GIT_HOOKS_DIR" ]; then
        log "WARNING" "Git hooks Verzeichnis nicht gefunden: $GIT_HOOKS_DIR"
        return 1
    fi

    local hook_path="${GIT_HOOKS_DIR}/post-commit"

    # Backup falls vorhanden
    if [ -f "$hook_path" ]; then
        cp "$hook_path" "${hook_path}.backup"
        log "INFO" "Bestehender Hook gesichert"
    fi

    cat > "$hook_path" << 'EOF'
#!/bin/bash
# BQAS Post-Commit Hook
# Fuehrt schnelle Tests aus wenn voice-service geaendert wurde

# Nur ausfuehren wenn voice-service geaendert wurde
if git diff --name-only HEAD~1 2>/dev/null | grep -q "^voice-service/"; then
    echo ""
    echo "voice-service geaendert - starte BQAS Quick Check..."
    echo ""

    # Async ausfuehren (im Hintergrund)
    VOICE_SERVICE_DIR="/Users/benjaminadmin/Projekte/breakpilot-pwa/voice-service"

    if [ -f "${VOICE_SERVICE_DIR}/scripts/run_bqas.sh" ]; then
        nohup "${VOICE_SERVICE_DIR}/scripts/run_bqas.sh" --quick > /dev/null 2>&1 &
        echo "BQAS Quick Check gestartet (PID: $!)"
        echo "Logs: /var/log/bqas/bqas.log"
    fi
fi
EOF

    chmod +x "$hook_path"
    log "SUCCESS" "Git Hook erstellt: $hook_path"
}

remove_git_hook() {
    log "INFO" "Entferne Git post-commit Hook..."

    local hook_path="${GIT_HOOKS_DIR}/post-commit"

    if [ -f "$hook_path" ]; then
        # Prüfe ob es unser Hook ist
        if grep -q "BQAS" "$hook_path" 2>/dev/null; then
            rm -f "$hook_path"

            # Restore backup falls vorhanden
            if [ -f "${hook_path}.backup" ]; then
                mv "${hook_path}.backup" "$hook_path"
                log "INFO" "Vorheriger Hook wiederhergestellt"
            fi

            log "SUCCESS" "Git Hook entfernt"
        else
            log "WARNING" "Hook gehoert nicht zu BQAS, uebersprungen"
        fi
    else
        log "INFO" "Kein Git Hook gefunden"
    fi
}

show_status() {
    echo ""
    echo "=========================================="
    echo "BQAS Scheduler Status"
    echo "=========================================="
    echo ""

    # launchd Status
    echo "launchd Job:"
    if launchctl list | grep -q "$PLIST_NAME"; then
        echo -e "  ${GREEN}✓${NC} Geladen"
        launchctl list "$PLIST_NAME" 2>/dev/null || true
    else
        echo -e "  ${RED}✗${NC} Nicht geladen"
    fi
    echo ""

    # plist Status
    echo "plist Datei:"
    if [ -f "$PLIST_PATH" ]; then
        echo -e "  ${GREEN}✓${NC} Vorhanden: $PLIST_PATH"
    else
        echo -e "  ${RED}✗${NC} Nicht vorhanden"
    fi
    echo ""

    # Git Hook Status
    echo "Git Hook:"
    local hook_path="${GIT_HOOKS_DIR}/post-commit"
    if [ -f "$hook_path" ] && grep -q "BQAS" "$hook_path" 2>/dev/null; then
        echo -e "  ${GREEN}✓${NC} Installiert: $hook_path"
    else
        echo -e "  ${RED}✗${NC} Nicht installiert"
    fi
    echo ""

    # Log-Verzeichnis
    echo "Log-Verzeichnis:"
    if [ -d "$LOG_DIR" ]; then
        echo -e "  ${GREEN}✓${NC} Vorhanden: $LOG_DIR"
        if [ -f "${LOG_DIR}/bqas.log" ]; then
            echo "  Letzter Eintrag:"
            tail -1 "${LOG_DIR}/bqas.log" 2>/dev/null || echo "    (leer)"
        fi
    else
        echo -e "  ${RED}✗${NC} Nicht vorhanden"
    fi
    echo ""

    # Naechste Ausfuehrung
    echo "Zeitplan: Taeglich um 07:00 Uhr"
    echo ""
}

do_install() {
    log "INFO" "=========================================="
    log "INFO" "BQAS Scheduler Installation"
    log "INFO" "=========================================="

    create_log_directory
    create_plist
    load_plist
    create_git_hook

    echo ""
    log "SUCCESS" "Installation abgeschlossen!"
    echo ""
    echo "Naechste Schritte:"
    echo "  1. Manueller Test:    $0 test"
    echo "  2. Status pruefen:    $0 status"
    echo "  3. Logs anschauen:    tail -f ${LOG_DIR}/bqas.log"
    echo ""
}

do_uninstall() {
    log "INFO" "=========================================="
    log "INFO" "BQAS Scheduler Deinstallation"
    log "INFO" "=========================================="

    unload_plist
    remove_git_hook

    echo ""
    log "SUCCESS" "Deinstallation abgeschlossen!"
    echo ""
    echo "Log-Verzeichnis wurde nicht entfernt: $LOG_DIR"
    echo "Zum Entfernen: sudo rm -rf $LOG_DIR"
    echo ""
}

do_test() {
    log "INFO" "Starte BQAS Tests manuell..."
    echo ""

    if [ -f "${VOICE_SERVICE_DIR}/scripts/run_bqas.sh" ]; then
        "${VOICE_SERVICE_DIR}/scripts/run_bqas.sh"
    else
        log "ERROR" "run_bqas.sh nicht gefunden!"
        exit 1
    fi
}

# Hauptlogik
case $ACTION in
    install)
        do_install
        ;;
    uninstall)
        do_uninstall
        ;;
    status)
        show_status
        ;;
    test)
        do_test
        ;;
    *)
        show_usage
        exit 1
        ;;
esac
