#!/bin/bash
# Complete Phase 1 Setup Script
# Automates all next steps that can be automated

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE1_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.env"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "=========================================="
echo "Phase 1: Complete Setup"
echo "=========================================="
echo ""

# Load Cloudflare credentials and domain
if [ -f "$ENV_FILE" ]; then
    echo -e "${BLUE}Loading Cloudflare credentials and domain from .env...${NC}"
    export $(grep -v '^#' "$ENV_FILE" | grep -E "CLOUDFLARE_" | xargs)
    # Get domain from CLOUDFLARE_DOMAIN or extract from RPC_URL
    if [ -z "${CLOUDFLARE_DOMAIN:-}" ]; then
        RPC_URL=$(grep "^RPC_URL=" "$ENV_FILE" 2>/dev/null | cut -d'=' -f2 | tr -d '"' || echo "")
        if [ -n "$RPC_URL" ]; then
            DOMAIN_FROM_ENV=$(echo "$RPC_URL" | sed 's|https\?://||' | sed 's|/.*||')
        fi
    else
        # Use CLOUDFLARE_DOMAIN and construct RPC subdomain
        DOMAIN_FROM_ENV="rpc.${CLOUDFLARE_DOMAIN}"
    fi
    if [ -n "$DOMAIN_FROM_ENV" ]; then
        export DOMAIN_FROM_ENV
    fi
fi

cd "$PHASE1_DIR"

