#!/usr/bin/env bash
# Run PMM phase (DeployDODOPMMIntegration) and optionally DeployPrivatePoolRegistryAndPools.
# Requires: .env with DODO_VENDING_MACHINE_ADDRESS, COMPLIANT_USDT_ADDRESS, COMPLIANT_USDC_ADDRESS,
#           OFFICIAL_USDT_ADDRESS, OFFICIAL_USDC_ADDRESS (see docs/integration/DODO_PMM_INTEGRATION.md).
# For XAU pools: set DODOPMM_INTEGRATION_ADDRESS and XAU_ADDRESS_138 after the first run.
# Usage: ./scripts/deployment/run-pmm-and-pools.sh

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

source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
load_deployment_env

# Reject unset, empty, or zero address (0x0 or 0x000...)
if [[ -z "${DODO_VENDING_MACHINE_ADDRESS:-}" ]]; then
  echo "DODO_VENDING_MACHINE_ADDRESS not set. Set it to the DODO DVM factory on Chain 138 (see docs/deployment/ALL_MAINNETS_DEPLOYMENT_RUNBOOK.md)."
  exit 1
fi
# Reject 0x0 or 0x000...000 (zero address)
if [[ "$(echo "${DODO_VENDING_MACHINE_ADDRESS}" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')" =~ ^0x0+$ ]]; then
  echo "DODO_VENDING_MACHINE_ADDRESS is zero. Set it to the DVM factory on Chain 138."
  exit 1
fi

echo "=== Deploy DODOPMMIntegration (Chain 138) ==="
bash "$SCRIPT_DIR/deploy-all-mainnets-with-mapper-oracle-pmm.sh" pmm

if [[ -n "${DODO_PMM_INTEGRATION:-}" || -n "${DODOPMM_INTEGRATION_ADDRESS:-}" ]]; then
  addr="${DODO_PMM_INTEGRATION:-$DODOPMM_INTEGRATION_ADDRESS}"
  echo ""
  echo "DODOPMMIntegration at $addr. Create cUSDT/USDT and cUSDC/USDC pools via createCUSDTUSDTPool/createCUSDCUSDCPool (see docs/integration/DODO_PMM_INTEGRATION.md)."
  if [[ -n "${XAU_ADDRESS_138:-}" ]]; then
    echo "=== Deploy PrivatePoolRegistry and XAU-anchored pools ==="
    forge script script/dex/DeployPrivatePoolRegistryAndPools.s.sol:DeployPrivatePoolRegistryAndPools \
      --rpc-url "$RPC_URL_138" --broadcast --private-key "$PRIVATE_KEY" \
      --with-gas-price "${GAS_PRICE_138:-1000000000}" --legacy -vvv || true
  else
    echo "Set XAU_ADDRESS_138 and DODOPMM_INTEGRATION_ADDRESS in .env to deploy XAU-anchored pools (DeployPrivatePoolRegistryAndPools)."
  fi
else
  echo "Set DODO_PMM_INTEGRATION or DODOPMM_INTEGRATION_ADDRESS in .env after deploy, then re-run for pool creation."
fi
