#!/usr/bin/env bash
# Setup script for DODO PMM pools
# Creates and configures DODO pools for cUSDT/USDT and cUSDC/USDC pairs

set -euo pipefail

hex_to_addr() {
    local value="${1#0x}"
    [[ ${#value} -ge 40 ]] || return 1
    printf '0x%s\n' "${value: -40}"
}

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

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"
elif [ -f "$PROJECT_ROOT/.env" ]; then
    set -a && source "$PROJECT_ROOT/.env" && set +a
fi

RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
RPC_URL="${RPC_URL%$'\r'}"
RPC_URL="${RPC_URL%$'\n'}"
INTEGRATION_ADDRESS="${DODO_PMM_INTEGRATION_ADDRESS:-}"
COMPLIANT_USDT="${COMPLIANT_USDT_ADDRESS:-0x93E66202A11B1772E55407B32B44e5Cd8eda7f22}"
COMPLIANT_USDC="${COMPLIANT_USDC_ADDRESS:-0xf22258f57794CC8E06237084b353Ab30fFfa640b}"
OFFICIAL_USDT="${OFFICIAL_USDT_ADDRESS:-0x004b63A7B5b0E06f6bB6adb4a5F9f590BF3182D1}"
OFFICIAL_USDC="${OFFICIAL_USDC_ADDRESS:-0x71D6687F38b93CCad569Fa6352c876eea967201b}"

if [ -z "$INTEGRATION_ADDRESS" ]; then
    log_error "DODO_PMM_INTEGRATION_ADDRESS not set"
    exit 1
fi

if [ -z "$PRIVATE_KEY" ]; then
    log_error "PRIVATE_KEY not set"
    exit 1
fi

# Pool parameters (can be configured)
LP_FEE_RATE="${LP_FEE_RATE:-3}"  # 0.03% = 3 basis points
INITIAL_PRICE="${INITIAL_PRICE:-1000000000000000000}"  # 1e18 = $1
K_FACTOR="${K_FACTOR:-500000000000000000}"  # 0.5e18 = 50%
ENABLE_TWAP="${ENABLE_TWAP:-true}"

log_info "========================================="
log_info "DODO PMM Pool Setup"
log_info "========================================="
log_info ""
log_info "Integration Address: $INTEGRATION_ADDRESS"
log_info "Compliant USDT: $COMPLIANT_USDT"
log_info "Compliant USDC: $COMPLIANT_USDC"
log_info "Official USDT: $OFFICIAL_USDT"
log_info "Official USDC: $OFFICIAL_USDC"
log_info "RPC URL: $RPC_URL"
log_info ""
log_info "Pool Parameters:"
log_info "  LP Fee Rate: $LP_FEE_RATE basis points"
log_info "  Initial Price: $INITIAL_PRICE (1e18 = $1)"
log_info "  K Factor: $K_FACTOR (slippage)"
log_info "  TWAP Enabled: $ENABLE_TWAP"
log_info ""

# Check if pools already exist
USDT_POOL=$(cast call "$INTEGRATION_ADDRESS" "pools(address,address)" "$COMPLIANT_USDT" "$OFFICIAL_USDT" --rpc-url "$RPC_URL" 2>/dev/null | while read -r raw; do hex_to_addr "$raw" 2>/dev/null || true; done)
USDC_POOL=$(cast call "$INTEGRATION_ADDRESS" "pools(address,address)" "$COMPLIANT_USDC" "$OFFICIAL_USDC" --rpc-url "$RPC_URL" 2>/dev/null | while read -r raw; do hex_to_addr "$raw" 2>/dev/null || true; done)

if [ "$USDT_POOL" != "0x0000000000000000000000000000000000000000" ] && [ -n "$USDT_POOL" ]; then
    log_warn "USDT pool already exists: $USDT_POOL"
else
    log_info "Creating cUSDT/USDT pool..."
    TWAP_VALUE=$([ "$ENABLE_TWAP" = "true" ] && echo "true" || echo "false")
    
    cast send "$INTEGRATION_ADDRESS" \
      "createCUSDTUSDTPool(uint256,uint256,uint256,bool)" \
      "$LP_FEE_RATE" \
      "$INITIAL_PRICE" \
      "$K_FACTOR" \
      "$TWAP_VALUE" \
      --rpc-url "$RPC_URL" \
      --private-key "$PRIVATE_KEY" \
      --gas-price 20000000000 \
      --legacy \
      -vv
    
    USDT_POOL=$(cast call "$INTEGRATION_ADDRESS" "pools(address,address)" "$COMPLIANT_USDT" "$OFFICIAL_USDT" --rpc-url "$RPC_URL" 2>/dev/null | while read -r raw; do hex_to_addr "$raw" 2>/dev/null || true; done)
    log_success "USDT pool created: $USDT_POOL"
fi

if [ "$USDC_POOL" != "0x0000000000000000000000000000000000000000" ] && [ -n "$USDC_POOL" ]; then
    log_warn "USDC pool already exists: $USDC_POOL"
else
    log_info "Creating cUSDC/USDC pool..."
    TWAP_VALUE=$([ "$ENABLE_TWAP" = "true" ] && echo "true" || echo "false")
    
    cast send "$INTEGRATION_ADDRESS" \
      "createCUSDCUSDCPool(uint256,uint256,uint256,bool)" \
      "$LP_FEE_RATE" \
      "$INITIAL_PRICE" \
      "$K_FACTOR" \
      "$TWAP_VALUE" \
      --rpc-url "$RPC_URL" \
      --private-key "$PRIVATE_KEY" \
      --gas-price 20000000000 \
      --legacy \
      -vv
    
    USDC_POOL=$(cast call "$INTEGRATION_ADDRESS" "pools(address,address)" "$COMPLIANT_USDC" "$OFFICIAL_USDC" --rpc-url "$RPC_URL" 2>/dev/null | while read -r raw; do hex_to_addr "$raw" 2>/dev/null || true; done)
    log_success "USDC pool created: $USDC_POOL"
fi

log_info ""
log_info "Pool addresses saved to environment:"
log_info "DODO_USDT_POOL=$USDT_POOL"
log_info "DODO_USDC_POOL=$USDC_POOL"
log_info ""
log_info "Next steps:"
log_info "1. Add liquidity to pools using addLiquidity()"
log_info "2. Monitor pool reserves and prices"
log_info "3. Enable trading and arbitrage"
log_info ""
log_info "For PMM coverage of all tokens (chain 138/651940), use:"
log_info "  scripts/create-all-dodo-pools-from-token-api.sh"
log_info "  (requires TOKEN_AGGREGATION_API_URL, CHAIN_ID, QUOTE_TOKEN_ADDRESS, DODO_PMM_INTEGRATION_ADDRESS, ENHANCED_SWAP_ROUTER_ADDRESS, UNIVERSAL_ASSET_REGISTRY_ADDRESS)"
