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

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 <tv-ip>" >&2
  exit 2
fi

IP="$1"
SERIAL="$IP:5555"
APP="com.cpt.electronicmenu.tv"
ACTIVITY="$APP/.MainActivity"
MAIN_ACTIVITY="$APP/com.cpt.electronicmenu.tv.MainActivity"
ACCESSIBILITY_SERVICE="$APP/com.cpt.electronicmenu.tv.AutoStartAccessibilityService"
MITV_HOME="com.mitv.tvhome"
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
APK="$ROOT_DIR/downloads/electronic-menu-tv-rdfz-v1.3.11-xiaomi-3s-first-screen-release-signed.apk"
ADB="${ADB:-/Users/sunqianqian/Library/Android/sdk/platform-tools/adb}"

log() {
  printf '[%s] %s\n' "$(date '+%F %T')" "$*"
}

adb_target() {
  "$ADB" -s "$SERIAL" "$@"
}

connect_target() {
  "$ADB" disconnect "$SERIAL" >/dev/null 2>&1 || true
  "$ADB" connect "$SERIAL" >/dev/null || true
  local state
  state="$("$ADB" devices | awk -v serial="$SERIAL" '$1 == serial {print $2}')"
  if [[ "$state" != "device" ]]; then
    echo "ADB not ready for $SERIAL; current state: ${state:-missing}" >&2
    echo "Open TV ADB debug again, authorize this computer, then rerun this script." >&2
    exit 3
  fi
}

wait_for_device() {
  local attempt state
  for attempt in $(seq 1 24); do
    "$ADB" connect "$SERIAL" >/dev/null 2>&1 || true
    state="$("$ADB" devices | awk -v serial="$SERIAL" '$1 == serial {print $2}')"
    if [[ "$state" == "device" ]]; then
      return 0
    fi
    sleep 5
  done
  return 1
}

if [[ ! -f "$APK" ]]; then
  echo "APK not found: $APK" >&2
  exit 2
fi

log "Connecting $SERIAL"
connect_target

log "Installing local Xiaomi boot APK"
adb_target install -r "$APK"

log "Checking installed package has Xiaomi boot broadcast"
if ! adb_target shell dumpsys package "$APP" | grep -q 'mitv.action.STR_BOOT_COMPLETED'; then
  echo "Installed package does not expose mitv.action.STR_BOOT_COMPLETED" >&2
  exit 4
fi

log "Launching app once to clear stopped state"
adb_target shell monkey -p "$APP" -c android.intent.category.LAUNCHER 1 >/dev/null
sleep 2

log "Keeping Xiaomi TV home enabled to avoid FallbackHome black screen"
adb_target shell pm enable "$MITV_HOME" || true

log "Writing Xiaomi start_3rd_app"
adb_target shell settings put global disable_back_home_whitelist disable
adb_target shell settings put system start_3rd_app "$APP"
adb_target shell settings put system rt_service_process_white_list "com.xiaomi.voicecontrol,$APP"
adb_target shell settings put system rt_pkg_white_list "com.ktcp.video,com.xiaodianshi.tv.yst,com.gitvdemo.video,com.cibn.tv,com.ixigua.android.tv.wasu,com.tencent.qqmusictv,com.kwai.tv.yst,com.hunantv.license,$APP"
adb_target shell settings put global 3rd_app_show_loading_page "com.cibn.tv:com.gitvdemo.video:com.ktcp.video:com.hunantv.license:com.xiaodianshi.tv.yst:net.myvst.v2:com.huya.nftv:com.m1905.tv:$APP"
adb_target shell cmd deviceidle whitelist "+$APP" >/dev/null 2>&1 || true
adb_target shell cmd package set-home-activity --user 0 "$MITV_HOME" || true

log "Enabling accessibility auto-start service"
existing_services="$(adb_target shell settings get secure enabled_accessibility_services | tr -d '\r')"
if [[ "$existing_services" == "null" || -z "$existing_services" ]]; then
  merged_services="$ACCESSIBILITY_SERVICE"
elif [[ ":$existing_services:" == *":$ACCESSIBILITY_SERVICE:"* ]]; then
  merged_services="$existing_services"
else
  merged_services="$existing_services:$ACCESSIBILITY_SERVICE"
fi
adb_target shell settings put secure enabled_accessibility_services "$merged_services"
adb_target shell settings put secure accessibility_enabled 1
adb_target shell settings get secure enabled_accessibility_services
adb_target shell settings get secure accessibility_enabled

log "Starting electronic menu before reboot"
adb_target shell am start -n "$ACTIVITY" >/dev/null
sleep 3
foreground_before="$(adb_target shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity|mFocusedApp|mCurrentFocus' || true)"
printf '%s\n' "$foreground_before"
if ! printf '%s\n' "$foreground_before" | grep -q "$APP"; then
  log "Electronic menu was not foreground; retrying explicit start"
  adb_target shell am start -n "$ACTIVITY" >/dev/null
  sleep 3
  foreground_before="$(adb_target shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity|mFocusedApp|mCurrentFocus' || true)"
  printf '%s\n' "$foreground_before"
fi
if ! printf '%s\n' "$foreground_before" | grep -q "$APP"; then
  echo "Pre-reboot foreground did not become $APP; refusing to reboot." >&2
  exit 7
fi

log "Smoke testing explicit Xiaomi boot broadcast before reboot"
adb_target shell logcat -c || true
adb_target shell am broadcast --include-stopped-packages --receiver-foreground \
  -a mitv.action.STR_BOOT_COMPLETED -n "$APP/.BootReceiver" >/dev/null || true
sleep 8
adb_target shell logcat -d -t 400 | grep -E 'ElectronicMenuBoot|automatic electronic-menu launch|STR_BOOT_COMPLETED|BOOT_COMPLETED|blocked automatic' | tail -80 || true

log "Rebooting $SERIAL for real boot verification"
adb_target reboot
sleep 45

if ! wait_for_device; then
  echo "TV rebooted, but ADB did not come back on $SERIAL." >&2
  echo "If the screen is showing electronic menu, boot autostart is visually OK." >&2
  echo "If not, re-open ADB debug on the TV and rerun verification." >&2
  exit 5
fi

boot_completed="$(adb_target shell getprop sys.boot_completed | tr -d '\r')"
foreground="$(adb_target shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity|mFocusedApp|mCurrentFocus' || true)"
start_app="$(adb_target shell settings get system start_3rd_app | tr -d '\r')"

log "sys.boot_completed=$boot_completed"
log "start_3rd_app=$start_app"
log "disable_back_home_whitelist=$(adb_target shell settings get global disable_back_home_whitelist | tr -d '\r')"
printf '%s\n' "$foreground"

if printf '%s\n' "$foreground" | grep -q "$APP"; then
  log "PASS: $APP is foreground after reboot."
  exit 0
fi

echo "FAIL: $APP is not foreground after reboot." >&2
exit 6
