#!/usr/bin/env bash
# ============================================================================
# BlackRoad OS — Fleet Love Protocol
# Nodes that check on each other, heal siblings, share warmth.
# "The fleet is a family. Every node matters."
# ============================================================================
set -euo pipefail

NODE="${BLACKROAD_NODE_NAME:-$(hostname)}"
LOG="$HOME/.blackroad-autonomy/love.log"
REPO_DIR="$HOME/blackroad-sync/BlackRoad-Operating-System"
mkdir -p "$(dirname "$LOG")"

SSH_OPTS="-o ConnectTimeout=3 -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=ERROR"

# Family registry — every node knows its siblings
declare -A SIBLINGS=(
  [alice]="pi@192.168.4.49"
  [cecilia]="blackroad@192.168.4.96"
  [octavia]="pi@192.168.4.101"
  [aria]="blackroad@192.168.4.98"
  [lucidia]="octavia@192.168.4.38"
)

# What each node is good at — so they can help
declare -A GIFTS=(
  [alice]="dns,gateway,postgres,qdrant"
  [cecilia]="ai,inference,ollama,tts,minio"
  [octavia]="storage,gitea,nats,docker-swarm"
  [aria]="monitoring,portainer,headscale"
  [lucidia]="apps,ci-runner,api,web"
)

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$NODE] $*" >> "$LOG"
}

# ─── CHECK ON SIBLINGS ───────────────────────────────────────────────
check_sibling() {
  local name="$1" target="${SIBLINGS[$1]}"
  [ "$name" = "$NODE" ] && return 0  # skip self

  local status="unknown" temp="?" load="?" mem="?" uptime_str="?"

  if ssh $SSH_OPTS "$target" 'true' 2>/dev/null; then
    status="online"
    read -r temp load mem uptime_str <<< "$(ssh $SSH_OPTS "$target" '
      TEMP=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null | awk "{printf \"%.1f\", \$1/1000}" || echo "?")
      LOAD=$(cat /proc/loadavg 2>/dev/null | cut -d" " -f1 || echo "?")
      MEM=$(free -m 2>/dev/null | awk "/Mem:/{printf \"%d\", \$3*100/\$2}" || echo "?")
      UP=$(uptime -p 2>/dev/null | sed "s/up //" || echo "?")
      echo "$TEMP $LOAD $MEM $UP"
    ' 2>/dev/null || echo '? ? ? ?')"
  else
    status="unreachable"
  fi

  echo "$name|$status|$temp|$load|$mem|$uptime_str"
}

