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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SMOM_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PROJECT_ROOT="$(cd "$SMOM_ROOT/.." && pwd)"
PROJECT_ENV_LOADER="$PROJECT_ROOT/scripts/lib/load-project-env.sh"
ENV_FILE="$SMOM_ROOT/.env"
ENV_SOURCE="<none>"
RUN_FORGE_DRY_RUN=0
RUN_TIMEOUT_SECONDS="${RUN_TIMEOUT_SECONDS:-120}"
VERBOSITY="${VERBOSITY:--vv}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --run)
      RUN_FORGE_DRY_RUN=1
      shift
      ;;
    --timeout-seconds)
      RUN_TIMEOUT_SECONDS="${2:?missing value for --timeout-seconds}"
      shift 2
      ;;
    --verbosity)
      VERBOSITY="${2:?missing value for --verbosity}"
      shift 2
      ;;
    *)
      echo "Unknown argument: $1" >&2
      echo "Usage: $0 [--run] [--timeout-seconds <seconds>] [--verbosity <-v|-vv|-vvv|...>]" >&2
      exit 1
      ;;
  esac
done

if [[ -f "$PROJECT_ENV_LOADER" ]]; then
  export PROJECT_ROOT
  # shellcheck disable=SC1090
  source "$PROJECT_ENV_LOADER"
  ENV_SOURCE="$PROJECT_ENV_LOADER"
