#!/usr/bin/env bash
# Mint cUSDT and cUSDC to the deployer for adding PMM liquidity on Chain 138.
# Deployer must be owner of both token contracts. After minting, run add-liquidity (see step 2).
#
# Usage:
#   cd smom-dbis-138 && ./scripts/mint-for-liquidity.sh
#   MINT_CUSDT_AMOUNT=2000000 MINT_CUSDC_AMOUNT=2000000 ./scripts/mint-for-liquidity.sh   # 2M each
#   ./scripts/mint-for-liquidity.sh --add-liquidity   # mint then run AddLiquidityPMMPoolsChain138
#
# Env (in smom-dbis-138/.env): PRIVATE_KEY, RPC_URL_138 (or RPC_URL).
# Optional: MINT_CUSDT_AMOUNT, MINT_CUSDC_AMOUNT (human units, default 1000000 = 1M each).
# For --add-liquidity: ADD_LIQUIDITY_BASE_AMOUNT, ADD_LIQUIDITY_QUOTE_AMOUNT (base units, 6 decimals).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
source "$PROJECT_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

RPC="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
CUSDT="${COMPLIANT_USDT:-0x93E66202A11B1772E55407B32B44e5Cd8eda7f22}"
CUSDC="${COMPLIANT_USDC:-0xf22258f57794CC8E06237084b353Ab30fFfa640b}"
DECIMALS=6

# Amounts in human units (e.g. 1000000 = 1M tokens)
MINT_CUSDT="${MINT_CUSDT_AMOUNT:-1000000}"
MINT_CUSDC="${MINT_CUSDC_AMOUNT:-1000000}"

RUN_ADD_LIQUIDITY=false
for a in "$@"; do [[ "$a" == "--add-liquidity" ]] && RUN_ADD_LIQUIDITY=true && break; done

if [[ -z "${PRIVATE_KEY:-}" ]]; then
  echo "ERROR: PRIVATE_KEY not set. Source smom-dbis-138/.env"
  exit 1
fi

DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || true)
if [[ -z "$DEPLOYER" ]]; then
  echo "ERROR: Could not derive address from PRIVATE_KEY"
  exit 1
fi

# Base units (6 decimals)
BASE_CUSDT=$((MINT_CUSDT * 10**DECIMALS))
BASE_CUSDC=$((MINT_CUSDC * 10**DECIMALS))

echo "=== Mint cUSDT / cUSDC for liquidity (Chain 138) ==="
echo "  Deployer: $DEPLOYER"
echo "  RPC:      $RPC"
echo "  cUSDT:    $MINT_CUSDT tokens ($BASE_CUSDT base units) -> $CUSDT"
echo "  cUSDC:    $MINT_CUSDC tokens ($BASE_CUSDC base units) -> $CUSDC"
echo ""

mint_one() {
  local addr="$1"
  local name="$2"
  local amount_base="$3"
  echo "Minting $name to deployer..."
  OWNER=$(cast call "$addr" "owner()(address)" --rpc-url "$RPC" 2>/dev/null || echo "")
  if [[ -n "$OWNER" && "$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')" != "$(echo "$DEPLOYER" | tr '[:upper:]' '[:lower:]')" ]]; then
    echo "  SKIP $name: contract owner is $OWNER, deployer is $DEPLOYER (only owner can mint)"
    return 0
  fi
  GAS_PRICE="${GAS_PRICE_138:-1000000000}"
  if cast send "$addr" "mint(address,uint256)" "$DEPLOYER" "$amount_base" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 100000 --gas-price "$GAS_PRICE"; then
    echo "  OK $name"
  else
    echo "  FAIL $name"
    return 1
  fi
}

mint_one "$CUSDT" "cUSDT" "$BASE_CUSDT"
mint_one "$CUSDC" "cUSDC" "$BASE_CUSDC"

echo ""
echo "Mint done. Deployer balances:"
B1=$(cast call "$CUSDT" "balanceOf(address)(uint256)" "$DEPLOYER" --rpc-url "$RPC" 2>/dev/null || echo "?")
B2=$(cast call "$CUSDC" "balanceOf(address)(uint256)" "$DEPLOYER" --rpc-url "$RPC" 2>/dev/null || echo "?")
echo "  cUSDT: $B1"
echo "  cUSDC: $B2"
echo ""

