#!/usr/bin/env bash
# Deploy Phase 2 and all contracts in full parallel mode
# This script orchestrates Phase 2 deployment and contract deployment in parallel where possible

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

RPC_URL="${RPC_URL:-${RPC_URL_138:-${CHAIN138_RPC_URL:-}}}"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Phase 2 + Contract Deployment - Full Parallel Mode"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Step 1: Generate Phase 2 configuration
log_warn "Step 1: Generating Phase 2 configuration..."
if ! ./scripts/deployment/generate-phase2-tfvars.sh; then
    log_error "Failed to generate Phase 2 configuration"
    exit 1
fi
log_success "✅ Phase 2 configuration generated"

# Step 2: Deploy Phase 2 infrastructure (all regions in parallel)
log_warn "Step 2: Deploying Phase 2 docker-compose files (all regions in parallel)..."
cd terraform/phases/phase2

if ! terraform init -upgrade > /dev/null 2>&1; then
    log_error "Failed to initialize Terraform"
    exit 1
fi

if ! terraform apply -auto-approve; then
    log_error "Failed to deploy Phase 2"
    exit 1
fi
log_success "✅ Phase 2 deployed to all regions"

cd "$PROJECT_ROOT"

# Step 3: Start Phase 2 services (all regions in parallel) and deploy contracts in parallel
log_warn "Step 3: Starting Phase 2 services and deploying contracts in parallel..."

# Start Phase 2 services in parallel
(
    log_warn "Starting Phase 2 services (all regions)..."
    if ./terraform/phases/phase2/scripts/start-services.sh all; then
        log_success "✅ Phase 2 services started on all regions"
    else
        log_error "❌ Failed to start Phase 2 services"
        exit 1
    fi
) &
PHASE2_SERVICES_PID=$!

# Deploy contracts in parallel (if RPC is ready)
if [ -n "$RPC_URL" ]; then
    (
        log_warn "Deploying contracts (parallel)..."
        # Wait a bit for Phase 2 Besu nodes to be ready
        sleep 10
        if ./scripts/deployment/deploy-contracts-parallel.sh; then
            log_success "✅ All contracts deployed"
        else
            log_error "❌ Failed to deploy contracts"
            exit 1
        fi
    ) &
    CONTRACTS_PID=$!
else
    log_warn "⚠️  RPC_URL not set in .env. Skipping contract deployment."
    CONTRACTS_PID=""
fi

# Wait for both operations to complete
wait $PHASE2_SERVICES_PID
if [ -n "$CONTRACTS_PID" ]; then
    wait $CONTRACTS_PID
fi

# Step 4: Verify deployments (parallel)
log_warn "Step 4: Verifying deployments (parallel)..."

# Verify Phase 2 services in parallel
(
    log_warn "Verifying Phase 2 services..."
    ./terraform/phases/phase2/scripts/status.sh all > /tmp/phase2-status.out 2>&1
    if [ $? -eq 0 ]; then
        log_success "✅ Phase 2 services verified"
    else
        log_error "❌ Phase 2 services verification failed"
    fi
) &
PHASE2_VERIFY_PID=$!

# Verify contracts in parallel (if deployed)
if [ -n "$CONTRACTS_PID" ] && [ -n "$RPC_URL" ]; then
    (
        log_warn "Verifying contracts..."
        if ./scripts/deployment/verify-contracts-parallel.sh > /tmp/contracts-verify.out 2>&1; then
            log_success "✅ Contracts verified"
        else
            log_error "❌ Contract verification failed"
        fi
    ) &
    CONTRACTS_VERIFY_PID=$!
else
    CONTRACTS_VERIFY_PID=""
fi

# Wait for verifications
wait $PHASE2_VERIFY_PID
if [ -n "$CONTRACTS_VERIFY_PID" ]; then
    wait $CONTRACTS_VERIFY_PID
fi

# Display results
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Deployment Summary"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Phase 2 Status:"
cat /tmp/phase2-status.out 2>/dev/null || echo "Status check failed"
echo ""
if [ -n "$CONTRACTS_VERIFY_PID" ]; then
    echo "Contract Verification:"
    cat /tmp/contracts-verify.out 2>/dev/null || echo "Verification failed"
    echo ""
fi

# Cleanup
rm -f /tmp/phase2-status.out /tmp/contracts-verify.out

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_success "=== Full Parallel Deployment Complete ==="
echo ""
echo "Next steps:"
echo "1. Review Phase 2 services: ./terraform/phases/phase2/scripts/status.sh all"
echo "2. Verify contracts: ./scripts/deployment/verify-contracts-parallel.sh"
echo "3. Check deployment outputs: terraform/phases/phase2/terraform output"
