#!/usr/bin/env bash
# Run all deployment tasks in parallel where possible.
# Respects dependency order. Requires .env with PRIVATE_KEY, RPC URLs.
# Usage: ./scripts/deployment/run-all-deployments-parallel.sh [chain]
# chain: chain138 (default), cronos, mainnet

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

CHAIN="${1:-chain138}"

case "$CHAIN" in
  chain138) RPC="${RPC_URL_138:-$CHAIN138_RPC_URL}"; CHAIN_ID=138 ;;
  cronos)   RPC="${CRONOS_RPC_URL:-https://evm.cronos.org}"; CHAIN_ID=25 ;;
  mainnet)  RPC="${ETHEREUM_MAINNET_RPC}"; CHAIN_ID=1 ;;
  *) echo "Unknown chain: $CHAIN"; exit 1 ;;
esac

echo "=== Parallel Deployment: $CHAIN (chain $CHAIN_ID) ==="
echo "RPC: $RPC"
echo ""

# Phase 1: Independent deployments (run in parallel)
echo "Phase 1: Core (parallel)..."
(
  forge script script/DeployMulticall.s.sol:DeployMulticall --rpc-url "$RPC" --broadcast &
  forge script script/DeployOracle.s.sol:DeployOracle --rpc-url "$RPC" --broadcast &
  wait
) 2>&1 | tee /tmp/deploy-phase1.log || true

# Phase 2: Depends on Phase 1 (CREATE2 if needed for deterministic)
echo ""
echo "Phase 2: CREATE2Factory (if not exists)..."
if [ -z "${CREATE2_FACTORY:-}" ] || [ "$CREATE2_FACTORY" = "0x0000000000000000000000000000000000000000" ]; then
  forge script script/Deploy.s.sol:Deploy --rpc-url "$RPC" --broadcast 2>&1 || true
fi

# Phase 3: Token/Reserve (require TOKEN_FACTORY etc.)
echo ""
echo "Phase 3: Token systems (require existing deps)..."
# DeployChain138, DeployISO4217WSystem, etc. — run if deps present

echo ""
echo "Deployment batch complete. Check logs for any failures."
echo "Note: Chain 138 may show 'Replacement transaction underpriced' if mempool has stuck tx."
