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

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILD_MODE="${1:-debug}"
FLAVOR="${2:-client}"

case "${BUILD_MODE}" in
  debug|profile|release)
    ;;
  *)
    echo "Usage: $0 [debug|profile|release] [client|mothership]" >&2
    exit 1
    ;;
esac

case "${FLAVOR}" in
  client|mothership)
    ;;
  *)
    echo "Invalid flavor '${FLAVOR}'. Use 'client' or 'mothership'." >&2
    exit 1
    ;;
esac

cd "${PROJECT_ROOT}"

timestamp="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
DART_DEFINES=(
  "APP_BUILD_TIMESTAMP=${timestamp}"
  "ENABLE_DEBUG_FEATURES=true"
)
dart_define_args=()
for define in "${DART_DEFINES[@]}"; do
  dart_define_args+=("--dart-define=${define}")
done

echo "[build_with_expiry] Using timestamp: ${timestamp} (UTC)"
echo "[build_with_expiry] Running flutter analyze..."
flutter analyze

echo "[build_with_expiry] Building APK (${BUILD_MODE}, flavor=${FLAVOR})..."
case "${BUILD_MODE}" in
  debug)
    flutter build apk --debug --flavor "${FLAVOR}" "${dart_define_args[@]}"
    ;;
  profile)
    flutter build apk --profile --flavor "${FLAVOR}" "${dart_define_args[@]}"
    ;;
  release)
    flutter build apk --release --flavor "${FLAVOR}" "${dart_define_args[@]}"
    ;;
esac

echo "[build_with_expiry] Done. APK with 90-day lifespan & full features generated."
