#!/usr/bin/env bash
# Phased deployment for Chain 138: run each phase in order.
# Break-up of "deploy all" into discrete steps; skip phases that are already deployed (env set).
#
# Usage:
#   ./scripts/deployment/deploy-all-phases.sh              # run all phases (skip when env indicates done)
#   ./scripts/deployment/deploy-all-phases.sh --all        # run every phase (no skip)
#   ./scripts/deployment/deploy-all-phases.sh --phase 5    # run only phase 5
#   ./scripts/deployment/deploy-all-phases.sh --dry-run    # print what would run
#
# Requires: .env with PRIVATE_KEY, RPC_URL_138 (Chain 138 Core). Uses --with-gas-price 1000000000 for Chain 138.

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

RPC="${RPC_URL_138:-http://192.168.11.211:8545}"
GAS_PRICE="${GAS_PRICE_138:-1000000000}"
DRY_RUN=""
RUN_ALL=""   # if set, do not skip any phase
PHASE_ONLY="" # if set, run only this phase number (e.g. 5)

while [ $# -gt 0 ]; do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    --all)     RUN_ALL=1 ;;
    --phase)
      shift
      [ $# -gt 0 ] && PHASE_ONLY="$1"
      ;;
  esac
  shift
done

if ! require_private_key_env; then
  exit 1
fi

run_phase() {
  local num="$1"
  local name="$2"
  local skip_var="$3"   # optional: if set in env, skip (unless --all)
  local cmd="$4"
  if [ -n "$PHASE_ONLY" ] && [ "$PHASE_ONLY" != "$num" ]; then
    return 0
  fi
  if [ -n "$skip_var" ] && [ -z "$RUN_ALL" ]; then
    local val=""
    eval "val=\"\${${skip_var}:-}\""
    if [ -n "$val" ]; then
      echo "[Phase $num] $name — SKIP (${skip_var} already set)"
      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 "Chain 138 — Phased deployment"
echo "RPC: $RPC"
echo "Gas price: $GAS_PRICE wei"
echo "============================================"
echo ""

# Phase 1: Phased core (registry + governance)
run_phase 1 "Phased core (01_DeployCore)" "UNIVERSAL_ASSET_REGISTRY" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/deploy/01_DeployCore.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 2: Phased bridges (CCIP bridge + orchestrator)
run_phase 2 "Phased bridges (02_DeployBridges)" "UNIVERSAL_CCIP_BRIDGE" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/deploy/02_DeployBridges.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 3: Channel managers
run_phase 3 "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 3 "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 4: Deterministic core (CREATE2)
run_phase 4 "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 5: Vault system
run_phase 5 "Vault system (DeployVaultSystem)" "VAULT_FACTORY" \
  "bash \"$PROJECT_ROOT/scripts/forge/scope.sh\" script script/deploy/vault/DeployVaultSystem.s.sol --rpc-url \"$RPC\" --broadcast --private-key \"$PRIVATE_KEY\" --with-gas-price \"$GAS_PRICE\""

# Phase 6: Reserve system (requires TOKEN_FACTORY in .env)
run_phase 6 "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 7: Trustless bridge (Lockbox138 on Chain 138)
run_phase 7 "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\""

echo ""
echo "============================================"
echo "Phased deployment finished."
echo "Update .env with any new addresses and run setCCIPRouter on deterministic bridge if Phase 4 ran."
echo "============================================"
