#!/usr/bin/env bash
# Deploy All Components: Contracts, Containers, and Services
# This script deploys everything needed for the complete SMOM-DBIS-138 setup

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 "Complete Deployment: All Components"
log_info "========================================="
log_info ""

# Step 1: Verify Network Readiness
log_info "Step 1: Verifying Network Readiness..."

# Try HTTPS endpoint first, then internal
RPC_URLS=("https://rpc-core.d-bis.org" "http://192.168.11.250:8545")
BLOCK="0"
CHAIN_ID="0"

for RPC_URL in "${RPC_URLS[@]}"; do
    RPC_RESPONSE=$(curl -s -k -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")
        if [ "$BLOCK" -gt 0 ]; then
            CHAIN_RESPONSE=$(curl -s -k -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_ID=$(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")
            fi
            break
        fi
    fi
done

# If still no response, check from Proxmox host
if [ "$BLOCK" -eq 0 ]; then
    log_warn "External RPC check failed, checking from Proxmox host..."
    BLOCK=$(ssh_proxmox "curl -s -X POST http://192.168.11.250:8545 -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' 2>/dev/null | 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
        CHAIN_ID=$(ssh_proxmox "curl -s -X POST http://192.168.11.250:8545 -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_chainId\",\"params\":[],\"id\":1}' 2>/dev/null | python3 -c 'import sys, json; data=json.load(sys.stdin); print(int(data.get(\"result\", \"0x0\"), 16))' 2>/dev/null" || echo "0")
    fi
fi

if [ "$BLOCK" -eq 0 ]; then
    log_warn "Could not verify network status, but continuing with deployment..."
    log_warn "Network verification will be done from within containers"
else
    if [ "$CHAIN_ID" -ne 138 ] && [ "$CHAIN_ID" -ne 0 ]; then
        log_error "Chain ID mismatch. Expected 138, got $CHAIN_ID"
        exit 1
    fi
    log_success "Network is ready!"
    log_info "   Current block: $BLOCK"
    log_info "   Chain ID: $CHAIN_ID"
fi
log_info ""

# Step 2: Deploy Smart Contracts (if source project configured)
log_info "========================================="
log_info "Step 2: Deploying Smart Contracts"
log_info "========================================="
log_info ""

if [ -f "$SOURCE_PROJECT/.env" ] && [ -f "$PROJECT_ROOT/scripts/deploy-contracts-chain138.sh" ]; then
    log_info "Source project .env found, deploying contracts..."
    cd "$PROJECT_ROOT"
    if bash scripts/deploy-contracts-chain138.sh 2>&1 | tee /tmp/contract-deployment.log; then
        log_success "Contracts deployed successfully"
    else
        log_warn "Contract deployment had issues (check logs)"
    fi
else
    log_warn "Skipping contract deployment:"
    log_warn "  - Source project .env: $([ -f "$SOURCE_PROJECT/.env" ] && echo "✓" || echo "✗")"
    log_warn "  - Deployment script: $([ -f "$PROJECT_ROOT/scripts/deploy-contracts-chain138.sh" ] && echo "✓" || echo "✗")"
    log_info "  You can deploy contracts later using: ./scripts/deploy-contracts-chain138.sh"
fi
log_info ""

# Step 3: Deploy LXC Containers
log_info "========================================="
log_info "Step 3: Deploying LXC Containers"
log_info "========================================="
log_info ""

cd "$PROJECT_ROOT/smom-dbis-138-proxmox"

# Deploy Services (Oracle, CCIP Monitor, Keeper, Tokenization)
log_info "3.1: Deploying Smart Contract Services..."
if ssh_proxmox "cd /opt/smom-dbis-138-proxmox 2>/dev/null || cd /root/smom-dbis-138-proxmox 2>/dev/null; \
    DEPLOY_ORACLE=true DEPLOY_CCIP_MONITOR=true DEPLOY_KEEPER=true DEPLOY_TOKENIZATION=true \
    bash scripts/deployment/deploy-services.sh 2>&1" 2>&1 | tee /tmp/services-deployment.log; then
    log_success "Smart Contract Services deployed"
else
    log_warn "Services deployment had issues (check logs)"
fi
log_info ""

# Deploy Hyperledger Services
log_info "3.2: Deploying Hyperledger Services..."
if ssh_proxmox "cd /opt/smom-dbis-138-proxmox 2>/dev/null || cd /root/smom-dbis-138-proxmox 2>/dev/null; \
    DEPLOY_FIREFLY=true DEPLOY_CACTI=true DEPLOY_FABRIC=true DEPLOY_INDY=true \
    bash scripts/deployment/deploy-hyperledger-services.sh 2>&1" 2>&1 | tee /tmp/hyperledger-deployment.log; then
    log_success "Hyperledger Services deployed"
else
    log_warn "Hyperledger deployment had issues (check logs)"
fi
log_info ""

# Deploy Monitoring Stack
log_info "3.3: Deploying Monitoring Stack..."
if ssh_proxmox "cd /opt/smom-dbis-138-proxmox 2>/dev/null || cd /root/smom-dbis-138-proxmox 2>/dev/null; \
    bash scripts/deployment/deploy-monitoring.sh 2>&1" 2>&1 | tee /tmp/monitoring-deployment.log; then
    log_success "Monitoring Stack deployed"
else
    log_warn "Monitoring deployment had issues (check logs)"
fi
log_info ""

# Deploy Explorer
log_info "3.4: Deploying Blockscout Explorer..."
if ssh_proxmox "cd /opt/smom-dbis-138-proxmox 2>/dev/null || cd /root/smom-dbis-138-proxmox 2>/dev/null; \
    bash scripts/deployment/deploy-explorer.sh 2>&1" 2>&1 | tee /tmp/explorer-deployment.log; then
    log_success "Explorer deployed"
else
    log_warn "Explorer deployment had issues (check logs)"
fi
log_info ""

# Step 4: Configure Services
log_info "========================================="
log_info "Step 4: Configuring Services"
log_info "========================================="
log_info ""

# Update RPC URLs in all services
log_info "4.1: Updating RPC URLs in all services..."

# Oracle Publisher (3500)
if ssh_proxmox "pct status 3500 >/dev/null 2>&1"; then
    log_info "Configuring Oracle Publisher (3500)..."
    ssh_proxmox "pct exec 3500 -- bash -c 'cat > /opt/oracle-publisher/.env <<EOF
RPC_URL_138=http://192.168.11.250:8545
WS_URL_138=ws://192.168.11.250:8546
ORACLE_CONTRACT_ADDRESS=
PRIVATE_KEY=
UPDATE_INTERVAL=60
METRICS_PORT=8000
DATA_SOURCE_1_URL=https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd
DATA_SOURCE_1_PARSER=coingecko
DATA_SOURCE_2_URL=https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT
DATA_SOURCE_2_PARSER=binance
EOF'"
fi

# CCIP Monitor (3501)
if ssh_proxmox "pct status 3501 >/dev/null 2>&1"; then
    log_info "Configuring CCIP Monitor (3501)..."
    ssh_proxmox "pct exec 3501 -- bash -c 'cat > /opt/ccip-monitor/.env <<EOF
RPC_URL_138=http://192.168.11.250:8545
CCIP_ROUTER_ADDRESS=
CCIP_SENDER_ADDRESS=
LINK_TOKEN_ADDRESS=
METRICS_PORT=8000
CHECK_INTERVAL=60
EOF'"
fi

# Keeper (3502)
if ssh_proxmox "pct status 3502 >/dev/null 2>&1"; then
    log_info "Configuring Keeper (3502)..."
    ssh_proxmox "pct exec 3502 -- bash -c 'cat > /opt/keeper/.env <<EOF
RPC_URL_138=http://192.168.11.250:8545
KEEPER_CONTRACT_ADDRESS=
ORACLE_CONTRACT_ADDRESS=
PRIVATE_KEY=
UPDATE_INTERVAL=300
HEALTH_PORT=3000
EOF'"
fi

# Financial Tokenization (3503)
if ssh_proxmox "pct status 3503 >/dev/null 2>&1"; then
    log_info "Configuring Financial Tokenization (3503)..."
    ssh_proxmox "pct exec 3503 -- bash -c 'cat > /opt/financial-tokenization/.env <<EOF
BESU_RPC_URL=http://192.168.11.250:8545
TOKENIZATION_CONTRACT_ADDRESS=
PRIVATE_KEY=
CHAIN_ID=138
EOF'"
fi

# Hyperledger Services
for vmid in 5200 6000 6200 6400; do
    if ssh_proxmox "pct status $vmid >/dev/null 2>&1"; then
        log_info "Configuring Hyperledger service (VMID $vmid)..."
        case $vmid in
            6200) # Firefly
                ssh_proxmox "pct exec $vmid -- bash -c 'cd /opt/firefly && \
                    sed -i \"s|FF_BLOCKCHAIN_RPC=.*|FF_BLOCKCHAIN_RPC=http://192.168.11.250:8545|\" docker-compose.yml && \
                    sed -i \"s|FF_BLOCKCHAIN_WS=.*|FF_BLOCKCHAIN_WS=ws://192.168.11.250:8546|\" docker-compose.yml'"
                ;;
            5200) # Cacti
                ssh_proxmox "pct exec $vmid -- bash -c 'cd /opt/cacti && \
                    sed -i \"s|BESU_RPC_URL=.*|BESU_RPC_URL=http://192.168.11.250:8545|\" docker-compose.yml && \
                    sed -i \"s|BESU_WS_URL=.*|BESU_WS_URL=ws://192.168.11.250:8546|\" docker-compose.yml'"
                ;;
        esac
    fi
done

# Blockscout (5000)
if ssh_proxmox "pct status 5000 >/dev/null 2>&1"; then
    log_info "Configuring Blockscout (5000)..."
    ssh_proxmox "pct exec 5000 -- bash -c 'cd /opt/blockscout && \
        sed -i \"s|ETHEREUM_JSONRPC_HTTP_URL=.*|ETHEREUM_JSONRPC_HTTP_URL=http://192.168.11.250:8545|\" docker-compose.yml && \
        sed -i \"s|ETHEREUM_JSONRPC_TRACE_URL=.*|ETHEREUM_JSONRPC_TRACE_URL=http://192.168.11.250:8545|\" docker-compose.yml'"
fi

log_success "Service configuration completed"
log_info ""

# Step 5: Summary
log_info "========================================="
log_success "Deployment Complete!"
log_info "========================================="
log_info ""
log_info "Deployed Components:"
log_info "  ✓ Smart Contracts (if configured)"
log_info "  ✓ Smart Contract Services (3500-3503)"
log_info "  ✓ Hyperledger Services (5200, 6000, 6200, 6400)"
log_info "  ✓ Monitoring Stack (3504-3508)"
log_info "  ✓ Blockscout Explorer (5000)"
log_info ""
log_info "Next Steps:"
log_info "1. Deploy contracts (if not done): ./scripts/deploy-contracts-chain138.sh"
log_info "2. Update service .env files with contract addresses"
log_info "3. Start services: pct exec <VMID> -- systemctl start <service>"
log_info "4. Verify deployments: pct list"
log_info ""
log_info "Logs saved to:"
log_info "  - /tmp/contract-deployment.log"
log_info "  - /tmp/services-deployment.log"
log_info "  - /tmp/hyperledger-deployment.log"
log_info "  - /tmp/monitoring-deployment.log"
log_info "  - /tmp/explorer-deployment.log"
log_info ""

