#!/usr/bin/env bash
# Deploy all contracts to Chain 138
# Usage: ./deploy-contracts-chain138.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if source project exists
if [ ! -d "$SOURCE_PROJECT" ]; then
    log_error "Source project not found at $SOURCE_PROJECT"
    exit 1
fi

# Check if .env exists in source project
if [ ! -f "$SOURCE_PROJECT/.env" ]; then
    log_warn ".env file not found in source project"
    log_info "Creating .env template..."
    cat > "$SOURCE_PROJECT/.env.template" <<EOF
# Chain 138 RPC
RPC_URL_138=http://192.168.11.250:8545

# Deployer
PRIVATE_KEY=<your-private-key>

# Oracle Configuration
ORACLE_PRICE_FEED=<oracle-price-feed-address>

# Reserve Configuration
RESERVE_ADMIN=<admin-address>
TOKEN_FACTORY=<token-factory-address>

# Keeper Configuration
KEEPER_ADDRESS=<keeper-address>
EOF
    log_warn "Please create .env file in $SOURCE_PROJECT with your configuration"
    exit 1
fi

# Load environment
cd "$SOURCE_PROJECT"
source .env 2>/dev/null || true

# Try HTTPS endpoint first, then fallback to HTTP
if curl -s -k -X POST https://rpc-core.d-bis.org -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null | grep -q '"result"'; then
    RPC_URL="https://rpc-core.d-bis.org"
    log_info "Using HTTPS RPC endpoint: $RPC_URL"
else
    RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
    log_info "Using HTTP RPC endpoint: $RPC_URL"
fi
PRIVATE_KEY="${PRIVATE_KEY:-}"

if [ -z "$PRIVATE_KEY" ]; then
    log_error "PRIVATE_KEY not set in .env file"
    exit 1
fi

# Ensure PRIVATE_KEY has 0x prefix
if [[ ! "$PRIVATE_KEY" =~ ^0x ]]; then
    export PRIVATE_KEY="0x$PRIVATE_KEY"
fi

log_info "========================================="
log_info "Chain 138 Contract Deployment"
log_info "========================================="
log_info ""
log_info "RPC URL: $RPC_URL"
log_info "Deployer: $(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo 'unknown')"
log_info ""

# Step 1: Verify network is ready
log_info "Step 1: Verifying network is ready..."

# Try using cast first, then fallback to curl
if command -v cast >/dev/null 2>&1; then
    BLOCK=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null | xargs printf "%d" 2>/dev/null || echo "0")
    CHAIN=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null | xargs printf "%d" 2>/dev/null || echo "0")
else
    # Fallback to curl if cast is not available
    RPC_RESPONSE=$(curl -s -X POST "$RPC_URL" \
        -H 'Content-Type: application/json' \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null)
    
    if echo "$RPC_RESPONSE" | grep -q '"result"'; then
        BLOCK=$(echo "$RPC_RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); print(int(data.get('result', '0x0'), 16))" 2>/dev/null || echo "0")
    else
        BLOCK="0"
    fi
    
    CHAIN_RESPONSE=$(curl -s -X POST "$RPC_URL" \
        -H 'Content-Type: application/json' \
        -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>/dev/null)
    
    if echo "$CHAIN_RESPONSE" | grep -q '"result"'; then
        CHAIN=$(echo "$CHAIN_RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); print(int(data.get('result', '0x0'), 16))" 2>/dev/null || echo "0")
    else
        CHAIN="0"
    fi
fi

if [ "$BLOCK" -eq 0 ]; then
    log_warn "Could not verify block number, but continuing with deployment..."
    log_warn "Network verification will be done during contract deployment"
    BLOCK="unknown"
    CHAIN="unknown"
else
    if [ "$CHAIN" -ne 138 ] && [ "$CHAIN" -ne 0 ]; then
        log_error "Chain ID mismatch. Expected 138, got $CHAIN"
        exit 1
    fi
    log_success "Network is ready!"
    log_info "   Current block: $BLOCK"
    log_info "   Chain ID: $CHAIN"
fi
log_info ""

# Step 2: Deploy contracts
log_info "========================================="
log_info "Step 2: Deploying Contracts"
log_info "========================================="
log_info ""

DEPLOYMENT_LOG="$PROJECT_ROOT/logs/contract-deployment-$(date +%Y%m%d-%H%M%S).log"
mkdir -p "$PROJECT_ROOT/logs"

# Deploy Oracle
log_info "2.1: Deploying Oracle..."
if forge script script/DeployOracle.s.sol:DeployOracle \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --legacy -vvv 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "Oracle|Aggregator|Proxy|deployed at:|Error" | head -5; then
    log_success "Oracle deployment completed"
else
    log_error "Oracle deployment failed"
fi

# Deploy CCIP Router
log_info ""
log_info "2.2: Deploying CCIP Router..."
if forge script script/DeployCCIPRouter.s.sol:DeployCCIPRouter \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --legacy -vvv 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "CCIP Router|deployed at:|Error" | head -3; then
    log_success "CCIP Router deployment completed"
else
    log_error "CCIP Router deployment failed"
fi

# Deploy CCIP Sender
log_info ""
log_info "2.3: Deploying CCIP Sender..."
if forge script script/DeployCCIPSender.s.sol:DeployCCIPSender \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --legacy -vvv 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "CCIPSender|deployed at:|Error" | head -3; then
    log_success "CCIP Sender deployment completed"
else
    log_error "CCIP Sender deployment failed"
fi

# Deploy Keeper (if Oracle Price Feed is available)
log_info ""
log_info "2.4: Deploying Price Feed Keeper..."
if [ -n "$ORACLE_PRICE_FEED" ]; then
    if forge script script/reserve/DeployKeeper.s.sol:DeployKeeper \
        --rpc-url "$RPC_URL" \
        --broadcast \
        --private-key "$PRIVATE_KEY" \
        --legacy -vvv 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "PriceFeedKeeper|deployed at:|Error" | head -3; then
        log_success "Keeper deployment completed"
    else
        log_error "Keeper deployment failed"
    fi
else
    log_warn "Skipping Keeper deployment (ORACLE_PRICE_FEED not set)"
fi

log_info ""
log_success "========================================="
log_success "Deployment Complete!"
log_success "========================================="
log_info ""
log_info "Deployment log: $DEPLOYMENT_LOG"
log_info ""
log_info "Next steps:"
log_info "1. Extract contract addresses from broadcast files"
log_info "2. Update .env file with deployed addresses"
log_info "3. Update service configurations in Proxmox containers"
log_info ""

