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

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

CALLER_POSITION_MANAGER="${POSITION_MANAGER:-}"
CALLER_RPC_URL="${RPC_URL:-}"
CALLER_TOKEN_A="${TOKEN_A:-}"
CALLER_TOKEN_B="${TOKEN_B:-}"
CALLER_AMOUNT_A="${AMOUNT_A:-}"
CALLER_AMOUNT_B="${AMOUNT_B:-}"
CALLER_FEE="${FEE:-}"
CALLER_EXECUTE="${EXECUTE:-}"
CALLER_RECIPIENT="${RECIPIENT:-}"
CALLER_PRIVATE_KEY="${PRIVATE_KEY:-}"

if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$REPO_ROOT"
fi

POSITION_MANAGER="${CALLER_POSITION_MANAGER:-${POSITION_MANAGER:-}}"
RPC_URL="${CALLER_RPC_URL:-${ETHEREUM_MAINNET_RPC:-${ETH_MAINNET_RPC_URL:-${RPC_URL:-}}}}"
TOKEN_A="${CALLER_TOKEN_A:-${TOKEN_A:-}}"
TOKEN_B="${CALLER_TOKEN_B:-${TOKEN_B:-}}"
AMOUNT_A="${CALLER_AMOUNT_A:-${AMOUNT_A:-}}"
AMOUNT_B="${CALLER_AMOUNT_B:-${AMOUNT_B:-}}"
FEE="${CALLER_FEE:-${FEE:-500}}"
EXECUTE="${CALLER_EXECUTE:-${EXECUTE:-0}}"
DEADLINE_SECONDS="${DEADLINE_SECONDS:-3600}"
RECIPIENT="${CALLER_RECIPIENT:-${RECIPIENT:-}}"
PRIVATE_KEY="${CALLER_PRIVATE_KEY:-${PRIVATE_KEY:-}}"

if [[ -z "$POSITION_MANAGER" || -z "$RPC_URL" || -z "$TOKEN_A" || -z "$TOKEN_B" || -z "$AMOUNT_A" || -z "$AMOUNT_B" ]]; then
  echo "Required: POSITION_MANAGER RPC_URL TOKEN_A TOKEN_B AMOUNT_A AMOUNT_B" >&2
  exit 1
fi

if [[ -z "$RECIPIENT" ]]; then
  if [[ -z "$PRIVATE_KEY" ]]; then
    echo "Set RECIPIENT or PRIVATE_KEY" >&2
    exit 1
  fi
  RECIPIENT="$(cast wallet address --private-key "$PRIVATE_KEY")"
fi

lower_hex="$(printf '%s\n%s\n' "$TOKEN_A" "$TOKEN_B" | tr '[:upper:]' '[:lower:]' | sort | sed -n '1p')"
upper_hex="$(printf '%s\n%s\n' "$TOKEN_A" "$TOKEN_B" | tr '[:upper:]' '[:lower:]' | sort | sed -n '2p')"

token0="$lower_hex"
token1="$upper_hex"
amount0="$AMOUNT_A"
amount1="$AMOUNT_B"

if [[ "${TOKEN_A,,}" != "$token0" ]]; then
  amount0="$AMOUNT_B"
  amount1="$AMOUNT_A"
fi

case "$FEE" in
  100) tick_spacing=1 ;;
  500) tick_spacing=10 ;;
  3000) tick_spacing=60 ;;
  10000) tick_spacing=200 ;;
  *)
    echo "Unsupported fee tier for tick-spacing inference: $FEE" >&2
    exit 1
    ;;
esac

min_tick=-887272
max_tick=887272
tick_lower=$(( (min_tick / tick_spacing) * tick_spacing ))
tick_upper=$(( (max_tick / tick_spacing) * tick_spacing ))

deadline="$(($(date +%s) + DEADLINE_SECONDS))"

echo "Funding Uniswap v3 pool"
echo "  token0: $token0 amount0: $amount0"
echo "  token1: $token1 amount1: $amount1"
echo "  fee: $FEE ticks: [$tick_lower, $tick_upper]"
echo "  recipient: $RECIPIENT"

if [[ "$EXECUTE" != "1" ]]; then
  echo "Dry run only."
  echo "Approve token0:"
  echo "  cast send \"$token0\" 'approve(address,uint256)' \"$POSITION_MANAGER\" \"$amount0\" --rpc-url \"$RPC_URL\" --private-key \"\$PRIVATE_KEY\""
  echo "Approve token1:"
  echo "  cast send \"$token1\" 'approve(address,uint256)' \"$POSITION_MANAGER\" \"$amount1\" --rpc-url \"$RPC_URL\" --private-key \"\$PRIVATE_KEY\""
  echo "Mint position:"
  echo "  cast send \"$POSITION_MANAGER\" \"mint((address,address,uint24,int24,int24,uint256,uint256,uint256,uint256,address,uint256))\" \"($token0,$token1,$FEE,$tick_lower,$tick_upper,$amount0,$amount1,0,0,$RECIPIENT,$deadline)\" --rpc-url \"$RPC_URL\" --private-key \"\$PRIVATE_KEY\" -vv"
  exit 0
fi

