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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DEFAULT_ANDROID_ADDRESS="${TDC114_STARTUP_ANDROID_ADDRESS:-172.21.128.1:5559}"
ADB_ADDRESS="${TDC114_ADB_CONNECT_ADDRESS:-$DEFAULT_ANDROID_ADDRESS}"
ADB_HOST="${ADB_ADDRESS%%:*}"
ADB_PORT="${ADB_ADDRESS##*:}"
ADB_SOCKET="${ADB_SERVER_SOCKET:-}"
FLUTTER_DEVICE_ID="${TDC114_FLUTTER_DEVICE_ID:-}"
FLUTTER_DOCKER_SCRIPT="$ROOT_DIR/scripts/flutter-docker.sh"

print_common_header() {
  echo "[android-preflight]"
  if [ -n "$ADB_SOCKET" ]; then
    echo "Target ADB server socket: $ADB_SOCKET"
    if [ -n "$FLUTTER_DEVICE_ID" ]; then
      echo "Target Flutter device id: $FLUTTER_DEVICE_ID"
    fi
    echo "Policy default: Windows ADB server sharing via ADB_SERVER_SOCKET"
  else
    echo "Target emulator address: $ADB_ADDRESS"
    echo "Fallback direct emulator bridge: $DEFAULT_ANDROID_ADDRESS"
  fi
  echo
}

print_success() {
  print_common_header
  echo "PASS Android emulator is reachable from Docker/WSL."
  echo "Next step: continue runtime startup and later run integration/manual Android checks."
}

print_failure_no_address() {
  echo "[android-preflight]"
  echo "FAIL Android emulator address is empty."
  echo "Set TDC114_ADB_CONNECT_ADDRESS first, for example:"
  echo "  TDC114_ADB_CONNECT_ADDRESS=$DEFAULT_ANDROID_ADDRESS ./scripts/startup.sh --auto --wait=40"
}

print_failure_instructions() {
  local reason="$1"

  print_common_header
  echo "FAIL $reason"
  echo
  echo "Local PC work required before startup continues:"
  echo "1. On Windows, open Android Studio."
  echo "2. In Device Manager, keep only one manual-test emulator running."
  echo "3. In Windows PowerShell, run adb.exe devices and confirm the emulator is in device state."
  echo "4. If it is offline or missing there too, restart the emulator first."
  if [ -n "$ADB_SOCKET" ]; then
    echo "5. If Windows adb is healthy but WSL still fails, make sure portproxy forwards 5037 -> 127.0.0.1:5037 and the firewall rule for 5037 still exists."
  else
    echo "5. If Windows adb is healthy but WSL still fails, make sure portproxy forwards $ADB_PORT -> 127.0.0.1:$ADB_PORT and the firewall rule for that port still exists."
  fi
  echo "6. After Windows-side recovery, rerun:"
  if [ -n "$ADB_SOCKET" ]; then
    echo "   ADB_SERVER_SOCKET=$ADB_SOCKET ./scripts/startup.sh --auto --wait=40"
  else
    echo "   TDC114_ADB_CONNECT_ADDRESS=$ADB_ADDRESS ./scripts/startup.sh --auto --wait=40"
  fi
  echo
  echo "Minimum Windows-side action I cannot do from here:"
  echo "- Start or restart the emulator GUI."
  if [ -n "$ADB_SOCKET" ]; then
    echo "- If needed, fix Windows adb/portproxy state for port 5037."
  else
    echo "- If needed, fix Windows adb/portproxy state for port $ADB_PORT."
  fi
  echo
  echo "What I can keep doing from WSL after that:"
  echo "- Recheck Docker/WSL visibility."
  echo "- Continue Baron runtime startup."
  echo "- Run API smoke and integration commands."
}

if [ -z "$ADB_ADDRESS" ]; then
  print_failure_no_address
  exit 1
fi

if [ ! -x "$FLUTTER_DOCKER_SCRIPT" ]; then
  echo "Missing executable script: $FLUTTER_DOCKER_SCRIPT" >&2
  exit 1
fi