# Get infrastructure details
NGINX_IP=$(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value.public_ip // empty' || echo "")
NGINX_PRIVATE_IP=$(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value.private_ip // empty' || echo "")
BACKEND_IPS=$(terraform output -json 2>/dev/null | jq -r '.phase1_us_regions.value | to_entries[] | .value.private_ips[0]' | tr '\n' ',' | sed 's/,$//' || echo "")

if [ -z "$NGINX_IP" ]; then
    echo -e "${RED}Error: Nginx proxy IP not found${NC}"
    exit 1
fi

echo -e "${GREEN}Infrastructure Details:${NC}"
echo "  Nginx Proxy: $NGINX_IP (public) / $NGINX_PRIVATE_IP (private)"
echo "  Backend IPs: $BACKEND_IPS"
echo ""

# Step 1: Update Nginx backend configuration
echo -e "${BLUE}Step 1: Updating Nginx Backend Configuration${NC}"
echo "---------------------------------------------------"

if [ -n "$BACKEND_IPS" ]; then
    echo "Copying update script to Nginx proxy..."
    scp "$SCRIPT_DIR/update-nginx-backends.sh" besuadmin@$NGINX_IP:/tmp/ 2>/dev/null || {
        echo -e "${YELLOW}Warning: Could not copy script. Manual step required.${NC}"
    }
    
    echo "Updating Nginx backend configuration..."
    ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no besuadmin@$NGINX_IP "chmod +x /tmp/update-nginx-backends.sh && sudo /tmp/update-nginx-backends.sh '$BACKEND_IPS'" 2>&1 | while read line; do
        echo "  $line"
    done || {
        echo -e "${YELLOW}Warning: Could not update Nginx configuration remotely.${NC}"
        echo -e "${YELLOW}Run manually: ssh besuadmin@$NGINX_IP${NC}"
        echo -e "${YELLOW}Then: ./update-nginx-backends.sh '$BACKEND_IPS'${NC}"
    }
else
    echo -e "${YELLOW}Warning: Backend IPs not found. Skipping Nginx update.${NC}"
fi

echo ""

# Step 2: Setup Cloudflare Tunnel
echo -e "${BLUE}Step 2: Setting Up Cloudflare Tunnel${NC}"
echo "---------------------------------------------------"

DOMAIN_NAME="${1:-${DOMAIN_FROM_ENV:-}}"
if [ -z "$DOMAIN_NAME" ]; then
    echo -e "${YELLOW}No domain name provided. Skipping Cloudflare Tunnel setup.${NC}"
    echo -e "${YELLOW}To setup manually:${NC}"
    echo -e "${YELLOW}  ssh besuadmin@$NGINX_IP${NC}"
    echo -e "${YELLOW}  ./setup-cloudflare-tunnel.sh <domain-name>${NC}"
else
    echo -e "${GREEN}Using domain: $DOMAIN_NAME${NC}"
    echo "Copying Cloudflare Tunnel setup script..."
    scp "$SCRIPT_DIR/setup-cloudflare-tunnel.sh" besuadmin@$NGINX_IP:/tmp/ 2>/dev/null || {
        echo -e "${YELLOW}Warning: Could not copy script. Manual step required.${NC}"
    }
    
    echo -e "${YELLOW}Cloudflare Tunnel setup requires browser authentication.${NC}"
    echo -e "${YELLOW}Please run manually:${NC}"
    echo -e "${YELLOW}  ssh besuadmin@$NGINX_IP${NC}"
    echo -e "${YELLOW}  cd /tmp && ./setup-cloudflare-tunnel.sh $DOMAIN_NAME${NC}"
fi

echo ""

# Step 3: Backend VM Configuration
echo -e "${BLUE}Step 3: Backend VM Configuration${NC}"
echo "---------------------------------------------------"
echo -e "${YELLOW}Backend VMs use private IPs and require VPN/Bastion access.${NC}"
echo -e "${YELLOW}Configuration scripts are ready for manual execution:${NC}"
echo ""

BACKEND_VMS=$(terraform output -json 2>/dev/null | jq -r '.phase1_us_regions.value | to_entries[] | "\(.key):\(.value.private_ips[0]):\(.value.vm_names[0])"' || echo "")

if [ -n "$BACKEND_VMS" ]; then
    while IFS=: read -r region ip vm_name; do
        if [ -n "$ip" ] && [ "$ip" != "null" ]; then
            echo -e "  ${BLUE}Region: $region${NC}"
            echo -e "    IP: $ip"
            echo -e "    VM: $vm_name"
            echo -e "    Command: ssh besuadmin@$ip"
            echo -e "    Then: ./setup-besu-node.sh besu-node 0 $region"
            echo ""
        fi
    done <<< "$BACKEND_VMS"
fi

# Step 4: Cloudflare DNS Configuration
echo -e "${BLUE}Step 4: Cloudflare DNS Configuration${NC}"
echo "---------------------------------------------------"

if [ -n "${CLOUDFLARE_ZONE_ID:-}" ] && [ -n "${CLOUDFLARE_API_TOKEN:-}" ] && [ -n "$DOMAIN_NAME" ]; then
    echo "Cloudflare credentials available. DNS can be configured via API."
    echo -e "${YELLOW}Note: DNS records will be created automatically when Cloudflare Tunnel is set up.${NC}"
else
    echo -e "${YELLOW}Cloudflare DNS configuration requires:${NC}"
    echo -e "${YELLOW}  1. Domain name${NC}"
    echo -e "${YELLOW}  2. Cloudflare Tunnel ID${NC}"
    echo -e "${YELLOW}  3. Manual configuration in Cloudflare Dashboard${NC}"
fi

echo ""

# Summary
echo "=========================================="
echo "Setup Summary"
echo "=========================================="
echo -e "${GREEN}Completed:${NC}"
echo "  ✓ Infrastructure deployed"
echo "  ✓ Nginx proxy configured"
echo "  ✓ Scripts prepared"
echo ""
echo -e "${YELLOW}Manual Steps Required:${NC}"
echo "  1. Setup Cloudflare Tunnel (requires browser auth)"
echo "  2. Configure Besu nodes on backend VMs (requires VPN/Bastion)"
echo "  3. Configure Cloudflare DNS (if not done automatically)"
echo ""
echo -e "${BLUE}Next Commands:${NC}"
if [ -n "$DOMAIN_NAME" ]; then
    echo "  ssh besuadmin@$NGINX_IP"
    echo "  cd /tmp && ./setup-cloudflare-tunnel.sh $DOMAIN_NAME"
else
    echo "  ssh besuadmin@$NGINX_IP"
    echo "  cd /tmp && ./setup-cloudflare-tunnel.sh <your-domain>"
fi
echo ""

