#!/bin/bash
# ════════════════════════════════════════════════
#  ARIA Cockpit — Android Build Script
#  Verwendung: ./build.sh [debug|release]
# ════════════════════════════════════════════════

set -e

MODE="${1:-release}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# ── Farben ────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${YELLOW}╔═══════════════════════════════════════╗${NC}"
echo -e "${YELLOW}║   ARIA Cockpit — Android Build        ║${NC}"
echo -e "${YELLOW}║   Modus: ${MODE}$(printf '%*s' $((27 - ${#MODE})) '')║${NC}"
echo -e "${YELLOW}╚═══════════════════════════════════════╝${NC}"

# ── Voraussetzungen prüfen ────────────────────
MISSING=0

check_cmd() {
    if ! command -v "$1" &> /dev/null; then
        echo -e "  ${RED}✗ $1 nicht gefunden${NC}"
        MISSING=1
    else
        echo -e "  ${GREEN}✓${NC} $1 — $(command -v "$1")"
    fi
}

echo ""
echo -e "${CYAN}Voraussetzungen prüfen...${NC}"
check_cmd node
check_cmd npm
check_cmd npx
check_cmd java

if [ "$MISSING" -eq 1 ]; then
    echo ""
    echo -e "${RED}Fehlende Abhängigkeiten! Bitte zuerst ausführen:${NC}"
    echo -e "${RED}  ./setup.sh${NC}"
    exit 1
fi

# ── JDK 17 erzwingen (AGP 8.1 + Gradle 8.3 braucht JDK 17, nicht 21+) ──
echo ""
echo -e "${CYAN}Java-Version prüfen...${NC}"

CURRENT_JAVA_MAJOR=$(java -version 2>&1 | head -1 | cut -d'"' -f2 | cut -d'.' -f1)

if [ "$CURRENT_JAVA_MAJOR" -gt 17 ] 2>/dev/null; then
    echo -e "  ${YELLOW}JDK $CURRENT_JAVA_MAJOR erkannt — React Native 0.73 braucht JDK 17${NC}"
    echo -e "  ${YELLOW}Suche JDK 17...${NC}"

    JDK17_FOUND=""
    for JDK_PATH in \
        /usr/lib/jvm/java-17-openjdk-amd64 \
        /usr/lib/jvm/temurin-17-jdk-amd64 \
        /usr/lib/jvm/java-17-openjdk \
        /usr/lib/jvm/jdk-17 \
        /usr/lib/jvm/zulu-17 \
        /opt/java/jdk-17 \
        /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home \
        /Library/Java/JavaVirtualMachines/openjdk-17.jdk/Contents/Home; do
        if [ -x "$JDK_PATH/bin/java" ]; then
            JDK17_FOUND="$JDK_PATH"
            break
        fi
    done

    if [ -n "$JDK17_FOUND" ] && [ -x "$JDK17_FOUND/bin/jlink" ]; then
        export JAVA_HOME="$JDK17_FOUND"
        export PATH="$JAVA_HOME/bin:$PATH"
        # Gradle muss den Pfad auch kennen (verhindert dass es kaputte JVM-Verzeichnisse findet)
        GRADLE_PROPS="android/gradle.properties"
        if [ -f "$GRADLE_PROPS" ]; then
            if grep -q "^org.gradle.java.home=" "$GRADLE_PROPS" 2>/dev/null; then
                sed -i "s|^org.gradle.java.home=.*|org.gradle.java.home=$JDK17_FOUND|" "$GRADLE_PROPS"
            else
                echo "" >> "$GRADLE_PROPS"
                echo "# ARIA: JDK 17 Pfad (gesetzt von build.sh)" >> "$GRADLE_PROPS"
                echo "org.gradle.java.home=$JDK17_FOUND" >> "$GRADLE_PROPS"
            fi
        fi
        echo -e "  ${GREEN}✓${NC} JAVA_HOME → $JDK17_FOUND"
    elif [ -n "$JDK17_FOUND" ]; then
        echo -e "  ${RED}JDK 17 gefunden aber unvollständig (jlink fehlt — nur JRE installiert)${NC}"
        echo -e "  ${RED}Installieren: sudo apt install openjdk-17-jdk${NC}"
        exit 1
    else
        echo -e "  ${RED}JDK 17 nicht gefunden!${NC}"
        echo -e "  ${RED}Installieren: sudo apt install openjdk-17-jdk${NC}"
        echo -e "  ${RED}Oder: ./setup.sh${NC}"
        exit 1
    fi
else
    echo -e "  ${GREEN}✓${NC} JDK $CURRENT_JAVA_MAJOR — passt"
fi

# ── Natives Android-Projekt prüfen ───────────
if [ ! -f "android/gradlew" ]; then
    echo ""
    echo -e "${RED}Kein natives Android-Projekt gefunden (android/gradlew fehlt).${NC}"
    echo -e "${RED}Bitte zuerst ausführen:${NC}"
    echo -e "${RED}  ./setup.sh${NC}"
    exit 1
fi

