#!/usr/bin/env bash
# Full parity: Mapper + Oracle on ALL bridge networks.
# Extends deploy-all-mainnets-with-mapper-oracle-pmm.sh with Celo, Wemix, and Oracle-on-all-chains.
# Usage: bash scripts/deployment/deploy-full-parity-all-chains.sh [phase] [--dry-run]
#   phase: mapper | oracle | bridges | all (default: all)
#   --dry-run  Print commands only
# Requires: .env with PRIVATE_KEY and per-chain RPC vars (GNOSIS_RPC, CELO_RPC, WEMIX_RPC, etc.)
# See: docs/07-ccip/FULL_PARITY_RUNBOOK.md

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# 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

[ -f "$SCRIPT_DIR/../lib/infura.sh" ] && source "$SCRIPT_DIR/../lib/infura.sh"

PHASE="${1:-all}"
DRY_RUN=false
for a in "$@"; do [[ "$a" == "--dry-run" ]] && DRY_RUN=true; done

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

ensure_rpc() {
  local rpc="$1"
  type ensure_infura_rpc_url &>/dev/null && [ -n "$rpc" ] && rpc=$(ensure_infura_rpc_url "$rpc")
  echo "$rpc"
}

run_or_echo() {
  if $DRY_RUN; then
    echo "  [DRY RUN] $*"
  else
    eval "$@" || echo -e "${RED}  Failed${NC}"
  fi
}

# --- Mapper: all chains including Celo, Wemix ---
run_mapper() {
  echo -e "${YELLOW}=== Full Parity: Mapper (AddressMapperEmpty) on ALL bridge chains ===${NC}"
  [ -z "${PRIVATE_KEY:-}" ] && { echo -e "${RED}PRIVATE_KEY not set${NC}"; return 1; }
  # RPC_VAR:CHAIN_ID — include Celo, Wemix
  local chains="ETHEREUM_MAINNET_RPC:1 BSC_RPC_URL:56 POLYGON_MAINNET_RPC:137 BASE_MAINNET_RPC:8453 ARBITRUM_MAINNET_RPC:42161 OPTIMISM_MAINNET_RPC:10 AVALANCHE_RPC_URL:43114 CRONOS_RPC_URL:25 GNOSIS_RPC:100 CELO_RPC:42220 WEMIX_RPC:1111"
  for entry in $chains; do
    local rpc_var="${entry%%:*}"; local chain_id="${entry#*:}"
    local rpc="${!rpc_var:-}"
    [ -z "$rpc" ] && echo "  Skip chain $chain_id ($rpc_var not set)" && continue
    rpc=$(ensure_rpc "$rpc")
    echo "  Deploying AddressMapperEmpty on chain $chain_id ($rpc_var)..."
    local gas_opts=""
    [ "$chain_id" = "138" ] && gas_opts="--with-gas-price ${GAS_PRICE_138:-1000000000} --legacy"
    run_or_echo "forge script script/DeployAddressMapperOtherChain.s.sol:DeployAddressMapperOtherChain --rpc-url \"$rpc\" --chain-id \"$chain_id\" --broadcast --private-key \"\$PRIVATE_KEY\" $gas_opts -vvv"
  done
  echo -e "${GREEN}Mapper phase done. Record addresses in config.${NC}"
}

# --- Oracle: all chains ---
run_oracle() {
  echo -e "${YELLOW}=== Full Parity: Oracle (Aggregator+Proxy) on ALL bridge chains ===${NC}"
  [ -z "${PRIVATE_KEY:-}" ] && { echo -e "${RED}PRIVATE_KEY not set${NC}"; return 1; }
  local chains="RPC_URL_138:138 ETHEREUM_MAINNET_RPC:1 BSC_RPC_URL:56 POLYGON_MAINNET_RPC:137 BASE_MAINNET_RPC:8453 ARBITRUM_MAINNET_RPC:42161 OPTIMISM_MAINNET_RPC:10 AVALANCHE_RPC_URL:43114 CRONOS_RPC_URL:25 GNOSIS_RPC:100 CELO_RPC:42220 WEMIX_RPC:1111"
  for entry in $chains; do
    local rpc_var="${entry%%:*}"; local chain_id="${entry#*:}"
    local rpc="${!rpc_var:-}"
    [ -z "$rpc" ] && echo "  Skip chain $chain_id ($rpc_var not set)" && continue
    rpc=$(ensure_rpc "$rpc")
    echo "  Deploying Oracle on chain $chain_id ($rpc_var)..."
    local gas_opts=""
    [ "$chain_id" = "138" ] && gas_opts="--with-gas-price ${GAS_PRICE_138:-1000000000} --legacy"
    run_or_echo "forge script script/DeployOracle.s.sol:DeployOracle --rpc-url \"$rpc\" --broadcast --private-key \"\$PRIVATE_KEY\" $gas_opts -vvv"
  done
  echo -e "${GREEN}Oracle phase done. Record Aggregator+Proxy addresses in config.${NC}"
}

# --- Bridges: Celo, Wemix (when funded) ---
run_bridges() {
  echo -e "${YELLOW}=== Full Parity: CCIP Bridges on Celo, Wemix ===${NC}"
  [ -z "${PRIVATE_KEY:-}" ] && { echo -e "${RED}PRIVATE_KEY not set${NC}"; return 1; }
  run_or_echo "bash scripts/deployment/deploy-bridges-config-ready-chains.sh celo"
  run_or_echo "bash scripts/deployment/deploy-bridges-config-ready-chains.sh wemix"
  echo "  Run complete-config-ready-chains.sh after recording bridge addresses in .env"
  echo -e "${GREEN}Bridges phase done.${NC}"
}

# --- Main ---
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Full Parity: Mapper, Oracle, AMB on All Bridge Networks${NC}"
echo -e "${GREEN}========================================${NC}"
echo "Phase: $PHASE  Dry-run: $DRY_RUN"
echo ""

case "$PHASE" in
  mapper)  run_mapper ;;
  oracle)  run_oracle ;;
  bridges) run_bridges ;;
  all)
    run_bridges
    run_mapper
    run_oracle
    ;;
  *) echo "Usage: $0 [mapper|oracle|bridges|all] [--dry-run]"; exit 1 ;;
esac

echo ""
echo -e "${GREEN}Done. Update .env and config with new addresses. See docs/07-ccip/FULL_PARITY_RUNBOOK.md${NC}"
