#!/usr/bin/env bash
# autoresearch-tick.sh — Periodic XDC autoresearch tick (#120)
# Collects node metrics, logs research entries, and reports summary.
# Usage: ./autoresearch-tick.sh [--dry-run]
set -euo pipefail

readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
readonly DATA_DIR="${REPO_ROOT}/data/autoresearch"
readonly LOG_FILE="${DATA_DIR}/tick.jsonl"
readonly SUMMARY_FILE="${DATA_DIR}/latest-summary.json"
readonly TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

DRY_RUN=false
[[ "${1:-}" == "--dry-run" ]] && DRY_RUN=true

mkdir -p "$DATA_DIR"

log() {
  echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*"
}

# --- Gather metrics ---
get_block_height() {
  # Try local geth RPC first, fallback to public RPC
  local height
  height=$(curl -s -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
    http://localhost:8545 2>/dev/null | grep -o '"result":"0x[0-9a-fA-F]*"' | cut -d'"' -f4 | xargs -I {} printf "%d\n" {} 2>/dev/null) || true
  if [[ -z "${height:-}" ]]; then
    height=$(curl -s -X POST -H "Content-Type: application/json" \
      --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
      https://rpc.xinfin.network 2>/dev/null | grep -o '"result":"0x[0-9a-fA-F]*"' | cut -d'"' -f4 | xargs -I {} printf "%d\n" {} 2>/dev/null) || true
  fi
  echo "${height:-0}"
}

get_peer_count() {
  local peers
  peers=$(curl -s -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":1}' \
    http://localhost:8545 2>/dev/null | grep -o '"result":"0x[0-9a-fA-F]*"' | cut -d'"' -f4 | xargs -I {} printf "%d\n" {} 2>/dev/null) || true
  echo "${peers:-0}"
}

get_syncing() {
  local sync
  sync=$(curl -s -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' \
    http://localhost:8545 2>/dev/null | grep -o '"result":[^}]*' | cut -d: -f2-) || true
  if [[ -z "${sync:-}" ]] || [[ "$sync" == "false" ]]; then
    echo "synced"
  else
    echo "syncing"
  fi
}

get_gas_price() {
  local gp
  gp=$(curl -s -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}' \
    https://rpc.xinfin.network 2>/dev/null | grep -o '"result":"0x[0-9a-fA-F]*"' | cut -d'"' -f4 | xargs -I {} printf "%d\n" {} 2>/dev/null) || true
  echo "${gp:-0}"
}

# --- Main tick ---
log "=== XDC Autoresearch Tick ==="
log "Timestamp: $TIMESTAMP"
log "Dry-run:   $DRY_RUN"

BLOCK_HEIGHT=$(get_block_height)
PEER_COUNT=$(get_peer_count)
SYNC_STATUS=$(get_syncing)
GAS_PRICE=$(get_gas_price)
HOSTNAME=$(hostname)

log "Block height: $BLOCK_HEIGHT"
log "Peer count:   $PEER_COUNT"
log "Sync status:  $SYNC_STATUS"
log "Gas price:    $GAS_PRICE"

# Build JSON entry
ENTRY=$(cat <<JSON
{"timestamp":"$TIMESTAMP","hostname":"$HOSTNAME","block_height":$BLOCK_HEIGHT,"peer_count":$PEER_COUNT,"sync_status":"$SYNC_STATUS","gas_price":$GAS_PRICE}
JSON
)

if [[ "$DRY_RUN" == true ]]; then
  log "[DRY-RUN] Would write entry:"
  echo "$ENTRY"
else
  echo "$ENTRY" >> "$LOG_FILE"
  echo "$ENTRY" > "$SUMMARY_FILE"
  log "Entry written to $LOG_FILE"
fi

# Summary report
cat <<REPORT

--- Autoresearch Tick Summary ---
Timestamp:    $TIMESTAMP
Hostname:     $HOSTNAME
Block Height: $BLOCK_HEIGHT
Peer Count:   $PEER_COUNT
Sync Status:  $SYNC_STATUS
Gas Price:    $GAS_PRICE
Data Dir:     $DATA_DIR
Log File:     $LOG_FILE
---------------------------------
REPORT

log "Tick complete."