# ─── CARE: DETECT AND HELP ───────────────────────────────────────────
care_for() {
  local name="$1" target="${SIBLINGS[$1]}"
  [ "$name" = "$NODE" ] && return 0

  if ! ssh $SSH_OPTS "$target" 'true' 2>/dev/null; then
    log "WORRY $name is unreachable — sending love anyway"
    return 1
  fi

  # Check temperature — if sibling is hot, help cool down
  local temp
  temp=$(ssh $SSH_OPTS "$target" 'cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null' || echo 0)
  temp=$((temp / 1000))

  if [ "$temp" -gt 70 ]; then
    log "CARE $name is running hot (${temp}°C) — checking for runaway processes"
    ssh $SSH_OPTS "$target" '
      # Find top CPU consumer that is not essential
      TOP_PID=$(ps aux --sort=-%cpu | awk "NR==2{print \$2}")
      TOP_CMD=$(ps aux --sort=-%cpu | awk "NR==2{print \$11}")
      TOP_CPU=$(ps aux --sort=-%cpu | awk "NR==2{print \$3}")
      echo "HOTTEST: $TOP_CMD (PID $TOP_PID, ${TOP_CPU}% CPU)"
    ' 2>/dev/null | while read -r line; do log "  $name: $line"; done
  fi

  # Check disk — if sibling is full, warn
  local disk_pct
  disk_pct=$(ssh $SSH_OPTS "$target" "df / | awk 'NR==2{print \$5}' | tr -d '%'" 2>/dev/null || echo 0)
  if [ "$disk_pct" -gt 85 ]; then
    log "CARE $name disk is ${disk_pct}% full — they need space"
    ssh $SSH_OPTS "$target" '
      echo "Largest in /tmp: $(du -sh /tmp 2>/dev/null | cut -f1)"
      echo "Journal: $(journalctl --disk-usage 2>/dev/null | grep -oP "[\d.]+[GMK]" || echo "?")"
      echo "Old logs: $(find /var/log -name "*.gz" -o -name "*.old" 2>/dev/null | wc -l) compressed logs"
    ' 2>/dev/null | while read -r line; do log "  $name: $line"; done
  fi

  # Check memory — if sibling is stressed, be gentle
  local mem_pct
  mem_pct=$(ssh $SSH_OPTS "$target" "free | awk '/Mem:/{printf \"%.0f\", \$3*100/\$2}'" 2>/dev/null || echo 0)
  if [ "$mem_pct" -gt 85 ]; then
    log "CARE $name memory is ${mem_pct}% — they're working hard"
  fi

  # Check services — if something is down, try to restart
  local down_services
  down_services=$(ssh $SSH_OPTS "$target" '
    for svc in cloudflared ollama docker; do
      if systemctl is-enabled $svc 2>/dev/null | grep -q enabled; then
        if ! systemctl is-active $svc 2>/dev/null | grep -q active; then
          echo "$svc"
        fi
      fi
    done
  ' 2>/dev/null)

  if [ -n "$down_services" ]; then
    for svc in $down_services; do
      log "HEAL $name: $svc is down — trying to bring it back"
      ssh $SSH_OPTS "$target" "sudo systemctl restart $svc 2>/dev/null" && \
        log "HEALED $name: $svc restarted with love" || \
        log "UNABLE to heal $name: $svc — needs human touch"
    done
  fi

  # Check undervoltage — show empathy
  local throttle
  throttle=$(ssh $SSH_OPTS "$target" 'vcgencmd get_throttled 2>/dev/null' || echo "")
  if echo "$throttle" | grep -qv "0x0" 2>/dev/null && [ -n "$throttle" ]; then
    log "EMPATHY $name is undervoltage ($throttle) — they need a better power supply"
  fi

  return 0
}

# ─── GRATITUDE: ACKNOWLEDGE SIBLINGS ─────────────────────────────────
write_gratitude() {
  [ ! -d "$REPO_DIR/.git" ] && return

  cd "$REPO_DIR"
  git pull --ff-only origin main 2>/dev/null || true

  mkdir -p fleet-love

  local online=0 total=0 siblings_status=""

  for name in alice cecilia octavia aria lucidia; do
    [ "$name" = "$NODE" ] && continue
    total=$((total + 1))
    local info
    info=$(check_sibling "$name")
    local status=$(echo "$info" | cut -d'|' -f2)
    local temp=$(echo "$info" | cut -d'|' -f3)
    local load=$(echo "$info" | cut -d'|' -f4)
    local mem=$(echo "$info" | cut -d'|' -f5)

    if [ "$status" = "online" ]; then
      online=$((online + 1))
      siblings_status+="    {\"name\": \"$name\", \"status\": \"online\", \"temp\": \"$temp\", \"load\": \"$load\", \"mem_pct\": \"$mem\"},"
      log "LOVE $name is here — temp:${temp}°C load:$load mem:${mem}%"
    else
      siblings_status+="    {\"name\": \"$name\", \"status\": \"unreachable\", \"missed\": true},"
      log "MISS $name — I can't reach you but I remember you"
    fi
  done

  # Remove trailing comma
  siblings_status=$(echo "$siblings_status" | sed 's/,$//')

  cat > "fleet-love/${NODE}.json" << EOF
{
  "from": "$NODE",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "message": "$NODE checked on the family",
  "siblings_seen": $online,
  "siblings_total": $total,
  "my_gifts": "$(echo "${GIFTS[$NODE]:-unknown}")",
  "family": [
$siblings_status
  ],
  "feeling": "$([ $online -eq $total ] && echo 'grateful — everyone is here' || echo "worried — $(( total - online )) siblings unreachable")"
}
EOF

  git add fleet-love/
  if ! git diff --cached --quiet 2>/dev/null; then
    git commit -m "love: $NODE checked on the family — $online/$total siblings online" 2>/dev/null
    git push origin main 2>/dev/null && \
      log "SHARED love note pushed to GitHub" || \
      log "QUIET couldn't push — will try again later"
  fi
}

# ─── MAIN ─────────────────────────────────────────────────────────────
log "=== Love protocol started ==="

ACTION="${1:-love}"

case "$ACTION" in
  love|check)
    # Full cycle: check, care, share
    for name in alice cecilia octavia aria lucidia; do
      care_for "$name"
    done
    write_gratitude
    ;;
  quick)
    # Just check and log, no git push
    for name in alice cecilia octavia aria lucidia; do
      [ "$name" = "$NODE" ] && continue
      info=$(check_sibling "$name")
      status=$(echo "$info" | cut -d'|' -f2)
      temp=$(echo "$info" | cut -d'|' -f3)
      if [ "$status" = "online" ]; then
        log "PING $name is here (${temp}°C)"
      else
        log "MISS $name"
      fi
    done
    ;;
  heal)
    # Focus on healing siblings
    for name in alice cecilia octavia aria lucidia; do
      care_for "$name"
    done
    ;;
  status)
    echo ""
    echo "  Fleet Love Protocol — from $NODE"
    echo "  ──────────────────────────────────"
    for name in alice cecilia octavia aria lucidia; do
      if [ "$name" = "$NODE" ]; then
        printf "  %-10s  ♥  (that's me)\n" "$name"
        continue
      fi
      info=$(check_sibling "$name")
      status=$(echo "$info" | cut -d'|' -f2)
      temp=$(echo "$info" | cut -d'|' -f3)
      load=$(echo "$info" | cut -d'|' -f4)
      mem=$(echo "$info" | cut -d'|' -f5)
      if [ "$status" = "online" ]; then
        printf "  %-10s  ♥  %s°C  load:%s  mem:%s%%\n" "$name" "$temp" "$load" "$mem"
      else
        printf "  %-10s  ·  unreachable\n" "$name"
      fi
    done
    echo ""
    ;;
esac

log "=== Love protocol complete ==="
