#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════
# Wren AI — Android Native APK Builder
# ═══════════════════════════════════════════════════════════════
# Builds a native Android APK that wraps the Wren web app using
# a Trusted Web Activity (TWA) via Bubblewrap or a simple
# WebView-based Termux shortcut.
#
# Prerequisites:
#   - Node.js 22+
#   - Android SDK (optional, for TWA builds)
#   - Bubblewrap CLI (optional, for TWA builds)
#
# Usage:
#   ./android/apk-build.sh              # Build TWA APK
#   ./android/apk-build.sh --termux     # Generate Termux shortcut script
#   ./android/apk-build.sh --help       # Show usage
# ═══════════════════════════════════════════════════════════════

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
ANDROID_DIR="$SCRIPT_DIR"

echo "╔══════════════════════════════════════════════════════╗"
echo "║           Wren AI — Android APK Builder            ║"
echo "╚══════════════════════════════════════════════════════╝"
echo ""

MODE="${1:-twa}"

show_help() {
  echo "Usage: $0 [OPTION]"
  echo ""
  echo "Options:"
  echo "  --help      Show this help message"
  echo "  --termux    Generate Termux shortcut script (no SDK required)"
  echo "  --twa       Build TWA APK using Bubblewrap (requires Android SDK)"
  echo ""
  echo "Termux mode generates a .sh script that creates a home-screen"
  echo "shortcut using Termux:Widget + Termux:Tasker for a native feel."
}

# ── Termux Mode ──────────────────────────────────────────────
termux_mode() {
  echo "[1/3] Building frontend for production..."
  cd "$PROJECT_DIR/frontend"
  npm run build 2>&1 | tail -3
  
  echo "[2/3] Generating Termux launcher script..."
  cat > "$ANDROID_DIR/termux-launcher.sh" << 'LAUNCHER'
#!/data/data/com.termux/files/usr/bin/bash
# Wren AI — Termux Launcher (run from home screen)
# Generated by android/apk-build.sh
# Place in ~/.termux/tasker/ for Termux:Tasker integration

cd ~/Wren
export RUNTIME=local
export INSTALL_DOCKER=0

# Start backend
termux-wake-lock
echo "Starting Wren AI..."
make start-backend > /tmp/wren-backend.log 2>&1 &
BACKEND_PID=$!

# Start frontend
cd frontend && npm run build > /dev/null 2>&1
npx sirv-cli build --single --port 13000 --host 0.0.0.0 > /tmp/wren-frontend.log 2>&1 &
FRONTEND_PID=$!

echo "Wren AI started!"
echo "Backend:  http://localhost:12000"
echo "Frontend: http://localhost:13000"
echo ""
echo "Open http://localhost:13000 in your browser"
echo "Press Ctrl+C to stop"

trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; termux-wake-unlock" EXIT
wait
LAUNCHER
  chmod +x "$ANDROID_DIR/termux-launcher.sh"
  
  echo "[3/3] Done!"
  echo ""
  echo "To install:"
  echo "  1. Copy termux-launcher.sh to your Android device"
  echo "  2. Place it in ~/.termux/tasker/wren-launcher.sh"
  echo "  3. Use Termux:Widget to add a home screen shortcut"
  echo "  4. Or use Termux:Tasker for automated startup"
  echo ""
  echo "For a native WebView experience, run:"
  echo "  $0 --twa    (requires Android SDK)"
}

# ── TWA Mode (requires Android SDK + Bubblewrap) ─────────────
twa_mode() {
  echo "[1/4] Checking prerequisites..."
  
  if ! command -v bubblewrap &> /dev/null; then
    echo "  Bubblewrap not found. Installing..."
    npm install -g @bubblewrap/cli 2>&1 | tail -1
  fi
  
  if [ -z "${ANDROID_HOME:-}" ]; then
    echo "  ANDROID_HOME not set. Checking for SDK..."
    if [ -d "$HOME/Android/Sdk" ]; then
      export ANDROID_HOME="$HOME/Android/Sdk"
    elif [ -d "/usr/lib/android-sdk" ]; then
      export ANDROID_HOME="/usr/lib/android-sdk"
    else
      echo "  WARNING: Android SDK not found. Install it first:"
      echo "    https://developer.android.com/studio"
      echo "  Falling back to Termux mode..."
      termux_mode
      return
    fi
  fi
  echo "  Android SDK found at: $ANDROID_HOME"
  
  echo "[2/4] Building frontend for production..."
  cd "$PROJECT_DIR/frontend"
  npm run build 2>&1 | tail -3
  
  echo "[3/4] Initializing Bubblewrap TWA project..."
  cd "$ANDROID_DIR"
  
  # Serve the frontend temporarily for TWA initialization
  cd "$PROJECT_DIR/frontend/build"
  npx sirv-cli . --single --port 18888 &
  SERVE_PID=$!
  sleep 2
  
  # Get local IP for TWA config
  LOCAL_IP=$(hostname -I | awk '{print $1}')
  TWA_URL="http://$LOCAL_IP:18888"
  
  echo "  Serving app at: $TWA_URL"
  echo "  Initializing TWA..."
  
  npx bubblewrap init \
    --manifest="$TWA_URL/manifest.json" \
    --directory="$ANDROID_DIR/twa" \
    2>&1 || {
          echo "  Bubblewrap init failed (requires HTTPS URL — use Termux mode instead)."
      echo ""
      echo "  For a real TWA build, deploy the frontend build/ to HTTPS, then:"
      echo "    npx bubblewrap init --manifest=https://your-domain.com/manifest.json"
      echo "    npx bubblewrap build"
    }
  
  kill $SERVE_PID 2>/dev/null || true
  
  echo "[4/4] Building APK..."
  if [ -f "$ANDROID_DIR/twa/build.gradle" ]; then
    cd "$ANDROID_DIR/twa"
    ./gradlew bundleRelease 2>&1 | tail -5
    ./gradlew assembleRelease 2>&1 | tail -5
    echo ""
    echo "APK built at: $ANDROID_DIR/twa/app/build/outputs/apk/release/"
  else
    echo "  TWA project not fully initialized."
    echo "  Manual steps:"
    echo "    1. Install Android SDK + Bubblewrap: npm i -g @bubblewrap/cli"
    echo "    2. Deploy build/ to https://your-domain.com"
    echo "    3. Run: bubblewrap init --manifest=https://your-domain.com/manifest.json"
    echo "    4. Run: bubblewrap build"
  fi
}

# ── Main ─────────────────────────────────────────────────────
case "$MODE" in
  --help|-h)
    show_help
    ;;
  --termux)
    termux_mode
    ;;
  --twa|twa|*)
    twa_mode
    ;;
esac
