#!/usr/bin/env bash

# Start Local Anvil Testnet
# This script starts a local Anvil testnet for testing contract deployments

set -e


# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
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

log_info "=== Starting Local Anvil Testnet ==="

# Check if Anvil is installed
if ! command -v anvil &> /dev/null; then
    log_error "Error: Anvil is not installed"
    echo "Please install Foundry: https://book.getfoundry.sh/getting-started/installation"
    exit 1
fi

# Check if Anvil is already running
if lsof -Pi :8545 -sTCP:LISTEN -t >/dev/null ; then
    log_warn "Anvil is already running on port 8545"
    echo "Using existing Anvil instance"
    RPC_URL="http://localhost:8545"
else
    log_warn "Starting Anvil testnet..."
    
    # Chain ID 138 (same as production)
    CHAIN_ID=${CHAIN_ID:-138}
    PORT=${PORT:-8545}
    
    # Start Anvil in background
    anvil --chain-id "$CHAIN_ID" --port "$PORT" \
        --host 0.0.0.0 \
        --block-time 2 \
        --gas-limit 30000000 \
        > /tmp/anvil.log 2>&1 &
    
    ANVIL_PID=$!
    echo "Anvil started with PID: $ANVIL_PID"
    echo "PID saved to: /tmp/anvil.pid"
    echo $ANVIL_PID > /tmp/anvil.pid
    
    # Wait for Anvil to start
    sleep 3
    
    # Verify Anvil is running
    if ! curl -s -X POST "http://localhost:${PORT}" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' > /dev/null 2>&1; then
        log_error "Error: Anvil failed to start"
        echo "Check logs: /tmp/anvil.log"
        exit 1
    fi
    
    RPC_URL="http://localhost:${PORT}"
    log_success "✅ Anvil testnet started on ${RPC_URL}"
fi

# Update .env with RPC_URL
if [ -f .env ]; then
    if grep -q "^RPC_URL=" .env; then
        sed -i "s|^RPC_URL=.*|RPC_URL=${RPC_URL}|" .env
    else
        echo "RPC_URL=${RPC_URL}" >> .env
    fi
    log_success "✅ Updated .env: RPC_URL=${RPC_URL}"
else
    log_warn "Warning: .env file not found"
    echo "Please create .env file and set RPC_URL=${RPC_URL}"
fi

# Get accounts from Anvil
log_info "=== Anvil Test Accounts ==="
ANVIL_ACCOUNTS=$(cast wallet address --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 2>/dev/null || echo "")
if [ -n "$ANVIL_ACCOUNTS" ]; then
    log_success "Default account: ${ANVIL_ACCOUNTS}"
    log_warn "Private key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
    log_warn "Note: This account is prefunded with 10000 ETH on Anvil"
fi

# Display Anvil info
log_info "=== Anvil Information ==="
echo "Chain ID: $CHAIN_ID"
echo "RPC URL: $RPC_URL"
echo "Port: $PORT"
log_success "✅ Local testnet is ready"
echo "To stop Anvil, run:"
echo "  kill \$(cat /tmp/anvil.pid)"
echo "Or use:"
echo "  pkill -f anvil"
echo "To deploy contracts, run:"
echo "  ./scripts/deployment/deploy-all-ordered.sh"