if [[ -z "$PRIVATE_KEY" ]]; then
  echo "PRIVATE_KEY is required when EXECUTE=1" >&2
  exit 1
fi

cast_send_wait() {
  local to="$1"
  local sig="$2"
  local use_gas_limit="${CAST_GAS_LIMIT:-}"
  shift 2
  local -a extra=()
  local from nonce
  from="$(cast wallet address --private-key "$PRIVATE_KEY")"
  nonce="$(cast nonce "$from" --rpc-url "$RPC_URL" --block pending)"
  extra+=(--nonce "$nonce")
  if [[ -n "$use_gas_limit" ]]; then
    extra+=(--gas-limit "$use_gas_limit")
  fi
  if [[ "${CAST_USE_LEGACY:-1}" == "1" ]]; then
    extra+=(--legacy)
    if [[ -n "${CAST_GAS_PRICE:-}" ]]; then
      extra+=(--gas-price "$CAST_GAS_PRICE")
    fi
  elif [[ -n "${CAST_MAX_PRIORITY_FEE_PER_GAS:-}" ]]; then
    extra+=(--priority-gas-price "$CAST_MAX_PRIORITY_FEE_PER_GAS")
  fi
  local out tx
  out="$(cast send "$to" "$sig" "$@" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --async \
    --timeout "${CAST_SEND_TIMEOUT:-1800}" \
    "${extra[@]}")"
  tx="$(printf '%s\n' "$out" | grep -oE '0x[a-fA-F0-9]{64}' | head -1)"
  [[ -n "$tx" ]] || { echo "cast send did not return tx hash: $out" >&2; return 1; }
  echo "  tx: $tx (nonce $nonce)"
  if wait_for_mainnet_receipt "$tx" "$RPC_URL"; then
    return 0
  fi
  if [[ -n "${MESH_FUND_VERIFY_POOL:-}" && -n "${MESH_FUND_VERIFY_TOKEN:-}" && -n "${MESH_FUND_VERIFY_MIN:-}" ]]; then
    local vb
    vb="$(cast call "${MESH_FUND_VERIFY_TOKEN}" "balanceOf(address)(uint256)" "${MESH_FUND_VERIFY_POOL}" --rpc-url "$RPC_URL" | awk '{print $1}')"
    if python3 -c "import sys; vb=int('$vb'); m=int('${MESH_FUND_VERIFY_MIN}'); sys.exit(0 if vb >= m - 10**12 else 1)"; then
      echo "  receipt timeout; on-chain pool leg OK (balance=$vb)"
      return 0
    fi
  fi
  return 1
}

allowance_of() {
  cast call "$1" "allowance(address,address)(uint256)" "$RECIPIENT" "$POSITION_MANAGER" --rpc-url "$RPC_URL" | awk '{print $1}'
}

allowance_lt() {
  python3 - "$1" "$2" <<'PY'
import sys
print("yes" if int(sys.argv[1]) < int(sys.argv[2]) else "no")
PY
}

PROXMOX_ROOT="$(cd "$REPO_ROOT/.." && pwd)"
if [[ -f "$PROXMOX_ROOT/scripts/lib/mainnet_gas_api.sh" ]]; then
  # shellcheck source=/dev/null
  source "$PROXMOX_ROOT/scripts/lib/mainnet_gas_api.sh"
  export_mesh_mainnet_gas
fi

need0="$(allowance_of "$token0")"
if [[ "$(allowance_lt "$need0" "$amount0")" == yes ]]; then
  CAST_GAS_LIMIT="" cast_send_wait "$token0" \
    "approve(address,uint256)" \
    "$POSITION_MANAGER" \
    "$amount0"
else
  echo "  skip approve token0 (allowance sufficient)"
fi

need1="$(allowance_of "$token1")"
if [[ "$(allowance_lt "$need1" "$amount1")" == yes ]]; then
  CAST_GAS_LIMIT="" cast_send_wait "$token1" \
    "approve(address,uint256)" \
    "$POSITION_MANAGER" \
    "$amount1"
else
  echo "  skip approve token1 (allowance sufficient)"
fi

if [[ "${CAST_GAS_ESTIMATE_MINT:-1}" == "1" ]]; then
  mint_est="$(cast estimate "$POSITION_MANAGER" \
    "mint((address,address,uint24,int24,int24,uint256,uint256,uint256,uint256,address,uint256))" \
    "($token0,$token1,$FEE,$tick_lower,$tick_upper,$amount0,$amount1,0,0,$RECIPIENT,$deadline)" \
    --rpc-url "$RPC_URL" \
    --from "$RECIPIENT" 2>/dev/null | awk '{print $1}')" || true
  if [[ -n "$mint_est" && "$mint_est" -gt 0 ]]; then
    export CAST_GAS_LIMIT="$(( mint_est * 130 / 100 ))"
    echo "  mint gas estimate: $mint_est → limit $CAST_GAS_LIMIT"
  fi
fi

cast_send_wait "$POSITION_MANAGER" \
  "mint((address,address,uint24,int24,int24,uint256,uint256,uint256,uint256,address,uint256))" \
  "($token0,$token1,$FEE,$tick_lower,$tick_upper,$amount0,$amount1,0,0,$RECIPIENT,$deadline)"
