#!/usr/bin/env bash
# Create a Uniswap V3 pool for cUSDT/cUSDC (or two token addresses) on a given chain.
# Requires: cast (foundry), RPC for the chain, PRIVATE_KEY with gas.
# Usage:
#   CUSDT=0x... CUSDC=0x... RPC_URL=$POLYGON_MAINNET_RPC ./scripts/deployment/create-uniswap-v3-pool-cusdt-cusdc.sh
#   Or: TOKEN_A=0x... TOKEN_B=0x... FEE=500 RPC_URL=... ./scripts/deployment/create-uniswap-v3-pool-cusdt-cusdc.sh
# Fee: 500 = 0.05% (typical for stables), 3000 = 0.3%, 10000 = 1%.
# Uniswap V3 factory (mainnet, Polygon, BSC, Base, Arbitrum, Optimism): 0x1F98431c8aD98523631AE4a59f267346ea31F984
# See docs/deployment/CUSDT_CUSDC_MULTICHAIN_LIQUIDITY_RUNBOOK.md
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
DOTENV="$REPO_ROOT/.env"

UNISWAP_V3_FACTORY="${UNISWAP_V3_FACTORY:-0x1F98431c8aD98523631AE4a59f267346ea31F984}"
FEE="${FEE:-500}"
TOKEN_A="${TOKEN_A:-${CUSDT_ADDRESS:-}}"
TOKEN_B="${TOKEN_B:-${CUSDC_ADDRESS:-}}"
if [[ -z "$TOKEN_A" ]] && [[ -n "${CUSDT_ADDRESS_137:-}" ]]; then
  TOKEN_A="${CUSDT_ADDRESS_137}"
  TOKEN_B="${CUSDC_ADDRESS_137}"
fi
if [[ -z "$TOKEN_A" ]]; then
  echo "Set TOKEN_A and TOKEN_B (or CUSDT_ADDRESS and CUSDC_ADDRESS, or CUSDT_ADDRESS_<chainId> and CUSDC_ADDRESS_<chainId>)"
  exit 1
fi
if [[ -z "$TOKEN_B" ]]; then
  echo "Set TOKEN_B (or CUSDC_ADDRESS)"
  exit 1
fi
RPC_URL="${RPC_URL:-${POLYGON_MAINNET_RPC:-${ETHEREUM_MAINNET_RPC:-}}}"
if [[ -z "$RPC_URL" ]]; then
  echo "Set RPC_URL (or POLYGON_MAINNET_RPC / ETHEREUM_MAINNET_RPC)"
  exit 1
fi

echo "Creating Uniswap V3 pool: tokenA=$TOKEN_A tokenB=$TOKEN_B fee=$FEE"
echo "Factory=$UNISWAP_V3_FACTORY RPC=$RPC_URL"
POOL=$(cast call "$UNISWAP_V3_FACTORY" "getPool(address,address,uint24)(address)" "$TOKEN_A" "$TOKEN_B" "$FEE" --rpc-url "$RPC_URL" 2>/dev/null || true)
if [[ -n "$POOL" ]] && [[ "$POOL" != "0x0000000000000000000000000000000000000000" ]]; then
  echo "Pool already exists: $POOL"
  exit 0
fi
cast send "$UNISWAP_V3_FACTORY" "createPool(address,address,uint24)" "$TOKEN_A" "$TOKEN_B" "$FEE" \
  --rpc-url "$RPC_URL" \
  --private-key "${PRIVATE_KEY:?PRIVATE_KEY required}"
POOL=$(cast call "$UNISWAP_V3_FACTORY" "getPool(address,address,uint24)(address)" "$TOKEN_A" "$TOKEN_B" "$FEE" --rpc-url "$RPC_URL")
echo "Pool created: $POOL"
echo "Next: initialize the pool with sqrtPriceX96 and add liquidity via Uniswap UI or NonfungiblePositionManager."
