#!/usr/bin/env bash
# Direct deployment of CCIPReceiver using cast send
# Bypasses forge script compilation issues

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
source "$PROJECT_ROOT/scripts/lib/forge-scope.sh"

# Load environment variables
source "$HOME/projects/explorer-monorepo/.env" 2>/dev/null || true

PRIVATE_KEY="${PRIVATE_KEY:-}"
CCIP_ROUTER_ADDRESS="${CCIP_ROUTER_ADDRESS:-}"
ORACLE_AGGREGATOR_ADDRESS="${ORACLE_AGGREGATOR_ADDRESS:-}"
RPC_URL="${RPC_URL:-http://192.168.11.250:8545}"

if [ -z "$PRIVATE_KEY" ]; then
    echo "Error: PRIVATE_KEY not set"
    exit 1
fi

if [ -z "$CCIP_ROUTER_ADDRESS" ]; then
    echo "Error: CCIP_ROUTER_ADDRESS not set"
    exit 1
fi

if [ -z "$ORACLE_AGGREGATOR_ADDRESS" ]; then
    echo "Error: ORACLE_AGGREGATOR_ADDRESS not set"
    exit 1
fi

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     DEPLOY CCIPReceiver - Direct Deployment                  ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "RPC URL: $RPC_URL"
echo "CCIP Router: $CCIP_ROUTER_ADDRESS"
echo "Oracle Aggregator: $ORACLE_AGGREGATOR_ADDRESS"
echo ""

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

echo "Deployer: $DEPLOYER"
echo ""

# Check balance
BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
echo "Balance: $(cast --to-unit "$BALANCE" ether) ETH"
echo ""

# Compile contract
echo "Compiling CCIPReceiver..."
forge build --force contracts/ccip/CCIPReceiver.sol 2>&1 | grep -E "(Compiling|Error|Successfully)" || true

# Get bytecode
BYTECODE=$(forge build --force --json 2>/dev/null | jq -r '.contracts."contracts/ccip/CCIPReceiver.sol:CCIPReceiver".bytecode.object' 2>/dev/null || echo "")

if [ -z "$BYTECODE" ] || [ "$BYTECODE" = "null" ]; then
    echo "Error: Failed to get bytecode"
    echo "Trying alternative method..."
    
    # Try to get from out directory
    BYTECODE=$(cat out/CCIPReceiver.sol/CCIPReceiver.json 2>/dev/null | jq -r '.bytecode.object' || echo "")
fi

if [ -z "$BYTECODE" ] || [ "$BYTECODE" = "null" ]; then
    echo "Error: Could not get bytecode. Please compile manually first."
    exit 1
fi

echo "✅ Bytecode obtained (${#BYTECODE} chars)"
echo ""

# Encode constructor arguments
echo "Encoding constructor arguments..."
CONSTRUCTOR_ARGS=$(cast abi-encode "constructor(address,address)" "$CCIP_ROUTER_ADDRESS" "$ORACLE_AGGREGATOR_ADDRESS")
DEPLOY_BYTECODE="${BYTECODE}${CONSTRUCTOR_ARGS:2}"  # Remove 0x prefix from constructor args

echo "✅ Constructor arguments encoded"
echo ""

# Deploy using cast send
echo "Deploying contract..."
echo "This may take a minute..."
echo ""

TX_HASH=$(cast send --private-key "$PRIVATE_KEY" --rpc-url "$RPC_URL" --legacy --gas-price 20000000000 --gas-limit 5000000 --create "$DEPLOY_BYTECODE" 2>&1 | grep -oE "0x[a-fA-F0-9]{64}" | tail -1 || echo "")

if [ -z "$TX_HASH" ]; then
    echo "❌ Deployment failed - no transaction hash"
    exit 1
fi

echo "✅ Transaction sent: $TX_HASH"
echo ""

# Wait for confirmation
echo "Waiting for transaction confirmation..."
sleep 5

# Get receipt
RECEIPT=$(cast receipt "$TX_HASH" --rpc-url "$RPC_URL" 2>&1 || echo "")
if echo "$RECEIPT" | grep -q "status.*0x1"; then
    CONTRACT_ADDRESS=$(echo "$RECEIPT" | grep -oE "contractAddress.*0x[a-fA-F0-9]{40}" | grep -oE "0x[a-fA-F0-9]{40}" || echo "")
    
    if [ -n "$CONTRACT_ADDRESS" ]; then
        echo "✅ CCIPReceiver deployed successfully!"
        echo "   Address: $CONTRACT_ADDRESS"
        echo "   Transaction: $TX_HASH"
        echo ""
        
        # Verify on-chain
        CODE=$(cast code "$CONTRACT_ADDRESS" --rpc-url "$RPC_URL" 2>&1 || echo "")
        CODE_SIZE=$(echo "$CODE" | wc -c)
        
        if [ "$CODE_SIZE" -gt 100 ]; then
            echo "✅ Contract verified on-chain (code size: $CODE_SIZE bytes)"
        else
            echo "⚠️  Contract code size: $CODE_SIZE bytes (may need more confirmations)"
        fi
        
        echo ""
        echo "Update .env with:"
        echo "CCIP_RECEIVER=$CONTRACT_ADDRESS"
        echo "CCIP_RECEIVER_138=$CONTRACT_ADDRESS"
    else
        echo "⚠️  Transaction confirmed but contract address not found in receipt"
        echo "Receipt: $RECEIPT"
    fi
else
    echo "❌ Transaction failed"
    echo "Receipt: $RECEIPT"
    exit 1
fi
