#!/usr/bin/env bash
# Deploy contracts from Proxmox host where RPC access is allowed
# Usage: ./deploy-contracts-from-proxmox.sh

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"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PASS="${PROXMOX_PASS:-L@kers2010}"

# 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"; }

# SSH helper
ssh_proxmox() {
    sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

log_info "========================================="
log_info "Deploy Contracts from Proxmox Host"
log_info "========================================="
log_info ""

# Step 1: Check if source project exists on Proxmox host
log_info "Step 1: Checking source project on Proxmox host..."

SOURCE_PROJECT_REMOTE="/root/smom-dbis-138"
if ssh_proxmox "[ -d '$SOURCE_PROJECT_REMOTE' ]"; then
    log_success "Source project found at $SOURCE_PROJECT_REMOTE"
    REMOTE_PROJECT="$SOURCE_PROJECT_REMOTE"
elif ssh_proxmox "[ -d '/home/intlc/projects/smom-dbis-138' ]"; then
    log_success "Source project found at /home/intlc/projects/smom-dbis-138"
    REMOTE_PROJECT="/home/intlc/projects/smom-dbis-138"
else
    log_error "Source project not found on Proxmox host"
    log_info "Syncing source project to Proxmox host..."
    
    # Create directory
    ssh_proxmox "mkdir -p $SOURCE_PROJECT_REMOTE"
    
    # Sync files (excluding node_modules, .git, etc.)
    rsync -avz --exclude 'node_modules' --exclude '.git' --exclude 'broadcast' \
        "$SOURCE_PROJECT/" "root@$PROXMOX_HOST:$SOURCE_PROJECT_REMOTE/" || {
        log_error "Failed to sync source project"
        exit 1
    }
    
    REMOTE_PROJECT="$SOURCE_PROJECT_REMOTE"
    log_success "Source project synced to $REMOTE_PROJECT"
fi

# Step 2: Check .env file
log_info ""
log_info "Step 2: Checking .env file..."

if ssh_proxmox "[ -f '$REMOTE_PROJECT/.env' ]"; then
    log_success ".env file found"
else
    log_warn ".env file not found, copying from local..."
    if [ -f "$SOURCE_PROJECT/.env" ]; then
        scp -o StrictHostKeyChecking=no "$SOURCE_PROJECT/.env" "root@$PROXMOX_HOST:$REMOTE_PROJECT/.env" || {
            log_error "Failed to copy .env file"
            exit 1
        }
        log_success ".env file copied"
    else
        log_error ".env file not found locally or remotely"
        exit 1
    fi
fi

# Step 3: Verify network from Proxmox host
log_info ""
log_info "Step 3: Verifying network from Proxmox host..."

BLOCK=$(ssh_proxmox "cd $REMOTE_PROJECT && source .env 2>/dev/null && \
    curl -s -X POST \${RPC_URL_138:-http://192.168.11.250:8545} \
    -H 'Content-Type: application/json' \
    -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' | \
    python3 -c 'import sys, json; data=json.load(sys.stdin); print(int(data.get(\"result\", \"0x0\"), 16))' 2>/dev/null" || echo "0")

if [ "$BLOCK" -gt 0 ]; then
    log_success "Network is ready! Block: $BLOCK"
else
    log_warn "Could not verify block number, but continuing..."
fi

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

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

# Deploy Oracle
log_info "4.1: Deploying Oracle Contract..."
ssh_proxmox "cd $REMOTE_PROJECT && source .env 2>/dev/null && \
    forge script script/DeployOracle.s.sol:DeployOracle \
    --rpc-url \${RPC_URL_138:-http://192.168.11.250:8545} \
    --broadcast \
    --private-key \$PRIVATE_KEY \
    --legacy -vvv" 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "Oracle|Aggregator|Proxy|deployed at|Error" | head -10 || {
    log_warn "Oracle deployment may have issues (check logs)"
}

# Deploy CCIP Router
log_info ""
log_info "4.2: Deploying CCIP Router..."
ssh_proxmox "cd $REMOTE_PROJECT && source .env 2>/dev/null && \
    forge script script/DeployCCIPRouter.s.sol:DeployCCIPRouter \
    --rpc-url \${RPC_URL_138:-http://192.168.11.250:8545} \
    --broadcast \
    --private-key \$PRIVATE_KEY \
    --legacy -vvv" 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "CCIP Router|deployed at|Error" | head -10 || {
    log_warn "CCIP Router deployment may have issues (check logs)"
}

# Deploy CCIP Sender
log_info ""
log_info "4.3: Deploying CCIP Sender..."
ssh_proxmox "cd $REMOTE_PROJECT && source .env 2>/dev/null && \
    forge script script/DeployCCIPSender.s.sol:DeployCCIPSender \
    --rpc-url \${RPC_URL_138:-http://192.168.11.250:8545} \
    --broadcast \
    --private-key \$PRIVATE_KEY \
    --legacy -vvv" 2>&1 | tee -a "$DEPLOYMENT_LOG" | grep -E "CCIPSender|deployed at|Error" | head -10 || {
    log_warn "CCIP Sender deployment may have issues (check logs)"
}

# Extract addresses
log_info ""
log_info "========================================="
log_info "Step 5: Extracting Contract Addresses"
log_info "========================================="
log_info ""

# Extract addresses from broadcast files
ssh_proxmox "cd $REMOTE_PROJECT && \
    find broadcast -name 'run-latest.json' -type f 2>/dev/null | head -5" | while read -r broadcast_file; do
    if [ -n "$broadcast_file" ]; then
        log_info "Found broadcast file: $broadcast_file"
        # Extract addresses would go here
    fi
done

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 on Proxmox host"
log_info "2. Update .env file with deployed addresses"
log_info "3. Update service configurations in Proxmox containers"
log_info ""