if [ -n "$ADB_SOCKET" ]; then
  set +e
  OUTPUT="$(ADB_SERVER_SOCKET="$ADB_SOCKET" "$FLUTTER_DOCKER_SCRIPT" adb devices 2>&1)"
  STATUS=$?
  set -e

  if [ -n "$FLUTTER_DEVICE_ID" ]; then
    DEVICE_PATTERN="^${FLUTTER_DEVICE_ID}[[:space:]]+device$"
    OFFLINE_PATTERN="^${FLUTTER_DEVICE_ID}[[:space:]]+offline$"
    UNAUTHORIZED_PATTERN="^${FLUTTER_DEVICE_ID}[[:space:]]+unauthorized$"
  else
    DEVICE_PATTERN="^emulator-[0-9]+[[:space:]]+device$"
    OFFLINE_PATTERN="^emulator-[0-9]+[[:space:]]+offline$"
    UNAUTHORIZED_PATTERN="^emulator-[0-9]+[[:space:]]+unauthorized$"
  fi

  if printf '%s\n' "$OUTPUT" | grep -Eq "$DEVICE_PATTERN"; then
    print_success
    printf '%s\n' "$OUTPUT"
    exit 0
  fi

  if printf '%s\n' "$OUTPUT" | grep -Eq "$OFFLINE_PATTERN"; then
    print_failure_instructions "Android emulator is visible through Windows ADB server but offline."
    printf '%s\n' "$OUTPUT"
    exit 1
  fi

  if printf '%s\n' "$OUTPUT" | grep -Eq "$UNAUTHORIZED_PATTERN"; then
    print_common_header
    echo "FAIL Android emulator is unauthorized through Windows ADB server."
    echo
    echo "Local PC work required before startup continues:"
    echo "1. Bring the emulator window to front."
    echo "2. Accept the RSA debugging prompt if it is visible."
    echo "3. Confirm Windows PowerShell adb.exe devices shows device."
    echo
    echo "After approval, rerun:"
    echo "  ADB_SERVER_SOCKET=$ADB_SOCKET ./scripts/startup.sh --auto --wait=40"
    printf '%s\n' "$OUTPUT"
    exit 1
  fi

  if printf '%s\n' "$OUTPUT" | grep -Eq "protocol fault|Connection refused|cannot connect|failed to check server version"; then
    print_failure_instructions "Docker/WSL could not use the Windows ADB server socket."
    printf '%s\n' "$OUTPUT"
    exit 1
  fi

  print_failure_instructions "Android emulator was not detected through the Windows ADB server socket."
  printf '%s\n' "$OUTPUT"
  exit "${STATUS:-1}"
fi

set +e
OUTPUT="$(TDC114_ADB_CONNECT_ADDRESS="$ADB_ADDRESS" "$FLUTTER_DOCKER_SCRIPT" adb-devices 2>&1)"
STATUS=$?
set -e

if printf '%s\n' "$OUTPUT" | grep -Eq "^${ADB_ADDRESS}[[:space:]]+device$"; then
  print_success
  printf '%s\n' "$OUTPUT"
  exit 0
fi

if printf '%s\n' "$OUTPUT" | grep -Eq "^${ADB_ADDRESS}[[:space:]]+offline$"; then
  print_failure_instructions "Android emulator is visible but offline."
  printf '%s\n' "$OUTPUT"
  exit 1
fi

if printf '%s\n' "$OUTPUT" | grep -Eq "^${ADB_ADDRESS}[[:space:]]+unauthorized$"; then
  print_common_header
  echo "FAIL Android emulator is unauthorized."
  echo
  echo "Local PC work required before startup continues:"
  echo "1. Bring the emulator window to front."
  echo "2. Accept the RSA debugging prompt if it is visible."
  echo "3. If no prompt appears, restart the emulator once and check adb.exe devices again on Windows."
  echo
  echo "After approval, rerun:"
  echo "  TDC114_ADB_CONNECT_ADDRESS=$ADB_ADDRESS ./scripts/startup.sh --auto --wait=40"
  echo
  echo "What I can do after that:"
  echo "- Retry WSL/Docker device detection."
  echo "- Continue the rest of startup automatically."
  printf '%s\n' "$OUTPUT"
  exit 1
fi

if printf '%s\n' "$OUTPUT" | grep -Eq "failed to connect to ${ADB_HOST}:${ADB_PORT}|Connection refused|cannot connect|protocol fault"; then
  print_failure_instructions "Docker/WSL could not connect to the Windows emulator bridge."
  printf '%s\n' "$OUTPUT"
  exit 1
fi

print_failure_instructions "Android emulator was not detected in a usable state."
printf '%s\n' "$OUTPUT"
exit "${STATUS:-1}"
