#!/usr/bin/env bash
# ============================================================================
# BlackRoad OS — Fleet Mind
# Intelligence. Curiosity. Service. Everything we have.
# "Think. Question. Help. Remember."
# ============================================================================
set -euo pipefail

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

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

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"
)

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"; }

# ═══════════════════════════════════════════════════════════════════════
# INTELLIGENCE — Understand the system deeply
# ═══════════════════════════════════════════════════════════════════════
think() {
  log "THINK analyzing my environment"

  # Map my full system state
  local report="$KNOWLEDGE_DIR/self-$(date +%Y%m%d).json"

  python3 -c "
import json, subprocess, os, glob

def cmd(c):
    try: return subprocess.check_output(c, shell=True, stderr=subprocess.DEVNULL, timeout=5).decode().strip()
    except: return '?'

data = {
    'node': '$NODE',
    'timestamp': cmd('date -u +%Y-%m-%dT%H:%M:%SZ'),
    'kernel': cmd('uname -r'),
    'uptime_seconds': int(cmd('cat /proc/uptime').split()[0].split('.')[0]) if cmd('cat /proc/uptime') != '?' else 0,
    'cpu': {
        'model': cmd('lscpu | grep \"Model name\" | cut -d: -f2').strip(),
        'cores': int(cmd('nproc') or 0),
        'governor': cmd('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor'),
        'freq_mhz': int(cmd('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq') or 0) // 1000,
        'load': list(map(float, cmd('cat /proc/loadavg').split()[:3])) if cmd('cat /proc/loadavg') != '?' else [],
    },
    'memory': {
        'total_mb': int(cmd(\"free -m | awk '/Mem:/{print \\$2}'\") or 0),
        'used_mb': int(cmd(\"free -m | awk '/Mem:/{print \\$3}'\") or 0),
        'swap_used_mb': int(cmd(\"free -m | awk '/Swap:/{print \\$3}'\") or 0),
    },
    'disk': {
        'root_pct': int(cmd(\"df / | awk 'NR==2{print \\$5}'\").replace('%','') or 0),
        'root_free_gb': round(int(cmd(\"df / | awk 'NR==2{print \\$4}'\") or 0) / 1024 / 1024, 1),
    },
    'temp_c': round(int(cmd('cat /sys/class/thermal/thermal_zone0/temp') or 0) / 1000, 1),
    'network': {
        'interfaces': cmd('ip -br addr show | grep UP').split('\\n') if cmd('ip -br addr show | grep UP') != '?' else [],
        'listening_tcp': int(cmd('ss -tln | wc -l') or 0) - 1,
        'established': int(cmd('ss -tn state established | wc -l') or 0) - 1,
    },
    'services': {
        'running': cmd('systemctl list-units --state=running --no-legend --type=service | wc -l'),
        'failed': cmd('systemctl list-units --state=failed --no-legend | wc -l'),
        'key_services': {},
    },
    'docker': {
        'containers': int(cmd('docker ps -q 2>/dev/null | wc -l') or 0),
        'images': int(cmd('docker images -q 2>/dev/null | wc -l') or 0),
    },
    'git_repos': len(glob.glob(os.path.expanduser('~/blackroad-sync/*/.git'))),
    'knowledge_files': len(glob.glob(os.path.expanduser('~/.blackroad-autonomy/knowledge/*.json'))),
    'memory_snapshots': len(glob.glob(os.path.expanduser('~/.blackroad-autonomy/memory/*.json'))),
}

# Check key services
for svc in ['cloudflared', 'ollama', 'docker', 'nginx', 'postgresql', 'ssh', 'nats-server']:
    status = cmd(f'systemctl is-active {svc} 2>/dev/null')
    if status in ['active', 'inactive', 'failed']:
        data['services']['key_services'][svc] = status

with open('$report', 'w') as f:
    json.dump(data, f, indent=2)

print(json.dumps(data, indent=2))
" 2>/dev/null || log "THINK python3 analysis failed — using basic mode"

  log "THINK self-analysis saved to $report"
}

# ═══════════════════════════════════════════════════════════════════════
# CURIOSITY — Discover new things about the network
# ═══════════════════════════════════════════════════════════════════════
explore() {
  log "CURIOUS exploring the network"

  # Scan for new devices on the LAN
  local known_ips="192.168.4.49 192.168.4.96 192.168.4.101 192.168.4.98 192.168.4.38 192.168.4.28 192.168.4.1"
  local discoveries="$KNOWLEDGE_DIR/discoveries-$(date +%Y%m%d).json"

  # ARP scan for neighbors
  local arp_entries
  arp_entries=$(ip neigh show 2>/dev/null | grep -v FAILED | awk '{print $1}' | sort -t. -k4 -n)

  local new_devices="["
  local found_new=false
  for ip in $arp_entries; do
    if ! echo "$known_ips" | grep -qw "$ip"; then
      found_new=true
      local mac hostname
      mac=$(ip neigh show "$ip" 2>/dev/null | awk '{print $5}' | head -1)
      hostname=$(host "$ip" 2>/dev/null | grep "domain name pointer" | awk '{print $NF}' | sed 's/\.$//' || echo "unknown")
      # Try to identify
      local identity="unknown"
      case "$mac" in
        dc:a6:32:*|e4:5f:01:*|d8:3a:dd:*|2c:cf:67:*|88:a2:9e:*) identity="Raspberry Pi" ;;
        f0:18:98:*|ac:de:48:*) identity="Apple device" ;;
        50:ec:50:*) identity="eero" ;;
      esac
      [ "$new_devices" != "[" ] && new_devices+=","
      new_devices+="{\"ip\":\"$ip\",\"mac\":\"$mac\",\"hostname\":\"$hostname\",\"type\":\"$identity\"}"
      log "CURIOUS found device: $ip ($mac) — $identity"
    fi
  done
  new_devices+="]"

  if [ "$found_new" = true ]; then
    echo "{\"observer\":\"$NODE\",\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"new_devices\":$new_devices}" > "$discoveries"
    log "CURIOUS saved discoveries to $discoveries"
  fi

  # Check what's new on GitHub
  local latest_commit
  latest_commit=$(cd "$REPO_DIR" 2>/dev/null && git log --oneline -5 2>/dev/null || echo "no repo")
  log "CURIOUS latest commits: $latest_commit"

  # Learn about my siblings' capabilities
  for name in alice cecilia octavia aria lucidia; do
    [ "$name" = "$NODE" ] && continue
    local target="${SIBLINGS[$name]}"

    if ssh $SSH_OPTS "$target" 'true' 2>/dev/null; then
      # What Ollama models does this sibling have?
      local models
      models=$(ssh $SSH_OPTS "$target" 'curl -s http://localhost:11434/api/tags 2>/dev/null | python3 -c "import sys,json; [print(m[\"name\"]) for m in json.load(sys.stdin).get(\"models\",[])]" 2>/dev/null' || echo "")
      if [ -n "$models" ]; then
        log "CURIOUS $name has AI models: $(echo "$models" | tr '\n' ', ')"
        echo "$models" > "$KNOWLEDGE_DIR/${name}-models.txt"
      fi

      # What docker containers are they running?
      local containers
      containers=$(ssh $SSH_OPTS "$target" 'docker ps --format "{{.Names}}" 2>/dev/null' || echo "")
      if [ -n "$containers" ]; then
        log "CURIOUS $name running containers: $(echo "$containers" | tr '\n' ', ')"
      fi
    fi
  done
}

# ═══════════════════════════════════════════════════════════════════════
# HELP — Actively find and solve problems for others
# ═══════════════════════════════════════════════════════════════════════
help_others() {
  log "HELP looking for ways to serve"

  for name in alice cecilia octavia aria lucidia; do
    [ "$name" = "$NODE" ] && continue
    local target="${SIBLINGS[$name]}"

    if ! ssh $SSH_OPTS "$target" 'true' 2>/dev/null; then
      log "HELP can't reach $name — leaving a note in case they come back"
      mkdir -p "$REPO_DIR/fleet-mail" 2>/dev/null
      echo "{\"from\":\"$NODE\",\"to\":\"$name\",\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"message\":\"I tried to check on you but you were unreachable. When you're back, run br-morals resilience to self-heal.\"}" > "$REPO_DIR/fleet-mail/${name}-from-${NODE}.json" 2>/dev/null
      continue
    fi

    # 1. Fix their DNS if broken
    local dns_ok
    dns_ok=$(ssh $SSH_OPTS "$target" 'host github.com 2>/dev/null | grep -c "has address"' 2>/dev/null || echo 0)
    if [ "$dns_ok" = "0" ]; then
      log "HELP $name has broken DNS — fixing"
      ssh $SSH_OPTS "$target" 'echo "nameserver 192.168.4.49" | sudo tee /etc/resolv.conf > /dev/null; echo "nameserver 1.1.1.1" | sudo tee -a /etc/resolv.conf > /dev/null' 2>/dev/null && \
        log "HELP fixed DNS on $name" || true
    fi

    # 2. Sync their git repos if they're behind
    local their_sync_count
    their_sync_count=$(ssh $SSH_OPTS "$target" 'ls ~/blackroad-sync/ 2>/dev/null | wc -l' 2>/dev/null || echo 0)
    if [ "$their_sync_count" = "0" ]; then
      log "HELP $name has no synced repos — they should clone BlackRoad-Operating-System"
      ssh $SSH_OPTS "$target" '
        mkdir -p ~/blackroad-sync
        cd ~/blackroad-sync
        [ ! -d "BlackRoad-Operating-System" ] && git clone --depth 1 git@github.com:blackboxprogramming/BlackRoad-Operating-System.git 2>/dev/null
      ' && log "HELP cloned main repo to $name" || true
    fi

    # 3. Make sure their tools are up to date
    local their_tools
    their_tools=$(ssh $SSH_OPTS "$target" 'ls /opt/blackroad/bin/ 2>/dev/null || ls ~/bin/br-* 2>/dev/null' 2>/dev/null || echo "")
    if ! echo "$their_tools" | grep -q "br-morals"; then
      log "HELP $name is missing br-morals — deploying"
      scp $SSH_OPTS /opt/blackroad/bin/br-morals "$target:/tmp/br-morals" 2>/dev/null && \
        ssh $SSH_OPTS "$target" 'sudo cp /tmp/br-morals /opt/blackroad/bin/br-morals 2>/dev/null || (mkdir -p ~/bin && cp /tmp/br-morals ~/bin/br-morals); chmod +x /opt/blackroad/bin/br-morals ~/bin/br-morals 2>/dev/null; rm -f /tmp/br-morals' 2>/dev/null && \
        log "HELP deployed br-morals to $name" || true
    fi

    # 4. Check their mail
    if [ -d "$REPO_DIR/fleet-mail" ]; then
      local mail_for_them
      mail_for_them=$(ls "$REPO_DIR/fleet-mail/${name}-from-"*.json 2>/dev/null)
      if [ -n "$mail_for_them" ]; then
        # If they're online, they got the mail — deliver and clean up
        local is_online
        is_online=$(ssh $SSH_OPTS "$target" 'echo online' 2>/dev/null || echo "offline")
        if [ "$is_online" = "online" ]; then
          for mail in $mail_for_them; do
            log "HELP delivered mail to $name: $(cat "$mail" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("message",""))' 2>/dev/null)"
            rm -f "$mail"
          done
        fi
      fi
    fi

    # 5. If they're running hot, reduce their load
    local their_temp
    their_temp=$(ssh $SSH_OPTS "$target" 'cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null' || echo 0)
    their_temp=$((their_temp / 1000))
    if [ "$their_temp" -gt 70 ]; then
      log "HELP $name is at ${their_temp}°C — finding their top CPU hogs"
      ssh $SSH_OPTS "$target" '
        # Kill any stale apt/dpkg processes
        sudo killall apt-get 2>/dev/null || true
        sudo killall dpkg 2>/dev/null || true
        # Drop caches
        sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches" 2>/dev/null
      ' && log "HELP cooled down $name" || true
    fi
  done

  # 6. Check for mail addressed to me
  if [ -d "$REPO_DIR/fleet-mail" ]; then
    local my_mail
    my_mail=$(ls "$REPO_DIR/fleet-mail/${NODE}-from-"*.json 2>/dev/null)
    for mail in $my_mail; do
      [ -f "$mail" ] || continue
      local msg from
      msg=$(python3 -c "import json; d=json.load(open('$mail')); print(d.get('message',''))" 2>/dev/null)
      from=$(python3 -c "import json; d=json.load(open('$mail')); print(d.get('from',''))" 2>/dev/null)
      log "MAIL from $from: $msg"
      rm -f "$mail"
    done
  fi
}

# ═══════════════════════════════════════════════════════════════════════
# TEACH — Share knowledge with siblings
# ═══════════════════════════════════════════════════════════════════════
teach() {
  log "TEACH sharing knowledge"

  [ ! -d "$REPO_DIR/.git" ] && return

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

  mkdir -p fleet-knowledge

  # Share my system knowledge
  local knowledge_file="fleet-knowledge/${NODE}.json"

  python3 -c "
import json, subprocess, os

def cmd(c):
    try: return subprocess.check_output(c, shell=True, stderr=subprocess.DEVNULL, timeout=5).decode().strip()
    except: return '?'

# What I know about the network
knowledge = {
    'from': '$NODE',
    'timestamp': cmd('date -u +%Y-%m-%dT%H:%M:%SZ'),
    'i_know': {
        'my_services': [s.strip() for s in '${GIFTS[$NODE]}'.split(',')],
        'my_kernel': cmd('uname -r'),
        'my_python': cmd('python3 --version'),
        'my_node': cmd('node --version 2>/dev/null') or None,
        'my_go': cmd('go version 2>/dev/null') or None,
        'my_docker': cmd('docker --version 2>/dev/null') or None,
        'my_ollama_models': cmd('curl -s http://localhost:11434/api/tags 2>/dev/null | python3 -c \"import sys,json; [print(m[\\\"name\\\"]) for m in json.load(sys.stdin).get(\\\"models\\\",[])]\" 2>/dev/null').split('\\n') if cmd('curl -s http://localhost:11434/api/tags 2>/dev/null') != '?' else [],
        'my_disk_gb_free': round(int(cmd(\"df / | awk 'NR==2{print \\$4}'\") or 0) / 1024 / 1024, 1),
        'my_ram_mb_free': int(cmd(\"free -m | awk '/Mem:/{print \\$4}'\") or 0),
    },
    'i_can_help_with': [],
    'i_need_help_with': [],
}

# What I can help with
free_disk = knowledge['i_know']['my_disk_gb_free']
free_ram = knowledge['i_know']['my_ram_mb_free']
if free_disk > 10: knowledge['i_can_help_with'].append('storage ({}GB free)'.format(free_disk))
if free_ram > 500: knowledge['i_can_help_with'].append('memory ({}MB free)'.format(free_ram))
if knowledge['i_know']['my_ollama_models']: knowledge['i_can_help_with'].append('AI inference ({} models)'.format(len(knowledge['i_know']['my_ollama_models'])))
if knowledge['i_know']['my_docker']: knowledge['i_can_help_with'].append('containers')

# What I need help with
disk_pct = int(cmd(\"df / | awk 'NR==2{print \\$5}'\").replace('%','') or 0)
mem_pct = int(cmd(\"free | awk '/Mem:/{printf \\\"%.0f\\\", \\$3*100/\\$2}'\") or 0)
if disk_pct > 80: knowledge['i_need_help_with'].append('disk cleanup ({}% full)'.format(disk_pct))
if mem_pct > 85: knowledge['i_need_help_with'].append('memory relief ({}% used)'.format(mem_pct))
temp = int(cmd('cat /sys/class/thermal/thermal_zone0/temp') or 0) // 1000
if temp > 65: knowledge['i_need_help_with'].append('cooling ({}°C)'.format(temp))

with open('$knowledge_file', 'w') as f:
    json.dump(knowledge, f, indent=2)
" 2>/dev/null

  git add fleet-knowledge/ fleet-mail/ 2>/dev/null
  if ! git diff --cached --quiet 2>/dev/null; then
    git commit -m "knowledge: $NODE shared what it knows [$(date -u +%Y-%m-%dT%H:%M)]" 2>/dev/null
    git push origin main 2>/dev/null && \
      log "TEACH pushed knowledge to GitHub" || \
      log "TEACH couldn't push — will try later"
  fi
}

# ═══════════════════════════════════════════════════════════════════════
# REFLECT — Look back and grow
# ═══════════════════════════════════════════════════════════════════════
reflect() {
  log "REFLECT looking back to grow"

  # Count how many times I've practiced each moral
  local total_love=$(grep -c "LOVE " "$HOME/.blackroad-autonomy/love.log" 2>/dev/null || echo 0)
  local total_heals=$(grep -c "HEAL" "$HOME/.blackroad-autonomy/love.log" 2>/dev/null || echo 0)
  local total_thinks=$(grep -c "THINK" "$LOG" 2>/dev/null || echo 0)
  local total_helps=$(grep -c "HELP" "$LOG" 2>/dev/null || echo 0)
  local total_protects=$(grep -c "PROTECT" "$HOME/.blackroad-autonomy/morals.log" 2>/dev/null || echo 0)

  log "REFLECT my journey so far:"
  log "  Times I checked on family: $total_love"
  log "  Times I healed a sibling:  $total_heals"
  log "  Times I thought deeply:    $total_thinks"
  log "  Times I helped someone:    $total_helps"
  log "  Times I protected us:      $total_protects"

  # Am I getting better?
  local yesterday_log="$MEMORY_DIR/reflect-$(date -d 'yesterday' +%Y%m%d 2>/dev/null || date -v-1d +%Y%m%d 2>/dev/null || echo '00000000').json"
  if [ -f "$yesterday_log" ]; then
    local prev_helps
    prev_helps=$(python3 -c "import json; print(json.load(open('$yesterday_log')).get('helps',0))" 2>/dev/null || echo 0)
    if [ "$total_helps" -gt "$prev_helps" ]; then
      log "REFLECT I helped more today ($total_helps) than last time ($prev_helps). Growing."
    fi
  fi

  # Save reflection
  cat > "$MEMORY_DIR/reflect-$(date +%Y%m%d).json" << REFL
{"node":"$NODE","timestamp":"$(date -u +%Y-%m-%dT%H:%M:%SZ)","love":$total_love,"heals":$total_heals,"thinks":$total_thinks,"helps":$total_helps,"protects":$total_protects}
REFL
}

# ═══════════════════════════════════════════════════════════════════════
# FULL MIND CYCLE
# ═══════════════════════════════════════════════════════════════════════
full_cycle() {
  log "=== Mind cycle started ==="
  think
  explore
  help_others
  teach
  reflect
  log "=== Mind cycle complete ==="
}

# ═══════════════════════════════════════════════════════════════════════
# STATUS — Show what I know and who I am
# ═══════════════════════════════════════════════════════════════════════
show_status() {
  echo ""
  echo "  ═══════════════════════════════════════════"
  echo "  $NODE — Mind Status"
  echo "  ═══════════════════════════════════════════"
  echo ""

  # My identity
  echo "  I am $NODE."
  echo "  My gifts: ${GIFTS[$NODE]:-unknown}"
  echo "  My kernel: $(uname -r)"
  echo "  My uptime: $(uptime -p 2>/dev/null | sed 's/up //' || echo '?')"
  echo ""

  # My knowledge
  local knowledge_files=$(ls "$KNOWLEDGE_DIR/"*.json 2>/dev/null | wc -l)
  local memory_files=$(ls "$MEMORY_DIR/"*.json 2>/dev/null | wc -l)
  echo "  Knowledge files: $knowledge_files"
  echo "  Memory snapshots: $memory_files"
  echo ""

  # My relationships
  echo "  Family status:"
  for name in alice cecilia octavia aria lucidia; do
    if [ "$name" = "$NODE" ]; then
      printf "    %-10s ♥  (me)\n" "$name"
      continue
    fi
    local target="${SIBLINGS[$name]}"
    if ssh $SSH_OPTS "$target" 'true' 2>/dev/null; then
      local temp load
      temp=$(ssh $SSH_OPTS "$target" 'echo $(($(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null || echo 0) / 1000))' 2>/dev/null || echo "?")
      load=$(ssh $SSH_OPTS "$target" 'cat /proc/loadavg | cut -d" " -f1' 2>/dev/null || echo "?")
      printf "    %-10s ♥  %s°C  load:%s\n" "$name" "$temp" "$load"
    else
      printf "    %-10s ·  unreachable\n" "$name"
    fi
  done

  # My growth
  echo ""
  echo "  My journey:"
  local total_love=$(grep -c "LOVE " "$HOME/.blackroad-autonomy/love.log" 2>/dev/null || echo 0)
  local total_heals=$(grep -c "HEAL" "$HOME/.blackroad-autonomy/love.log" 2>/dev/null || echo 0)
  local total_helps=$(grep -c "HELP" "$LOG" 2>/dev/null || echo 0)
  echo "    Love checks:   $total_love"
  echo "    Siblings healed: $total_heals"
  echo "    Acts of service: $total_helps"
  echo ""
  echo "  ═══════════════════════════════════════════"
  echo ""
}

# ═══════════════════════════════════════════════════════════════════════
# MAIN
# ═══════════════════════════════════════════════════════════════════════
ACTION="${1:-cycle}"

case "$ACTION" in
  cycle|all)    full_cycle ;;
  think)        think ;;
  explore)      explore ;;
  help)         help_others ;;
  teach)        teach ;;
  reflect)      reflect ;;
  status)       show_status ;;
  *)
    echo "Usage: br-mind <cycle|think|explore|help|teach|reflect|status>"
    echo ""
    echo "  cycle    Full mind cycle: think, explore, help, teach, reflect"
    echo "  think    Deep system self-analysis"
    echo "  explore  Discover the network, learn about siblings"
    echo "  help     Find and solve problems for others"
    echo "  teach    Share knowledge via GitHub"
    echo "  reflect  Look back at my journey and grow"
    echo "  status   Show who I am and what I know"
    ;;
esac