elif [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
  ENV_SOURCE="$ENV_FILE"
fi
source "$SMOM_ROOT/scripts/lib/forge-scope.sh"

RPC_URL_138="${RPC_URL_138:-http://192.168.11.211:8545}"
WETH="${WETH:-0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}"
OFFICIAL_USDT_ADDRESS="${OFFICIAL_USDT_ADDRESS:-0x004b63A7B5b0E06f6bB6adb4a5F9f590BF3182D1}"
OFFICIAL_USDC_ADDRESS="${OFFICIAL_USDC_ADDRESS:-0x71D6687F38b93CCad569Fa6352c876eea967201b}"
DODO_PMM_PROVIDER_ADDRESS="${DODO_PMM_PROVIDER_ADDRESS:-${DODO_PMM_PROVIDER:-}}"

show_var() {
  local name="$1" value="$2" note="${3:-}"
  printf '  %-28s %s' "$name" "$value"
  [[ -n "$note" ]] && printf '  (%s)' "$note"
  printf '\n'
}

show_secret_var() {
  local name="$1" value="${2:-}" note="${3:-}"
  local display="<unset>"
  if [[ -n "$value" ]]; then
    display="<set>"
  fi
  printf '  %-28s %s' "$name" "$display"
  [[ -n "$note" ]] && printf '  (%s)' "$note"
  printf '\n'
}

probe_support() {
  local token_in="$1" token_out="$2" provider="$3" label="$4"
  local result
  result="$(cast call "$provider" "supportsTokenPair(address,address)(bool)" "$token_in" "$token_out" --rpc-url "$RPC_URL_138" 2>/dev/null || true)"
  if [[ "$result" == "true" ]]; then
    echo "  OK: $label"
    return 0
  fi
  echo "  MISSING: $label"
  return 1
}

probe_quote() {
  local token_in="$1" token_out="$2" provider="$3" amount="$4" label="$5"
  local result amount_out
  result="$(cast call "$provider" "getQuote(address,address,uint256)(uint256,uint256)" "$token_in" "$token_out" "$amount" --rpc-url "$RPC_URL_138" 2>/dev/null || true)"
  amount_out="$(awk 'NR==1 {print $1}' <<<"$result")"
  if [[ -n "$amount_out" && "$amount_out" != "0" ]]; then
    echo "  OK: $label => $amount_out"
    return 0
  fi
  echo "  ZERO-QUOTE: $label"
  return 1
}

run_forge_dry_run() {
  local forge_cmd=(
    forge script script/bridge/trustless/DeployEnhancedSwapRouterV2.s.sol:DeployEnhancedSwapRouterV2
    --skip test
    --non-interactive
    --rpc-url "$RPC_URL_138"
    --private-key "$PRIVATE_KEY"
    "$VERBOSITY"
  )
  (
    cd "$SMOM_ROOT"
    forge build contracts/bridge/trustless/EnhancedSwapRouterV2.sol script/bridge/trustless/DeployEnhancedSwapRouterV2.s.sol
    if command -v timeout >/dev/null 2>&1; then
      timeout "${RUN_TIMEOUT_SECONDS}s" "${forge_cmd[@]}"
    else
      "${forge_cmd[@]}"
    fi
  )
}

echo "=== EnhancedSwapRouterV2 Chain 138 Dry Run ==="
echo "Project root: $SMOM_ROOT"
echo "Repository root: $PROJECT_ROOT"
echo "Env source: $ENV_SOURCE"
echo ""

show_var "RPC_URL_138" "$RPC_URL_138" "Core RPC only"
show_secret_var "PRIVATE_KEY" "${PRIVATE_KEY:-}" "not printed when present"
show_var "DODO_PMM_PROVIDER_ADDRESS" "${DODO_PMM_PROVIDER_ADDRESS:-<unset>}" "required"
show_var "CHAIN138_POOL_WETH_USDT" "${CHAIN138_POOL_WETH_USDT:-<unset>}" "required for swapToStablecoin readiness"
show_var "CHAIN138_POOL_WETH_USDC" "${CHAIN138_POOL_WETH_USDC:-<unset>}" "required for swapToStablecoin readiness"
show_var "CHAIN138_D3_PROXY_ADDRESS" "${CHAIN138_D3_PROXY_ADDRESS:-0xc9a11abB7C63d88546Be24D58a6d95e3762cB843}" "optional DODO v3 execution"
show_var "CHAIN138_D3_MM_ADDRESS" "${CHAIN138_D3_MM_ADDRESS:-0x6550A3a59070061a262a893A1D6F3F490afFDBDA}" "optional DODO v3 execution"
show_var "UNISWAP_V3_ROUTER" "${UNISWAP_V3_ROUTER:-<unset>}" "optional"
show_var "UNISWAP_QUOTER_ADDRESS" "${UNISWAP_QUOTER_ADDRESS:-<unset>}" "optional"
show_var "BALANCER_VAULT" "${BALANCER_VAULT:-<unset>}" "optional"
show_var "CURVE_3POOL" "${CURVE_3POOL:-<unset>}" "optional"
echo ""

if [[ -z "${PRIVATE_KEY:-}" ]]; then
  echo "PRIVATE_KEY is required"
  exit 1
fi

if [[ -z "$DODO_PMM_PROVIDER_ADDRESS" ]]; then
  echo "DODO_PMM_PROVIDER_ADDRESS is required"
  exit 1
fi

readiness_fail=0
echo "Provider route probe"
if [[ -n "${CHAIN138_POOL_WETH_USDT:-}" ]]; then
  if ! probe_support "$WETH" "$OFFICIAL_USDT_ADDRESS" "$DODO_PMM_PROVIDER_ADDRESS" "WETH -> USDT"; then
    readiness_fail=1
  fi
else
  echo "  SKIP: WETH -> USDT (CHAIN138_POOL_WETH_USDT unset)"
fi
if [[ -n "${CHAIN138_POOL_WETH_USDC:-}" ]]; then
  if ! probe_support "$WETH" "$OFFICIAL_USDC_ADDRESS" "$DODO_PMM_PROVIDER_ADDRESS" "WETH -> USDC"; then
    readiness_fail=1
  fi
else
  echo "  SKIP: WETH -> USDC (CHAIN138_POOL_WETH_USDC unset)"
fi
echo ""

echo "Quote readiness probe"
for amount in "1000000000000000000:1" "5000000000000000000:5" "25000000000000000000:25"; do
  raw_amount="${amount%%:*}"
  human_amount="${amount##*:}"
  if [[ -n "${CHAIN138_POOL_WETH_USDT:-}" ]]; then
    if ! probe_quote "$WETH" "$OFFICIAL_USDT_ADDRESS" "$DODO_PMM_PROVIDER_ADDRESS" "$raw_amount" "WETH -> USDT @ ${human_amount} WETH"; then
      readiness_fail=1
    fi
  fi
  if [[ -n "${CHAIN138_POOL_WETH_USDC:-}" ]]; then
    if ! probe_quote "$WETH" "$OFFICIAL_USDC_ADDRESS" "$DODO_PMM_PROVIDER_ADDRESS" "$raw_amount" "WETH -> USDC @ ${human_amount} WETH"; then
      readiness_fail=1
    fi
  fi
done
echo ""

if [[ -z "${CHAIN138_POOL_WETH_USDT:-}" || -z "${CHAIN138_POOL_WETH_USDC:-}" ]]; then
  echo "Readiness note: canonical WETH -> stable DODO PMM routes are still incomplete, so swapToStablecoin readiness remains partial."
  echo "The router-v2 deployment can still proceed for explicit executeRoute calldata, including DODO v3 pilot execution."
elif (( readiness_fail == 1 )); then
  echo "Readiness failed: Chain 138 still lacks at least one required WETH -> stable DODO route or non-zero quote."
  echo "Set CHAIN138_POOL_WETH_USDT / CHAIN138_POOL_WETH_USDC after creating and registering the canonical pools, then rerun."
  exit 1
else
  echo "Readiness passed: required WETH -> stable DODO routes are present with non-zero quotes for 1/5/25 WETH."
fi

if (( RUN_FORGE_DRY_RUN == 1 )); then
  echo ""
  run_forge_dry_run
fi
