#!/usr/bin/env bash
# Push ETH/USD into the on-chain WETH MockPriceFeed used by OraclePriceFeed / PriceFeedKeeper
# (avoids Besu vs aggregator updatedAt skew on the public ETH/USD aggregator).
#
# Env: smom-dbis-138/.env — RPC_URL_138, PRIVATE_KEY, optional CHAIN138_WETH_MOCK_PRICE_FEED,
#      COINGECKO_API_KEY (Pro URL + header when set).
# Usage: ./scripts/reserve/sync-weth-mock-price.sh [rpc-url]

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SMOM_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$SMOM_ROOT"

if [ -f "$SMOM_ROOT/.env" ]; then
  set -a
  # shellcheck source=/dev/null
  source "$SMOM_ROOT/.env"
  set +a
fi

RPC="${1:-${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}}"
MOCK="${CHAIN138_WETH_MOCK_PRICE_FEED:-0x3e8725b8De386feF3eFE5678c92eA6aDB41992B2}"
CG_UA="${COINGECKO_USER_AGENT:-proxmox-chain138-oracle/1.0 (dbis-138)}"

if [ -z "${PRIVATE_KEY:-}" ]; then
  echo "ERROR: PRIVATE_KEY required" >&2
  exit 1
fi

fetch_usd() {
  local u="0"
  if [ -n "${COINGECKO_API_KEY:-}" ]; then
    u=$(curl -s --max-time 20 -A "$CG_UA" -H "x-cg-demo-api-key: $COINGECKO_API_KEY" \
      'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd' | \
      python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('ethereum',{}).get('usd',0) or 0)" 2>/dev/null || echo 0)
  fi
  if { [ "$u" = "0" ] || [ -z "$u" ]; } && [ -n "${COINGECKO_API_KEY:-}" ]; then
    u=$(curl -s --max-time 20 -A "$CG_UA" -H "x-cg-pro-api-key: $COINGECKO_API_KEY" \
      'https://pro-api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd' | \
      python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('ethereum',{}).get('usd',0) or 0)" 2>/dev/null || echo 0)
  fi
  if [ "$u" = "0" ] || [ -z "$u" ]; then
    u=$(curl -s --max-time 20 -A "$CG_UA" 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd' | \
      python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('ethereum',{}).get('usd',0) or 0)" 2>/dev/null || echo 0)
  fi
  echo "$u"
}

USD="$(fetch_usd)"
if [ "$(python3 -c "print(1 if float('$USD')>0 else 0)" 2>/dev/null || echo 0)" != 1 ]; then
  echo "WARN: CoinGecko failed, trying Binance..." >&2
  USD=$(curl -s 'https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT' | \
    python3 -c "import sys, json; print(json.load(sys.stdin).get('price',0) or 0)" 2>/dev/null || echo 0)
fi

PRICE_I256="$(python3 -c "u=float('$USD'); print(int(round(u*1e8)))")"
if [ "$PRICE_I256" -le 0 ]; then
  echo "ERROR: invalid ETH price: $USD" >&2
  exit 1
fi

echo "Mock $MOCK updatePrice(int256) = $PRICE_I256 (8 dec; USD ~ $USD)"
cast send "$MOCK" "updatePrice(int256)" "$PRICE_I256" \
  --rpc-url "$RPC" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-limit 200000 \
  --gas-price "${MESH_CAST_GAS_PRICE:-2gwei}"