if [[ "$RUN_ADD_LIQUIDITY" == true ]]; then
  if [[ -z "${ADD_LIQUIDITY_BASE_AMOUNT:-}" || -z "${ADD_LIQUIDITY_QUOTE_AMOUNT:-}" ]]; then
    # Default: use half of what we just minted (so we add liquidity for the cUSDT/cUSDC pool)
    ADD_LIQUIDITY_BASE_AMOUNT=${ADD_LIQUIDITY_BASE_AMOUNT:-$((BASE_CUSDT / 2))}
    ADD_LIQUIDITY_QUOTE_AMOUNT=${ADD_LIQUIDITY_QUOTE_AMOUNT:-$((BASE_CUSDC / 2))}
    echo "Using default add-liquidity amounts (half of minted): base=$ADD_LIQUIDITY_BASE_AMOUNT quote=$ADD_LIQUIDITY_QUOTE_AMOUNT"
  fi
  export ADD_LIQUIDITY_BASE_AMOUNT ADD_LIQUIDITY_QUOTE_AMOUNT
  # Default pool addresses (Chain 138) if not in .env
  export POOL_CUSDTCUSDC="${POOL_CUSDTCUSDC:-0x9e89bAe009adf128782E19e8341996c596ac40dC}"
  export POOL_CUSDTUSDT="${POOL_CUSDTUSDT:-0x866Cb44b59303d8dc5f4F9E3E7A8e8b0bf238d66}"
  export POOL_CUSDCUSDC="${POOL_CUSDCUSDC:-0xc39B7D0F40838cbFb54649d327f49a6DAC964062}"
  export POOL_CUSDTWETH="${POOL_CUSDTWETH:-0xaE38a008Ba4Dbf8D9F141D03e9dC8f7Dbe0ce17c}"
  export POOL_CUSDCWETH="${POOL_CUSDCWETH:-0xAAE68830a55767722618E869882c6Ed064Cc1eb2}"
  export POOL_CEURTWETH="${POOL_CEURTWETH:-0x4a64c886cedF00db42ea5B946D6b304121ad9529}"
  if [[ -n "${DODO_PMM_INTEGRATION:-}" || -n "${DODO_PMM_INTEGRATION_ADDRESS:-}" ]]; then
    # Use pending nonce so broadcast does not get -32001 "Nonce too low" (mints just used N and N+1)
    NEXT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC" --block pending 2>/dev/null || true)
    [[ -n "$NEXT_NONCE" && "$NEXT_NONCE" =~ ^[0-9]+$ ]] && export NEXT_NONCE || unset -v NEXT_NONCE
    echo "Running AddLiquidityPMMPoolsChain138..."
    forge script script/dex/AddLiquidityPMMPoolsChain138.s.sol:AddLiquidityPMMPoolsChain138 \
      --rpc-url "$RPC" --broadcast --private-key "$PRIVATE_KEY" --with-gas-price 1000000000 --gas-estimate-multiplier 150
    echo "Add-liquidity done."
  else
    echo "Set DODO_PMM_INTEGRATION (or DODO_PMM_INTEGRATION_ADDRESS) and POOL_* in .env, then run:"
    echo "  forge script script/dex/AddLiquidityPMMPoolsChain138.s.sol:AddLiquidityPMMPoolsChain138 --rpc-url \$RPC_URL_138 --broadcast --private-key \$PRIVATE_KEY"
  fi
else
  echo "To add liquidity next: set ADD_LIQUIDITY_BASE_AMOUNT and ADD_LIQUIDITY_QUOTE_AMOUNT (base units, 6 decimals),"
  echo "POOL_CUSDTCUSDC (and optional POOL_CUSDTUSDT, POOL_CUSDCUSDC, POOL_CUSDTWETH, POOL_CUSDCWETH, POOL_CEURTWETH),"
  echo "DODO_PMM_INTEGRATION in .env, then run:"
  echo "  forge script script/dex/AddLiquidityPMMPoolsChain138.s.sol:AddLiquidityPMMPoolsChain138 --rpc-url \$RPC_URL_138 --broadcast --private-key \$PRIVATE_KEY"
  echo "Or run this script with --add-liquidity to mint and add in one go (uses half of minted for cUSDT/cUSDC pool)."
fi
