#!/usr/bin/env bash
# Deploy All Smart Contracts to ChainID 138
# Uses RPC: http://192.168.11.250:8545

set -euo pipefail

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

load_explorer_runtime_env

RPC_URL="http://192.168.11.250:8545"
CHAIN_ID=138
GAS_PRICE="${1:-20000000000}"  # Default 20 gwei
USE_VIA_IR="${2:-false}"  # Use via-ir for stack too deep issues

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     DEPLOY ALL SMART CONTRACTS TO CHAINID 138                ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "RPC URL: $RPC_URL"
echo "Chain ID: $CHAIN_ID"
echo "Gas Price: $GAS_PRICE ($(echo "scale=2; $GAS_PRICE / 1000000000" | bc) gwei)"
echo ""

# Check prerequisites
if [ -z "${PRIVATE_KEY:-}" ]; then
    echo "❌ Error: PRIVATE_KEY not available in effective environment"
    exit 1
fi

if ! command -v forge &> /dev/null; then
    echo "❌ Error: Foundry (forge) not installed"
    exit 1
fi

# Verify RPC connectivity
echo "Checking RPC connectivity..."
if ! cast block-number --rpc-url "$RPC_URL" > /dev/null 2>&1; then
    echo "❌ Error: RPC not accessible at $RPC_URL"
    exit 1
fi

BLOCK_NUM=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ACTUAL_CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

if [ "$ACTUAL_CHAIN_ID" != "$CHAIN_ID" ]; then
    echo "⚠️  Warning: Chain ID mismatch (expected: $CHAIN_ID, got: $ACTUAL_CHAIN_ID)"
fi

echo "✅ RPC accessible (block: $BLOCK_NUM, chain: $ACTUAL_CHAIN_ID)"
echo ""

# Check deployer balance
DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$DEPLOYER" ]; then
    echo "❌ Error: Invalid PRIVATE_KEY"
    exit 1
fi

BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
BALANCE_ETH=$(echo "scale=4; $BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")

echo "Deployer: $DEPLOYER"
echo "Balance: $BALANCE_ETH ETH"
echo ""

if (( $(echo "$BALANCE_ETH < 0.1" | bc -l 2>/dev/null || echo 1) )); then
    echo "⚠️  Warning: Low balance. Deployment may fail."
    echo ""
fi

# Check if source project exists
if [ ! -d "$SOURCE_PROJECT" ]; then
    echo "❌ Error: Source project not found: $SOURCE_PROJECT"
    exit 1
fi

cd "$SOURCE_PROJECT"

# Build contracts first
echo "═══════════════════════════════════════════════════════════════"
echo "Step 1: Building contracts..."
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Always use via-ir to avoid stack too deep issues
echo "Building with via-ir (required for TokenFactory138)..."
if forge build --via-ir 2>&1 | tail -10; then
    echo ""
    echo "✅ Contracts built successfully"
else
    echo ""
    echo "⚠️  Build completed with warnings (some contracts may have issues)"
fi

echo ""

# List available deployment scripts
echo "═══════════════════════════════════════════════════════════════"
echo "Step 2: Available Deployment Scripts"
echo "═══════════════════════════════════════════════════════════════"
echo ""

DEPLOYMENT_SCRIPTS=(
    "script/DeployMockLinkToken.s.sol:DeployMockLinkToken"
    "script/DeployCCIPReceiver.s.sol:DeployCCIPReceiver"
    "script/DeployCCIPLoggerOnly.s.sol:DeployCCIPLoggerOnly"
)

for script in "${DEPLOYMENT_SCRIPTS[@]}"; do
    if [ -f "$SOURCE_PROJECT/${script%%:*}" ]; then
        echo "  ✅ $script"
    else
        echo "  ⚠️  $script (not found)"
    fi
done

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "Step 3: Deploy Contracts"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Function to deploy a contract
deploy_contract() {
    local script_path=$1
    local contract_name=$2
    
    echo "Deploying $contract_name..."
    echo "───────────────────────────────────────────────────────────"
    
    if [ ! -f "$SOURCE_PROJECT/$script_path" ]; then
        echo "⚠️  Script not found: $script_path"
        return 1
    fi
    
    # Extract script name and contract name
    local script_file=$(basename "$script_path" .s.sol)
    local script_contract="${script_path##*/}"
    script_contract="${script_contract%.s.sol}"
    
    echo "Script: $script_path"
    echo "Contract: $contract_name"
    echo ""
    
    # Deploy using forge script (always use via-ir for consistency)
    local deploy_cmd="forge script $script_path \
        --rpc-url $RPC_URL \
        --broadcast \
        --legacy \
        --gas-price $GAS_PRICE \
        --via-ir \
        -vvv"
    
    echo "Running: $deploy_cmd"
    echo ""
    
    if eval "$deploy_cmd" 2>&1 | tee "/tmp/deploy-${contract_name}.log"; then
        echo ""
        echo "✅ $contract_name deployed successfully"
        
        # Try to extract deployed address from logs
        DEPLOYED_ADDRESS=$(grep -oE "0x[0-9a-fA-F]{40}" "/tmp/deploy-${contract_name}.log" | tail -1 || echo "")
        if [ -n "$DEPLOYED_ADDRESS" ]; then
            echo "   Address: $DEPLOYED_ADDRESS"
        fi
    else
        echo ""
        echo "❌ $contract_name deployment failed"
        echo "   Check logs: /tmp/deploy-${contract_name}.log"
        return 1
    fi
    
    echo ""
    return 0
}

# Deploy LINK Token first (required for other contracts)
echo "📋 Deployment Order:"
echo "  1. LINK Token (MockLinkToken)"
echo "  2. CCIP Receiver"
echo "  3. CCIP Logger"
echo ""

# Auto-deploy LINK Token (required for other contracts)
echo "Deploying LINK Token (required for CCIP)..."
echo ""
deploy_contract "script/DeployMockLinkToken.s.sol:DeployMockLinkToken" "MockLinkToken"

# Update address inventory with LINK token address if found
if [ -n "${DEPLOYED_ADDRESS:-}" ]; then
    echo ""
    echo "Updating address inventory with LINK_TOKEN=$DEPLOYED_ADDRESS"
    persist_inventory_value "LINK_TOKEN" "$DEPLOYED_ADDRESS" || true
    persist_inventory_value "CCIP_CHAIN138_FEE_TOKEN" "$DEPLOYED_ADDRESS" || true
    echo "✅ Address inventory updated"
    DEPLOYED_ADDRESS=""  # Reset for next deployment
fi

echo ""
echo "Deploying CCIP Receiver..."
deploy_contract "script/DeployCCIPReceiver.s.sol:DeployCCIPReceiver" "CCIPReceiver"

echo ""
echo "Deploying CCIP Logger..."
deploy_contract "script/DeployCCIPLoggerOnly.s.sol:DeployCCIPLoggerOnly" "CCIPLogger"

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "Deployment Complete"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "📋 Summary:"
echo "  RPC: $RPC_URL"
echo "  Chain ID: $CHAIN_ID"
echo "  Deployer: $DEPLOYER"
echo ""
echo "📄 Deployment logs saved in /tmp/deploy-*.log"
echo ""
