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

PHONE="100.111.239.9:43477"
PKG="com.healthbridge.app"
LOG="/home/ubuntu/health-bridge/logs/morning-sync.log"
mkdir -p "$(dirname "$LOG")"

{
  echo "=== $(date -Is) morning Health Bridge sync ==="
  adb disconnect "$PHONE" || true
  timeout 30 adb connect "$PHONE" || true
  if ! adb -s "$PHONE" get-state >/dev/null 2>&1; then
    adb kill-server || true
    adb start-server || true
    timeout 30 adb connect "$PHONE" || true
  fi
  adb devices -l
  if ! adb -s "$PHONE" get-state >/dev/null 2>&1; then
    echo "WARN: Pixel ADB unavailable at $PHONE; skipping manual trigger. Phone-side 12h WorkManager sync may still run."
    exit 0
  fi
  JOB_ID=$(timeout 20 adb -s "$PHONE" shell dumpsys jobscheduler \
    | awk '/com.healthbridge.app\/androidx.work.impl.background.systemjob.SystemJobService/ {for (i=1;i<=NF;i++) if ($i ~ /^#u0a[0-9]+\/[0-9]+:/) {split($i,a,"/"); sub(":","",a[2]); print a[2]; exit}}')
  if [[ -z "${JOB_ID:-}" ]]; then
    echo "WARN: could not discover Health Bridge JobScheduler ID; skipping manual trigger"
    exit 0
  fi
  echo "discovered Health Bridge job id: $JOB_ID"
  timeout 20 adb -s "$PHONE" shell cmd jobscheduler run -f "$PKG" "$JOB_ID" || {
    echo "WARN: failed to trigger jobscheduler job $JOB_ID for $PKG"
    exit 0
  }
  echo "triggered jobscheduler job $JOB_ID for $PKG"
} >> "$LOG" 2>&1

# Silent on success; cron/no_agent will only alert on non-zero exit/errors.
