#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ANDROID_PROJECT_DIR="$ROOT_DIR/server/portacode_django"
DEFAULT_SDK_DIR="$HOME/.bubblewrap/android_sdk"
LOCAL_PROPERTIES_FILE="$ANDROID_PROJECT_DIR/local.properties"

MODE="play"
SKIP_SIGNING="false"

show_help() {
  cat <<'EOF'
Usage: ./build_android.sh [--debug] [--play] [--skip-signing] [--help]

Build Android app for this repository.

Options:
  --debug         Build debug APK with Gradle (faster local verification).
  --play          Build signed release artifacts with Bubblewrap (default).
  --skip-signing  Skip signing (only meaningful with --play).
  -h, --help      Show this help.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --debug)
      MODE="debug"
      shift
      ;;
    --play)
      MODE="play"
      shift
      ;;
    --skip-signing)
      SKIP_SIGNING="true"
      shift
      ;;
    -h|--help)
      show_help
      exit 0
      ;;
    *)
      echo "error: unknown argument '$1'" >&2
      show_help >&2
      exit 1
      ;;
  esac
done

if [[ ! -d "$ANDROID_PROJECT_DIR" ]]; then
  echo "error: Android project dir not found at $ANDROID_PROJECT_DIR" >&2
  exit 1
fi

if [[ ! -x "$ANDROID_PROJECT_DIR/gradlew" ]]; then
  chmod +x "$ANDROID_PROJECT_DIR/gradlew"
fi

SDK_DIR="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$DEFAULT_SDK_DIR}}"
if [[ ! -d "$SDK_DIR" ]]; then
  echo "error: Android SDK dir not found at $SDK_DIR" >&2
  echo "hint: install/configure SDK or set ANDROID_HOME/ANDROID_SDK_ROOT." >&2
  exit 1
fi

cat > "$LOCAL_PROPERTIES_FILE" <<EOF
# Auto-generated by build_android.sh
sdk.dir=$SDK_DIR
EOF

export ANDROID_HOME="$SDK_DIR"
export ANDROID_SDK_ROOT="$SDK_DIR"
START_TS="$(date +%s)"

echo "Android project: $ANDROID_PROJECT_DIR"
echo "Android SDK:     $SDK_DIR"
echo "Build mode:      $MODE"
echo

cd "$ANDROID_PROJECT_DIR"

if [[ "$MODE" == "debug" ]]; then
  ./gradlew assembleDebug --no-daemon
else
  BUILD_CMD=(bubblewrap build)
  if [[ "$SKIP_SIGNING" == "true" ]]; then
    BUILD_CMD+=(--skipSigning)
  fi
  if [[ "${BUBBLEWRAP_AUTO_CONFIRM:-0}" == "1" ]]; then
    printf 'Y\n' | "${BUILD_CMD[@]}"
  else
    "${BUILD_CMD[@]}"
  fi
fi

DEBUG_APK="$ANDROID_PROJECT_DIR/app/build/outputs/apk/debug/app-debug.apk"
RELEASE_AAB="$ANDROID_PROJECT_DIR/app/build/outputs/bundle/release/app-release.aab"
LEGACY_RELEASE_AAB="$ANDROID_PROJECT_DIR/app-release-bundle.aab"
SIGNED_APK="$ANDROID_PROJECT_DIR/app-release-signed.apk"
UNSIGNED_ALIGNED_APK="$ANDROID_PROJECT_DIR/app-release-unsigned-aligned.apk"

print_if_fresh() {
  local label="$1"
  local file="$2"
  if [[ -f "$file" ]]; then
    local file_ts
    file_ts="$(stat -c %Y "$file")"
    if (( file_ts >= START_TS )); then
      echo "  $label: $file"
      PRINTED_ANY=1
    fi
  fi
}

echo
echo "Build completed."
echo
PRINTED_ANY=0
echo "Artifacts produced/updated in this run:"
print_if_fresh "Debug APK          " "$DEBUG_APK"
print_if_fresh "Release AAB [UNSIGNED]" "$RELEASE_AAB"
print_if_fresh "Release AAB [SIGNED]  " "$LEGACY_RELEASE_AAB"
print_if_fresh "Signed Release APK " "$SIGNED_APK"
print_if_fresh "Unsigned Align APK " "$UNSIGNED_ALIGNED_APK"

if (( PRINTED_ANY == 0 )); then
  echo "  No artifact timestamp changed (build may be up-to-date)."
  echo "  Known paths:"
  echo "  - $DEBUG_APK"
  echo "  - $RELEASE_AAB"
  echo "  - $LEGACY_RELEASE_AAB"
  echo "  - $SIGNED_APK"
  echo "  - $UNSIGNED_ALIGNED_APK"
fi

echo
echo "Google Play reminder:"
echo "  1. Upload the SIGNED .aab file (app-release-bundle.aab) in Play Console."
echo "  2. Increase versionCode/versionName before each new production upload."
echo "  3. Keep your keystore (.android_keys/portacode-upload.jks) backed up securely."
