#!/usr/bin/env bash
set -euo pipefail

MNEMONIC_FILE=/workspace/onchain/.secret.local
ANVIL_STATE_DIR=/home/foundry/.foundry/anvil/tmp

# Cleanup ALL old state snapshots on start + periodic cleanup in background
# Anvil fork mode generates thousands of JSON snapshots that fill disk fast
if [[ -d "$ANVIL_STATE_DIR" ]]; then
  echo "[anvil] Cleaning up all state snapshots..."
  rm -rf "$ANVIL_STATE_DIR"/* 2>/dev/null || true
fi

# Background cleanup: every 6 hours, delete snapshots older than 1 hour
(while true; do
  sleep 21600
  if [[ -d "$ANVIL_STATE_DIR" ]]; then
    find "$ANVIL_STATE_DIR" -type f -name "*.json" -mmin +60 -delete 2>/dev/null || true
    find "$ANVIL_STATE_DIR" -type d -empty -delete 2>/dev/null || true
  fi
done) &

ANVIL_CMD=(anvil --fork-url "${FORK_URL:-https://sepolia.base.org}" --chain-id 31337 --block-time 1 --host 0.0.0.0 --port 8545 --threads 4 --timeout 2000 --retries 2 --fork-retry-backoff 100 --steps-tracing --no-storage-caching)

if [[ -f "$MNEMONIC_FILE" ]]; then
  MNEMONIC="$(tr -d '\n\r' <"$MNEMONIC_FILE")"
  if [[ -n "$MNEMONIC" ]]; then
    ANVIL_CMD+=(--mnemonic "$MNEMONIC")
  fi
fi

exec "${ANVIL_CMD[@]}"
