#!/usr/bin/env bash
# Telefono Android fisico → API produzione
set -euo pipefail
export PATH="$HOME/flutter/bin:$HOME/Android/Sdk/platform-tools:$PATH"
export ANDROID_HOME="$HOME/Android/Sdk"

DEVICE="${ANDROID_DEVICE:-}"
if [[ -z "$DEVICE" ]]; then
  DEVICE=$(adb devices | awk '/device$/{print $1; exit}' | grep -v emulator || true)
fi
if [[ -z "$DEVICE" ]]; then
  echo "Nessun telefono USB collegato. Collega il device e abilita debug USB."
  exit 1
fi

API_BASE_URL="${API_BASE_URL:-https://www.matchlivetv.it}"
MODE="${BUILD_MODE:-debug}"

cd "$(dirname "$0")/../mobile"
flutter pub get

ARGS=(run -d "$DEVICE" "--dart-define=API_BASE_URL=$API_BASE_URL")
if [[ "$MODE" == "release" ]]; then
  ARGS=(run --release -d "$DEVICE" "--dart-define=API_BASE_URL=$API_BASE_URL")
fi

echo "Device: $DEVICE | API: $API_BASE_URL | Mode: $MODE"
flutter "${ARGS[@]}"
