#!/usr/bin/env bash
# Fix nonce mismatch by clearing broadcast/cache so Forge uses fresh on-chain nonce.
# Usage: ./scripts/deployment/fix-nonce-and-retry.sh [--chain cronos] [--script <path>]
#        ./scripts/deployment/fix-nonce-and-retry.sh cronos   # positional still supported
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

CHAIN=""
SCRIPT=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --chain) CHAIN="${2:-cronos}"; shift 2 ;;
    --script) SCRIPT="${2:-script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge}"; shift 2 ;;
    *) if [[ -z "$CHAIN" ]]; then CHAIN="$1"; elif [[ -z "$SCRIPT" ]]; then SCRIPT="$1"; fi; shift ;;
  esac
done
CHAIN="${CHAIN:-cronos}"
SCRIPT="${SCRIPT:-script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge}"

case "$(echo "$CHAIN" | tr '[:upper:]' '[:lower:]')" in
  cronos)   RPC="${CRONOS_RPC_URL:-https://evm.cronos.org}"; CHAIN_ID=25 ;;
  chain138) RPC="${RPC_URL_138:-${CHAIN_138_RPC_URL:-}}"; CHAIN_ID=138 ;;
  bsc)      RPC="${BSC_RPC_URL:-}"; CHAIN_ID=56 ;;
  polygon)  RPC="${POLYGON_MAINNET_RPC:-}"; CHAIN_ID=137 ;;
  base)     RPC="${BASE_MAINNET_RPC:-}"; CHAIN_ID=8453 ;;
  optimism) RPC="${OPTIMISM_MAINNET_RPC:-}"; CHAIN_ID=10 ;;
  arbitrum) RPC="${ARBITRUM_MAINNET_RPC:-}"; CHAIN_ID=42161 ;;
  avalanche) RPC="${AVALANCHE_RPC_URL:-}"; CHAIN_ID=43114 ;;
  gnosis)   RPC="${GNOSIS_MAINNET_RPC:-}"; CHAIN_ID=100 ;;
  *) echo "Unknown chain: $CHAIN (use: cronos, chain138, bsc, polygon, base, optimism, arbitrum, avalanche, gnosis)"; exit 1 ;;
esac
if [[ -z "$RPC" ]]; then echo "RPC not set for $CHAIN"; exit 1; fi

DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || true)
NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC" 2>/dev/null || echo "0")
echo "Deployer: $DEPLOYER"
echo "Current on-chain nonce: $NONCE"
echo "RPC: $RPC"
echo ""

# Clear broadcast cache so Forge fetches fresh nonce
CACHE_DIR="$PROJECT_ROOT/cache"
BROADCAST_DIR="$PROJECT_ROOT/broadcast"
SCRIPT_PATH="${SCRIPT%%:*}"
rm -rf "$CACHE_DIR/$SCRIPT_PATH/$CHAIN_ID" 2>/dev/null || true
rm -rf "$BROADCAST_DIR/$SCRIPT_PATH/$CHAIN_ID" 2>/dev/null || true
echo "Cleared cache for $SCRIPT_PATH on chain $CHAIN_ID"

echo ""
echo "Run deployment (use --slow to avoid nonce gaps):"
echo "  forge script $SCRIPT --rpc-url \"$RPC\" --chain-id $CHAIN_ID --broadcast --private-key \"\$PRIVATE_KEY\" --slow"
echo ""
