#!/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"
CONFIG_JSON="${POOL_CONFIG_JSON:-$SMOM_ROOT/config/chain138-pmm-pools.json}"
ORIG_RPC_URL_138="${RPC_URL_138-}"
ORIG_RPC_URL="${RPC_URL-}"
ORIG_DODO_PMM_INTEGRATION_ADDRESS="${DODO_PMM_INTEGRATION_ADDRESS-}"
ORIG_DODO_PMM_INTEGRATION="${DODO_PMM_INTEGRATION-}"
ORIG_DODO_PMM_PROVIDER_ADDRESS="${DODO_PMM_PROVIDER_ADDRESS-}"
ORIG_DODO_PMM_PROVIDER="${DODO_PMM_PROVIDER-}"

if [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
fi

[[ -n "$ORIG_RPC_URL_138" ]] && RPC_URL_138="$ORIG_RPC_URL_138"
[[ -n "$ORIG_RPC_URL" ]] && RPC_URL="$ORIG_RPC_URL"
[[ -n "$ORIG_DODO_PMM_INTEGRATION_ADDRESS" ]] && DODO_PMM_INTEGRATION_ADDRESS="$ORIG_DODO_PMM_INTEGRATION_ADDRESS"
[[ -n "$ORIG_DODO_PMM_INTEGRATION" ]] && DODO_PMM_INTEGRATION="$ORIG_DODO_PMM_INTEGRATION"
[[ -n "$ORIG_DODO_PMM_PROVIDER_ADDRESS" ]] && DODO_PMM_PROVIDER_ADDRESS="$ORIG_DODO_PMM_PROVIDER_ADDRESS"
[[ -n "$ORIG_DODO_PMM_PROVIDER" ]] && DODO_PMM_PROVIDER="$ORIG_DODO_PMM_PROVIDER"

RPC_URL_138="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
if [[ -n "$ORIG_DODO_PMM_INTEGRATION_ADDRESS" ]]; then
  DODO_PMM_INTEGRATION_ADDRESS="$ORIG_DODO_PMM_INTEGRATION_ADDRESS"
else
  DODO_PMM_INTEGRATION_ADDRESS="${CHAIN_138_DODO_PMM_INTEGRATION:-0x5BDc62f1ae7D630c37A8B363a1d49845356Ee72d}"
fi
if [[ -n "$ORIG_DODO_PMM_PROVIDER_ADDRESS" ]]; then
  DODO_PMM_PROVIDER_ADDRESS="$ORIG_DODO_PMM_PROVIDER_ADDRESS"
else
  DODO_PMM_PROVIDER_ADDRESS="${CHAIN_138_DODO_PMM_PROVIDER:-0x5CAe6Ce155b7f08D3a956F5Dc82fC9945f29B381}"
fi

[[ -f "$CONFIG_JSON" ]] || { echo "POOL_CONFIG_JSON not found: $CONFIG_JSON" >&2; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq is required" >&2; exit 1; }
command -v cast >/dev/null 2>&1 || { echo "cast is required" >&2; exit 1; }
[[ -n "$DODO_PMM_INTEGRATION_ADDRESS" ]] || { echo "DODO_PMM_INTEGRATION_ADDRESS not set" >&2; exit 1; }
[[ -n "$DODO_PMM_PROVIDER_ADDRESS" ]] || { echo "DODO_PMM_PROVIDER_ADDRESS not set" >&2; exit 1; }

declare -A TOKENS=()
while IFS=$'\t' read -r sym addr; do
  TOKENS["$sym"]="$addr"
done < <(jq -r '.tokens | to_entries[] | [.key, .value] | @tsv' "$CONFIG_JSON")

mapfile -t C_STARS < <(jq -r '.groups.cStarSymbols[]' "$CONFIG_JSON")
mapfile -t OFFICIALS < <(jq -r '.groups.officialStableSymbols[]' "$CONFIG_JSON")
WETH_SYMBOL="$(jq -r '.groups.wethSymbol' "$CONFIG_JSON")"

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'
}

hex_to_addr() {
  local value="${1#0x}"
  if [[ ${#value} -lt 40 ]]; then
    echo "0x0000000000000000000000000000000000000000"
    return 0
  fi
  printf '0x%s\n' "${value: -40}"
}

pool_for() {
  local calldata result
  calldata="$(cast calldata "pools(address,address)" "$1" "$2" 2>/dev/null || true)"
  [[ -n "$calldata" ]] || { echo "0x0000000000000000000000000000000000000000"; return 0; }
  result="$(rpc_call "$DODO_PMM_INTEGRATION_ADDRESS" "$calldata" | json_result)"
  [[ -n "$result" ]] || { echo "0x0000000000000000000000000000000000000000"; return 0; }
  hex_to_addr "$result"
}

provider_pool_for() {
  local calldata result
  calldata="$(cast calldata "pools(address,address)" "$1" "$2" 2>/dev/null || true)"
  [[ -n "$calldata" ]] || { echo "0x0000000000000000000000000000000000000000"; return 0; }
  result="$(rpc_call "$DODO_PMM_PROVIDER_ADDRESS" "$calldata" | json_result)"
  [[ -n "$result" ]] || { echo "0x0000000000000000000000000000000000000000"; return 0; }
  hex_to_addr "$result"
}

declare -A SEEN=()
DESIRED_PAIRS=()

add_pair() {
  local base_sym="$1" quote_sym="$2"
  local base="${TOKENS[$base_sym]:-}"
  local quote="${TOKENS[$quote_sym]:-}"
  local key="${base_sym}|${quote_sym}"

  [[ -n "$base" && -n "$quote" ]] || return 0
  [[ -z "${SEEN[$key]:-}" ]] || return 0
  SEEN["$key"]=1
  DESIRED_PAIRS+=("${base_sym}|${base}|${quote_sym}|${quote}")
}

if [[ "$(jq -r '.groups.deploy.cStarVsCStar' "$CONFIG_JSON")" == "true" ]]; then
  for ((i=0; i<${#C_STARS[@]}; i++)); do
    for ((j=i+1; j<${#C_STARS[@]}; j++)); do
      add_pair "${C_STARS[$i]}" "${C_STARS[$j]}"
    done
  done
fi
if [[ "$(jq -r '.groups.deploy.cStarVsOfficial' "$CONFIG_JSON")" == "true" ]]; then
  for cstar in "${C_STARS[@]}"; do
    for official in "${OFFICIALS[@]}"; do
      add_pair "$cstar" "$official"
    done
  done
fi
if [[ "$(jq -r '.groups.deploy.cStarVsWeth' "$CONFIG_JSON")" == "true" ]]; then
  for cstar in "${C_STARS[@]}"; do
    add_pair "$cstar" "$WETH_SYMBOL"
  done
fi
if [[ "$(jq -r '.groups.deploy.officialVsWeth' "$CONFIG_JSON")" == "true" ]]; then
  for official in "${OFFICIALS[@]}"; do
    add_pair "$official" "$WETH_SYMBOL"
  done
fi
while IFS=$'\t' read -r base_sym quote_sym; do
  add_pair "$base_sym" "$quote_sym"
done < <(jq -r '.explicitPairs[]? | [.baseSymbol, .quoteSymbol] | @tsv' "$CONFIG_JSON")
while IFS=$'\t' read -r base_sym quote_sym; do
  add_pair "$base_sym" "$quote_sym"
done < <(jq -r '.plannedPairs[]? | [.baseSymbol, .quoteSymbol] | @tsv' "$CONFIG_JSON")

echo "=== Chain 138 PMM Desired-State Inventory ==="
echo "Config:       $CONFIG_JSON"
echo "Integration:  $DODO_PMM_INTEGRATION_ADDRESS"
echo "Provider:     $DODO_PMM_PROVIDER_ADDRESS"
echo "RPC:          $RPC_URL_138"
echo "Desired pairs:${#DESIRED_PAIRS[@]}"
echo ""

existing=0
missing=0
aligned=0
needs_registration=0
stale_provider_only=0
provider_mismatch=0

for pair in "${DESIRED_PAIRS[@]}"; do
  IFS='|' read -r base_sym base quote_sym quote <<< "$pair"
  label="${base_sym}/${quote_sym}"
  pool="$(pool_for "$base" "$quote")"
  provider_pool_ab="$(provider_pool_for "$base" "$quote")"
  provider_pool_ba="$(provider_pool_for "$quote" "$base")"

  if [[ "$pool" != "0x0000000000000000000000000000000000000000" ]]; then
    ((existing++)) || true
    status="EXISTS"
  else
    ((missing++)) || true
    status="MISSING"
  fi

  if [[ "$pool" != "0x0000000000000000000000000000000000000000" && "$provider_pool_ab" == "$pool" && "$provider_pool_ba" == "$pool" ]]; then
    ((aligned++)) || true
    route_status="ALIGNED"
  elif [[ "$pool" != "0x0000000000000000000000000000000000000000" && "$provider_pool_ab" == "0x0000000000000000000000000000000000000000" && "$provider_pool_ba" == "0x0000000000000000000000000000000000000000" ]]; then
    ((needs_registration++)) || true
    route_status="NEEDS_REGISTRATION"
  elif [[ "$pool" == "0x0000000000000000000000000000000000000000" && ( "$provider_pool_ab" != "0x0000000000000000000000000000000000000000" || "$provider_pool_ba" != "0x0000000000000000000000000000000000000000" ) ]]; then
    ((stale_provider_only++)) || true
    route_status="STALE_PROVIDER_ONLY"
  else
    ((provider_mismatch++)) || true
    route_status="PROVIDER_MISMATCH"
  fi

  echo "$status  $route_status  $label  integrationPool=$pool providerAB=$provider_pool_ab providerBA=$provider_pool_ba"
done

echo ""
echo "Summary:"
echo "  Existing pools:       $existing"
echo "  Missing pools:        $missing"
echo "  Aligned routes:       $aligned"
echo "  Needs registration:   $needs_registration"
echo "  Stale provider only:  $stale_provider_only"
echo "  Provider mismatch:    $provider_mismatch"
