#!/bin/bash
# HDGL Bridge - Single Deploy Script
# Elegant, simple, reliable

set -e

GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

log() { echo -e "${GREEN}✓${NC} $1"; }
info() { echo -e "${BLUE}→${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; exit 1; }

# Check prerequisites
check_prereqs() {
    info "Checking prerequisites..."
    command -v python3 >/dev/null || error "python3 not found"
    command -v cargo >/dev/null || error "cargo not found (install Rust)"
    command -v solana >/dev/null || error "solana CLI not found"
    command -v node >/dev/null || error "node not found"
    log "Prerequisites OK"
}

# Setup Python environment
setup_python() {
    info "Setting up Python environment..."
    
    if [ ! -d "venv" ]; then
        python3 -m venv venv
    fi
    
    source venv/bin/activate
    pip install --quiet web3 solana-py
    
    log "Python environment ready"
}

# Build Solana program
build_solana() {
    info "Building Solana program..."
    
    cd solana
    cargo build-bpf
    
    log "Solana program built: $(ls -1 target/deploy/*.so | head -1)"
    cd ..
}

# Deploy Solana program
deploy_solana() {
    info "Deploying to Solana..."
    
    PROGRAM_PATH="solana/target/deploy/hdgl_solana.so"
    
    if [ ! -f "$PROGRAM_PATH" ]; then
        error "Program not built. Run: ./deploy_hdgl.sh build"
    fi
    
    # Deploy
    PROGRAM_ID=$(solana program deploy $PROGRAM_PATH | grep "Program Id:" | awk '{print $3}')
    
    