# ── ANDROID_HOME prüfen / automatisch finden ─
if [ -z "$ANDROID_HOME" ] && [ -z "$ANDROID_SDK_ROOT" ]; then
    for SDK_PATH in \
        "$HOME/Android/Sdk" \
        "$HOME/android-sdk" \
        "/opt/android-sdk" \
        "$HOME/Library/Android/sdk"; do
        if [ -d "$SDK_PATH" ]; then
            export ANDROID_HOME="$SDK_PATH"
            export ANDROID_SDK_ROOT="$SDK_PATH"
            echo -e "  ${YELLOW}ANDROID_HOME automatisch gefunden: ${SDK_PATH}${NC}"
            break
        fi
    done

    if [ -z "$ANDROID_HOME" ]; then
        echo -e "  ${YELLOW}Warnung: ANDROID_HOME nicht gesetzt.${NC}"
        echo -e "  ${YELLOW}Falls der Build fehlschlägt: ./setup.sh ausführen${NC}"
    fi
fi

# ── Node Dependencies ────────────────────────
echo ""
echo -e "${GREEN}[1/3] Node Dependencies...${NC}"
if [ ! -d "node_modules" ]; then
    npm install
elif [ "package.json" -nt "node_modules" ]; then
    echo "      package.json geändert — update..."
    npm install
else
    echo "      node_modules aktuell"
fi

# ── File-Descriptor-Limit erhöhen (Metro braucht viele offene Dateien) ──
CURRENT_ULIMIT=$(ulimit -n)
if [ "$CURRENT_ULIMIT" -lt 8192 ] 2>/dev/null; then
    ulimit -n 8192 2>/dev/null || ulimit -n 4096 2>/dev/null || true
    NEW_ULIMIT=$(ulimit -n)
    if [ "$NEW_ULIMIT" -gt "$CURRENT_ULIMIT" ]; then
        echo -e "  ${YELLOW}ulimit -n: ${CURRENT_ULIMIT} → ${NEW_ULIMIT} (Metro braucht viele offene Dateien)${NC}"
    fi
fi

# ── APK bauen ─────────────────────────────────
echo ""
echo -e "${GREEN}[2/3] APK bauen (${MODE})...${NC}"

cd android
chmod +x gradlew 2>/dev/null || true

# CI=true verhindert dass Metro einen File-Watcher startet (EMFILE-Fix)
export CI=true

if [ "$MODE" = "debug" ]; then
    ./gradlew assembleDebug
    OUT_DIR="app/build/outputs/apk/debug"
else
    ./gradlew assembleRelease
    OUT_DIR="app/build/outputs/apk/release"
fi

# Mit ABI-Splits heisst die APK z.B. app-arm64-v8a-release.apk statt
# app-release.apk. arm64-v8a-Variante zuerst probieren (das ist unser
# Standard), Universal-APK als Fallback falls Splits deaktiviert sind.
if [ -f "$OUT_DIR/app-arm64-v8a-${MODE}.apk" ]; then
    APK_PATH="$OUT_DIR/app-arm64-v8a-${MODE}.apk"
elif [ -f "$OUT_DIR/app-${MODE}.apk" ]; then
    APK_PATH="$OUT_DIR/app-${MODE}.apk"
else
    echo -e "${RED}Keine passende APK in $OUT_DIR gefunden${NC}"
    cd ..
    exit 1
fi

cd ..

# ── Ergebnis ──────────────────────────────────
echo ""
if [ -f "android/$APK_PATH" ]; then
    APK_SIZE=$(du -h "android/$APK_PATH" | cut -f1)
    NICE_NAME="ARIA-Cockpit-${MODE}.apk"
    cp "android/$APK_PATH" "$NICE_NAME"

    echo -e "${GREEN}[3/3] Fertig!${NC}"
    echo ""
    echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║   APK erfolgreich gebaut!                     ║${NC}"
    echo -e "${GREEN}╠═══════════════════════════════════════════════╣${NC}"
    echo -e "${GREEN}║${NC}   Datei:  ${NICE_NAME}"
    echo -e "${GREEN}║${NC}   Größe:  ${APK_SIZE}"
    echo -e "${GREEN}║${NC}   Pfad:   android/${APK_PATH}"
    echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
    echo ""
    echo "Installieren:"
    echo "  adb install $NICE_NAME"
    echo ""
    echo "Oder APK direkt aufs Handy kopieren."
else
    echo -e "${RED}╔═══════════════════════════════════════════════╗${NC}"
    echo -e "${RED}║   Build fehlgeschlagen!                       ║${NC}"
    echo -e "${RED}╠═══════════════════════════════════════════════╣${NC}"
    echo -e "${RED}║${NC}   APK nicht gefunden."
    echo -e "${RED}║${NC}   Prüfe die Gradle-Ausgabe oben."
    echo -e "${RED}║${NC}"
    echo -e "${RED}║${NC}   Häufige Ursachen:"
    echo -e "${RED}║${NC}   - Android SDK fehlt    → ./setup.sh"
    echo -e "${RED}║${NC}   - JDK 17 fehlt         → ./setup.sh"
    echo -e "${RED}║${NC}   - Signing Config fehlt  (Release-Build)"
    echo -e "${RED}╚═══════════════════════════════════════════════╝${NC}"
    exit 1
fi
