#!/bin/bash
# Build + install on emulator or connected device
# Usage:
#   ./deploy.sh           → emulator
#   ./deploy.sh wifi      → phone via ADB WiFi (prompts for IP if not set)
#   ./deploy.sh logs      → stream logs only
set -e

export ANDROID_HOME=~/android-sdk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH"
GRADLE=~/gradle/gradle-8.6/bin/gradle
APK=app/build/outputs/apk/debug/app-debug.apk
PKG=me.khodak.claudeusage

# -- connect to phone over WiFi if requested
if [[ "$1" == "wifi" ]]; then
    PHONE_IP="${PHONE_IP:-$(cat .phone-ip 2>/dev/null)}"
    if [[ -z "$PHONE_IP" ]]; then
        read -rp "Phone IP address: " PHONE_IP
        echo "$PHONE_IP" > .phone-ip
    fi
    adb connect "$PHONE_IP:5555" 2>&1 | head -3
fi

# -- logs only
if [[ "$1" == "logs" ]]; then
    echo "Streaming logs (Ctrl-C to stop)..."
    adb logcat -s UsageRepo:D ClaudeWidget:D UsageWorker:D AlarmReceiver:D | sed 's/.*\(D\|W\|E\) //'
    exit 0
fi

# -- build
echo "Building..."
$GRADLE assembleDebug --no-daemon -q
echo "Build OK"

# -- pick target device
DEVICES=$(adb devices | awk '/device$/{print $1}')
if [[ -z "$DEVICES" ]]; then
    echo "No device/emulator connected. Start emulator with ./start-emulator.sh or enable WiFi debugging."
    exit 1
fi
echo "Devices: $DEVICES"

# -- install (keep data = upgrade)
echo "Installing..."
adb install -r "$APK"
echo "Installed."

# -- launch main activity
adb shell am start -n "$PKG/.MainActivity" 2>/dev/null || true

# -- stream relevant logs
echo ""
echo "Streaming logs (Ctrl-C to stop)..."
adb logcat -c && adb logcat -s UsageRepo:D MainActivity:D | sed 's/.*[VDIWEF]\///'
