#!/bin/bash
#
# AlvoTriX Core - Smartwatch Installer for macOS
# Double-click this file in Finder to run it.
#

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
BOLD='\033[1m'

clear
echo ""
echo -e "${CYAN}${BOLD} ============================================================${NC}"
echo -e "${CYAN}${BOLD}    AlvoTriX Core - Smartwatch Installer${NC}"
echo -e "${CYAN}${BOLD} ============================================================${NC}"
echo ""

# Get script directory (works even when double-clicked)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APK="$SCRIPT_DIR/AlvoTriX-Core.apk"
ADB_DIR="$SCRIPT_DIR/tools/mac"
ADB="$ADB_DIR/adb"

# Check APK exists
if [ ! -f "$APK" ]; then
    echo -e "${RED} [ERROR] AlvoTriX-Core.apk not found.${NC}"
    echo "         Please re-download the installer ZIP."
    echo ""
    echo " Press Enter to close..."
    read
    exit 1
fi

# Check if adb is available
setup_adb() {
    # 1. Check bundled adb
    if [ -x "$ADB" ]; then
        return 0
    fi

    # 2. Check system adb
    if command -v adb &>/dev/null; then
        ADB="adb"
        return 0
    fi

    # 3. Download from Google (official source)
    echo -e "${YELLOW} ADB tool not found. Downloading from Google...${NC}"
    echo " (This is a one-time download, ~5MB)"
    echo ""

    mkdir -p "$ADB_DIR"

    PLATFORM_TOOLS_URL="https://dl.google.com/android/repository/platform-tools-latest-darwin.zip"
    TEMP_ZIP="$ADB_DIR/platform-tools.zip"

    # Use curl (built into macOS)
    if curl -fSL -o "$TEMP_ZIP" "$PLATFORM_TOOLS_URL" 2>/dev/null; then
        # Extract only adb binary
        unzip -jo "$TEMP_ZIP" "platform-tools/adb" -d "$ADB_DIR" 2>/dev/null
        rm -f "$TEMP_ZIP"
        chmod +x "$ADB"

        if [ -x "$ADB" ]; then
            echo -e "${GREEN} [OK] ADB downloaded successfully.${NC}"
            echo ""
            return 0
        fi
    fi

    echo -e "${RED} [ERROR] Failed to download ADB.${NC}"
    echo "         Please check your internet connection and try again."
    echo "         Or install Android Platform Tools manually."
    echo ""
    echo " Press Enter to close..."
    read
    exit 1
}

setup_adb

# Kill any existing ADB server
"$ADB" kill-server &>/dev/null
"$ADB" start-server &>/dev/null

echo -e "${BOLD} [Step 1/4] Searching for your smartwatch...${NC}"
echo ""

# Check for connected devices
find_device() {
    DEVICE_ID=$("$ADB" devices 2>/dev/null | grep -w "device" | grep -v "List" | head -1 | awk '{print $1}')
    if [ -n "$DEVICE_ID" ]; then
        return 0
    fi
    return 1
}

if find_device; then
    echo -e "${GREEN} [OK] Smartwatch detected via USB: $DEVICE_ID${NC}"
