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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SMOM_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
ENV_FILE="$SMOM_ROOT/.env"

source "$SMOM_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

RPC_URL_138="${RPC_URL_138:-http://192.168.11.211:8545}"
DODO_PMM_INTEGRATION_ADDRESS="${CHAIN_138_DODO_PMM_INTEGRATION:-${DODO_PMM_INTEGRATION_ADDRESS:-0x5BDc62f1ae7D630c37A8B363a1d49845356Ee72d}}"
DODO_PMM_PROVIDER_ADDRESS="${CHAIN_138_DODO_PMM_PROVIDER:-${DODO_PMM_PROVIDER_ADDRESS:-0x5CAe6Ce155b7f08D3a956F5Dc82fC9945f29B381}}"

[[ -n "$DODO_PMM_INTEGRATION_ADDRESS" ]] || { echo "DODO_PMM_INTEGRATION_ADDRESS not set"; exit 1; }
[[ -n "$DODO_PMM_PROVIDER_ADDRESS" ]] || { echo "DODO_PMM_PROVIDER_ADDRESS not set"; exit 1; }

declare -A SYMBOLS=(
  ["0x93e66202a11b1772e55407b32b44e5cd8eda7f22"]="cUSDT"
  ["0xf22258f57794cc8e06237084b353ab30fffa640b"]="cUSDC"
  ["0x8085961f9cf02b4d800a3c6d386d31da4b34266a"]="cEURC"
  ["0xdf4b71c61e5912712c1bdd451416b9ac26949d72"]="cEURT"
  ["0x003960f16d9d34f2e98d62723b6721fb92074ad2"]="cGBPC"
  ["0x350f54e4d23795f86a9c03988c7135357ccad97c"]="cGBPT"
  ["0xd51482e567c03899eece3cae8a058161fd56069d"]="cAUDC"
  ["0xee269e1226a334182aace90056ee4ee5cc8a6770"]="cJPYC"
  ["0x873990849dda5117d7c644f0af24370797c03885"]="cCHFC"
  ["0x54dbd40cf05e15906a2c21f600937e96787f5679"]="cCADC"
  ["0x290e52a8819a4fbd0714e517225429aa2b70ec6b"]="cXAUC"
  ["0x94e408e26c6fd8f4ee00b54df19082fda07dc96e"]="cXAUT"
  ["0x004b63a7b5b0e06f6bb6adb4a5f9f590bf3182d1"]="USDT"
  ["0x71d6687f38b93ccad569fa6352c876eea967201b"]="USDC"
  ["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"]="WETH"
)

rpc_call() {
  local to="$1" data="$2"
  local payload
  payload=$(printf '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"%s","data":"%s"},"latest"],"id":1}' "$to" "$data")
  curl -s -X POST "$RPC_URL_138" -H 'Content-Type: application/json' --data "$payload"
}

json_result() {
  sed -n 's/.*"result":"\([^"]*\)".*/\1/p'
}

word_at() {
  local hex="$1" index="$2"
  local start=$(( index * 64 ))
  printf '%s' "${hex:$start:64}"
}

addr_from_word() {
  local word="$1"
  printf '0x%s' "${word:24:40}"
}

symbol_for() {
  local lower
  lower="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
  if [[ -n "${SYMBOLS[$lower]:-}" ]]; then
    printf '%s' "${SYMBOLS[$lower]}"
  else
    printf '%s' "$1"
  fi
}

decode_address_array() {
  local result="${1#0x}"
  local count_hex count i
  count_hex="$(word_at "$result" 1)"
  count=$((16#$count_hex))
  for ((i=0; i<count; i++)); do
    addr_from_word "$(word_at "$result" $((i + 2)))"
    printf '\n'
  done
}

get_all_pools_data="$(rpc_call "$DODO_PMM_INTEGRATION_ADDRESS" "$(cast calldata "getAllPools()")" | json_result)"
[[ -n "$get_all_pools_data" ]] || { echo "Failed to read getAllPools() from integration"; exit 1; }

mapfile -t pools < <(decode_address_array "$get_all_pools_data")

echo "=== DODO Registration Inventory (read-only) ==="
echo "Integration: $DODO_PMM_INTEGRATION_ADDRESS"
echo "Provider:    $DODO_PMM_PROVIDER_ADDRESS"
echo "RPC:         $RPC_URL_138"
echo "Pools found: ${#pools[@]}"
echo ""

for pool in "${pools[@]}"; do
  pool_config_data="$(rpc_call "$DODO_PMM_INTEGRATION_ADDRESS" "$(cast calldata "getPoolConfig(address)" "$pool")" | json_result)"
  [[ -n "$pool_config_data" ]] || {
    echo "Pool: $pool"
    echo "  SKIP: pool is removed or getPoolConfig(pool) is unreadable"
    echo ""
    continue
  }
  config_hex="${pool_config_data#0x}"
  base="$(addr_from_word "$(word_at "$config_hex" 1)")"
  quote="$(addr_from_word "$(word_at "$config_hex" 2)")"

  echo "Pool:  $pool"
  echo "Base:  $(symbol_for "$base") ($base)"
  echo "Quote: $(symbol_for "$quote") ($quote)"
  echo "Would register:"
  echo "  registerPool($base, $quote, $pool)"
  echo "  registerPool($quote, $base, $pool)"
  echo ""
done

echo "Dry-run command:"
echo "  cd \"$SMOM_ROOT\" && source scripts/load-env.sh && bash scripts/deployment/inventory-register-dodo-pools-chain138.sh"
echo ""
echo "Broadcast command:"
echo "  cd \"$SMOM_ROOT\" && source scripts/load-env.sh && bash scripts/forge/scope.sh script liquidity script/liquidity/RegisterDODOPools.s.sol:RegisterDODOPools --rpc-url \"\$RPC_URL_138\" --private-key \"\$PRIVATE_KEY\" --broadcast --slow --with-gas-price 1000000000"
