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

MODE="${1:-debug}"

if [[ "$MODE" != "debug" && "$MODE" != "release" ]]; then
  echo "Usage: $0 [debug|release]" >&2
  exit 2
fi

PROJECT_ROOT="/home/anthony/Documents/Projects/GameTime"
WATCH_ROOT="$PROJECT_ROOT/watch_app"
BUILD_ENV_ROOT="$PROJECT_ROOT/.ideai/build-env"
SDK_COPY="$BUILD_ENV_ROOT/flutter-sdk"
HOME_DIR="$BUILD_ENV_ROOT/home"
GRADLE_DIR="$BUILD_ENV_ROOT/gradle"
PUB_CACHE_DIR="$BUILD_ENV_ROOT/pub-cache"
TMP_DIR="$BUILD_ENV_ROOT/tmp"
ANDROID_HOME="/opt/android-sdk"
JAVA_HOME="/usr/lib/jvm/java-21-openjdk"
FLUTTER_BIN="$SDK_COPY/bin/flutter"

mkdir -p "$BUILD_ENV_ROOT" "$HOME_DIR/.config" "$HOME_DIR/.local/share" "$HOME_DIR/.cache" "$GRADLE_DIR" "$PUB_CACHE_DIR" "$TMP_DIR"

if [[ ! -x "$FLUTTER_BIN" ]]; then
  cp -a /opt/flutter "$SDK_COPY"
fi

export HOME="$HOME_DIR"
export XDG_CONFIG_HOME="$HOME_DIR/.config"
export XDG_DATA_HOME="$HOME_DIR/.local/share"
export XDG_CACHE_HOME="$HOME_DIR/.cache"
export GRADLE_USER_HOME="$GRADLE_DIR"
export PUB_CACHE="$PUB_CACHE_DIR"
export TMPDIR="$TMP_DIR"
export TMP="$TMP_DIR"
export TEMP="$TMP_DIR"
export JAVA_TOOL_OPTIONS="-Djava.io.tmpdir=$TMP_DIR"
export GRADLE_OPTS="-Djava.io.tmpdir=$TMP_DIR"
export ANDROID_HOME
export JAVA_HOME
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH"

cd "$WATCH_ROOT"

"$FLUTTER_BIN" --disable-analytics pub get
set +e
"$FLUTTER_BIN" build apk "--$MODE"
BUILD_STATUS=$?
set -e

APK_PATH="$WATCH_ROOT/build/app/outputs/flutter-apk/app-$MODE.apk"
ALT_APK_PATH="$WATCH_ROOT/build/watch_app/app/outputs/flutter-apk/app-$MODE.apk"
LEGACY_ALT_APK_PATH="$WATCH_ROOT/build/watch_app/app/outputs/apk/$MODE/app-$MODE.apk"
CANONICAL_APK_PATH="$WATCH_ROOT/build/app/outputs/flutter-apk/app-$MODE.apk"

copy_to_canonical_path() {
  local source_apk="$1"
  mkdir -p "$(dirname "$CANONICAL_APK_PATH")"
  if [[ "$source_apk" == "$CANONICAL_APK_PATH" ]]; then
    echo "APK already at canonical path: $CANONICAL_APK_PATH"
    return 0
  fi
  cp "$source_apk" "$CANONICAL_APK_PATH"
  echo "APK copied to canonical path: $CANONICAL_APK_PATH"
}

if [[ -f "$APK_PATH" ]]; then
  copy_to_canonical_path "$APK_PATH"
  echo "APK built at: $APK_PATH"
  exit 0
fi

if [[ -f "$ALT_APK_PATH" ]]; then
  copy_to_canonical_path "$ALT_APK_PATH"
  echo "APK built at: $ALT_APK_PATH"
  exit 0
fi

if [[ -f "$LEGACY_ALT_APK_PATH" ]]; then
  copy_to_canonical_path "$LEGACY_ALT_APK_PATH"
  echo "APK built at: $LEGACY_ALT_APK_PATH"
  exit 0
fi

if [[ $BUILD_STATUS -ne 0 ]]; then
  exit "$BUILD_STATUS"
fi

echo "APK built at: $APK_PATH"
