#!/usr/bin/env bash
# Deployments — Chain 138 and multichain (nothing optional nor future; these are planned deployments).
# Usage:
#   ./scripts/deployment/deploy-optional-future-all.sh           # run all phases
#   ./scripts/deployment/deploy-optional-future-all.sh --dry-run # print only
#   ./scripts/deployment/deploy-optional-future-all.sh --phases 1,3,5 # run phases 1,3,5
#
# Requires: .env with PRIVATE_KEY, RPC_URL_138. Chain 138: --with-gas-price (default 2 gwei).

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

if [ -f .env ]; then
  set -a
  source .env
  set +a
fi

RPC="${RPC_URL_138:-http://192.168.11.211:8545}"
# Default 2 gwei to reduce "Replacement transaction underpriced"; override with GAS_PRICE_138.
GAS_PRICE="${GAS_PRICE_138:-2000000000}"
DRY_RUN=""
PHASES=""   # comma-separated, e.g. 1,3,5

while [ $# -gt 0 ]; do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    --phases)
      shift
      [ $# -gt 0 ] && PHASES="$1"
      ;;
  esac
  shift
done

if [ -z "${PRIVATE_KEY:-}" ]; then
  echo "ERROR: PRIVATE_KEY not set in .env"
  exit 1
fi

# run_phase num name skip_var cmd [required_var]
# If required_var is set and skip_var is not set, requires that required_var is non-empty in env; else skips with message.
run_phase() {
  local num="$1"
  local name="$2"
  local skip_var="$3"
  local cmd="$4"
  local required_var="${5:-}"

  if [ -n "$PHASES" ]; then
    if ! echo ",$PHASES," | grep -q ",$num,"; then
      return 0
    fi
  fi

  if [ -n "$skip_var" ]; then
    local val=""
    eval "val=\"\${${skip_var}:-}\""
    if [ -n "$val" ]; then
      echo "[Phase $num] $name — SKIP (${skip_var} already set)"
      return 0
    fi
  fi

  if [ -n "$required_var" ]; then
    local req_val=""
    eval "req_val=\"\${${required_var}:-}\""
    if [ -z "$req_val" ]; then
      echo "[Phase $num] $name — SKIP (set ${required_var} in .env to run; or set ${skip_var} to skip)"
      return 0
    fi
  fi

  echo "[Phase $num] $name — RUNNING"
  if [ -n "$DRY_RUN" ]; then
    echo "  would run: $(echo "$cmd" | sed 's/--private-key "[^"]*"/--private-key ***REDACTED***/g')"
    return 0
  fi
  eval "$cmd" || { echo "Phase $num failed."; exit 1; }
  echo "[Phase $num] $name — DONE"
}

echo "============================================"
echo "Deployments — Chain 138 and multichain"
echo "RPC: $RPC"
echo "Gas price: $GAS_PRICE wei"
echo "============================================"
echo ""

# Phase 1: CREATE2 / Deterministic core
run_phase 1 "Deterministic core (DeployDeterministicCore)" "CREATE2_FACTORY" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/deploy/DeployDeterministicCore.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 2: Vault system
run_phase 2 "Vault system (DeployVaultSystem)" "VAULT_FACTORY" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/deploy/vault/DeployVaultSystem.s.sol:DeployVaultSystem --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 3: Reserve system (requires TOKEN_FACTORY)
run_phase 3 "Reserve system (DeployReserveSystem)" "RESERVE_SYSTEM" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/reserve/DeployReserveSystem.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 4: Reserve Keeper (requires ORACLE_PRICE_FEED unless RESERVE_KEEPER already set)
run_phase 4 "Reserve Keeper (DeployKeeper)" "RESERVE_KEEPER" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/reserve/DeployKeeper.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\"" \
  "ORACLE_PRICE_FEED"

# Phase 5: PaymentChannelManager + GenericStateChannelManager
run_phase 5a "PaymentChannelManager" "PAYMENT_CHANNEL_MANAGER" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/DeployPaymentChannelManager.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

run_phase 5b "GenericStateChannelManager" "GENERIC_STATE_CHANNEL_MANAGER" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/DeployGenericStateChannelManager.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 6: Trustless bridge (Lockbox138 on Chain 138)
run_phase 6 "Trustless bridge (Lockbox138)" "LOCKBOX_138" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 7: DODO / Swap (requires DODO_VENDING_MACHINE_ADDRESS, COMPLIANT_USDT_ADDRESS, COMPLIANT_USDC_ADDRESS)
run_phase 7 "DODO PMM Integration" "DODOPMM_INTEGRATION_ADDRESS" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/dex/DeployDODOPMMIntegration.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\"" \
  "DODO_VENDING_MACHINE_ADDRESS"

# Phase 8: eMoney (Chain 138)
run_phase 8 "eMoney (DeployChain138)" "TOKEN_FACTORY_138" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/emoney/DeployChain138.s.sol:DeployChain138 --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 9: Smart accounts (informational — actual deploy from ERC-4337 impl)
run_phase 9 "Smart accounts kit (informational)" "" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/smart-accounts/DeploySmartAccountsKit.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

echo ""
echo "============================================"
echo "Deployments finished."
echo "Update .env with new addresses."
echo "DeployAll (mainnet/multichain): run script/DeployAll.s.sol per chain."
echo "Trustless bridge Mainnet: run DeployTrustlessBridge with MAINNET_RPC."
echo "See docs/03-deployment/OPTIONAL_FUTURE_DEPLOYMENTS_RUNBOOK.md"
echo "============================================"