else
    echo " No smartwatch detected via USB."
    echo ""
    echo " Options:"
    echo "   1. Connect via USB and press Enter to retry"
    echo "   2. Connect via WiFi (enter IP address)"
    echo "   3. Exit"
    echo ""
    read -p " Your choice (1/2/3): " CHOICE

    case "$CHOICE" in
        1)
            echo ""
            echo " Waiting for smartwatch via USB..."
            echo " (Make sure USB Debugging is enabled on your watch)"
            echo " (Tap ALLOW if a permission dialog appears)"
            echo ""

            WAIT_COUNT=0
            while [ $WAIT_COUNT -lt 12 ]; do
                if find_device; then
                    echo -e "${GREEN} [OK] Smartwatch detected: $DEVICE_ID${NC}"
                    break
                fi
                WAIT_COUNT=$((WAIT_COUNT + 1))
                echo " Still searching... ($WAIT_COUNT/12)"
                sleep 5
            done

            if [ -z "$DEVICE_ID" ]; then
                echo -e "${RED}"
                echo " [TIMEOUT] Smartwatch not found after 60 seconds."
                echo ""
                echo " Troubleshooting:"
                echo "   - Make sure USB Debugging is ON in Developer Options"
                echo "   - Try a different USB cable"
                echo "   - Tap ALLOW on the watch if prompted"
                echo "   - Restart the watch and try again"
                echo -e "${NC}"
                echo " Press Enter to close..."
                read
                exit 1
            fi
            ;;
        2)
            echo ""
            read -p " Enter watch IP:PORT (e.g. 192.168.1.50:5555): " WIFI_ADDR

            if [ -z "$WIFI_ADDR" ]; then
                echo -e "${RED} [ERROR] No address entered.${NC}"
                echo " Press Enter to close..."
                read
                exit 1
            fi

            echo " Connecting to $WIFI_ADDR..."
            CONNECT_RESULT=$("$ADB" connect "$WIFI_ADDR" 2>/dev/null)

            if echo "$CONNECT_RESULT" | grep -q "connected"; then
                DEVICE_ID="$WIFI_ADDR"
                echo -e "${GREEN} [OK] Connected to $WIFI_ADDR${NC}"
            else
                echo -e "${RED}"
                echo " [ERROR] Could not connect to $WIFI_ADDR"
                echo ""
                echo " Make sure:"
                echo "   - WiFi Debugging is enabled on the watch"
                echo "   - Watch and computer are on the same WiFi network"
                echo "   - The IP and port are correct"
                echo -e "${NC}"
                echo " Press Enter to close..."
                read
                exit 1
            fi
            ;;
        *)
            echo " Exiting."
            exit 0
            ;;
    esac
fi

echo ""
echo -e "${BOLD} [Step 2/4] Removing old version (if any)...${NC}"
"$ADB" -s "$DEVICE_ID" uninstall com.rolaxit.alvotrix &>/dev/null
echo " Done."

echo ""
echo -e "${BOLD} [Step 3/4] Installing AlvoTriX Core...${NC}"
echo " (This may take 1-2 minutes, please wait)"
echo ""

INSTALL_RESULT=$("$ADB" -s "$DEVICE_ID" install -r "$APK" 2>&1)

if echo "$INSTALL_RESULT" | grep -q "Success"; then
    echo -e "${GREEN} Installation successful!${NC}"
else
    echo -e "${RED}"
    echo " [ERROR] Installation failed."
    echo ""
    echo " Possible causes:"
    echo "   - Not enough storage on the watch"
    echo "   - USB Debugging permission was denied"
    echo "   - Watch disconnected during install"
    echo ""
    echo " Try: free up space on the watch and run this installer again."
    echo -e "${NC}"
    echo " Press Enter to close..."
    read
    exit 1
fi

echo ""
echo -e "${BOLD} [Step 4/4] Launching AlvoTriX Core on your watch...${NC}"
"$ADB" -s "$DEVICE_ID" shell am start -n com.rolaxit.alvotrix/.ActivationActivity &>/dev/null

echo ""
echo -e "${GREEN}${BOLD} ============================================================${NC}"
echo -e "${GREEN}${BOLD}    SUCCESS! AlvoTriX Core has been installed.${NC}"
echo -e "${GREEN}${BOLD} ============================================================${NC}"
echo ""
echo " What's next:"
echo "   1. Look at your watch - AlvoTriX should be starting up"
echo "   2. Enter your activation code when prompted"
echo "   3. Grant all permissions the app requests"
echo "   4. You can disconnect the watch now"
echo ""
echo " If the app doesn't appear, open the app list on your"
echo " watch and look for \"AlvoTriX Core\"."
echo ""
echo " Support: office@alvotrix.com"
echo " ============================================================"
echo ""
echo " Press Enter to close..."
read
