#!/bin/bash

# Check Environment Variables Requirements
# This script checks what environment variables are needed for deployment

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
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"
fi

echo "=== Environment Variables Requirements Check ==="
echo ""

echo ""
echo "=== Required Variables (Must Be Set) ==="
echo ""

# Required for all phases
REQUIRED_ALL=(
    "PRIVATE_KEY"
    "ETHEREUM_MAINNET_RPC"
    "RPC_URL_138"
    "ETHERSCAN_API_KEY"
)

MISSING_REQUIRED=()
for var in "${REQUIRED_ALL[@]}"; do
    if [ -z "${!var:-}" ] || [ "${!var:-}" == "0x..." ] || [ "${!var:-}" == "your_etherscan_api_key" ] || [ "${!var:-}" == "http://chain138.example.com:8545" ]; then
        echo "✗ $var: NOT SET or using placeholder"
        MISSING_REQUIRED+=("$var")
    else
        if [ "$var" == "PRIVATE_KEY" ]; then
            echo "✓ $var: SET (${!var:0:10}...)"
        else
            echo "✓ $var: SET"
        fi
    fi
done

echo ""
echo "=== Phase-Specific Requirements ==="
echo ""

# Phase 2: Core Contracts
echo "Phase 2 (Deploy Core Contracts):"
if [ ${#MISSING_REQUIRED[@]} -eq 0 ]; then
    echo "  ✓ All prerequisites met"
else
    echo "  ✗ Missing prerequisites (see above)"
fi

# Phase 3: Enhanced Router
echo ""
echo "Phase 3 (Deploy Enhanced Router):"
if [ -z "$BRIDGE_SWAP_COORDINATOR" ] || [ "$BRIDGE_SWAP_COORDINATOR" == "0x..." ]; then
    echo "  ⚠️  BRIDGE_SWAP_COORDINATOR: Not set (needed after Phase 2)"
else
    echo "  ✓ BRIDGE_SWAP_COORDINATOR: SET"
fi

# Phase 4: Integration Contracts
echo ""
echo "Phase 4 (Deploy Integration Contracts):"
if [ -z "$BRIDGE_SWAP_COORDINATOR" ] || [ "$BRIDGE_SWAP_COORDINATOR" == "0x..." ]; then
    echo "  ✗ BRIDGE_SWAP_COORDINATOR: Not set (required)"
else
    echo "  ✓ BRIDGE_SWAP_COORDINATOR: SET"
fi

if [ -z "$RESERVE_SYSTEM" ] || [ "$RESERVE_SYSTEM" == "0x..." ]; then
    echo "  ✗ RESERVE_SYSTEM: Not set (required)"
else
    echo "  ✓ RESERVE_SYSTEM: SET"
fi

# Phase 5: Initialize
echo ""
echo "Phase 5 (Initialize System):"
if [ -z "$ENHANCED_SWAP_ROUTER" ] || [ "$ENHANCED_SWAP_ROUTER" == "0x..." ]; then
    echo "  ⚠️  ENHANCED_SWAP_ROUTER: Not set (needed after Phase 3)"
else
    echo "  ✓ ENHANCED_SWAP_ROUTER: SET"
fi

# Phase 6: Provide Liquidity
echo ""
echo "Phase 6 (Provide Liquidity):"
if [ -z "$LIQUIDITY_POOL" ] || [ "$LIQUIDITY_POOL" == "0x..." ]; then
    echo "  ⚠️  LIQUIDITY_POOL: Not set (needed after Phase 2)"
else
    echo "  ✓ LIQUIDITY_POOL: SET"
fi

if [ -z "$RESERVE_SYSTEM" ] || [ "$RESERVE_SYSTEM" == "0x..." ]; then
    echo "  ✗ RESERVE_SYSTEM: Not set (required)"
else
    echo "  ✓ RESERVE_SYSTEM: SET"
fi

echo ""
echo "=== Contract Addresses (Populated During Deployment) ==="
echo ""

CONTRACT_VARS=(
    "LOCKBOX_138"
    "BOND_MANAGER"
    "CHALLENGE_MANAGER"
    "LIQUIDITY_POOL"
    "INBOX_ETH"
    "SWAP_ROUTER"
    "BRIDGE_SWAP_COORDINATOR"
    "ENHANCED_SWAP_ROUTER"
    "STABLECOIN_PEG_MANAGER"
    "COMMODITY_PEG_MANAGER"
    "ISO_CURRENCY_MANAGER"
    "BRIDGE_RESERVE_COORDINATOR"
)

SET_COUNT=0
for var in "${CONTRACT_VARS[@]}"; do
    if [ ! -z "${!var}" ] && [ "${!var}" != "0x..." ] && [ "${!var}" != "" ]; then
        echo "✓ $var: ${!var}"
        SET_COUNT=$((SET_COUNT + 1))
    else
        echo "○ $var: Not set"
    fi
done

echo ""
echo "Set: $SET_COUNT/${#CONTRACT_VARS[@]} contract addresses"

echo ""
echo "=== Optional Configuration Variables ==="
echo ""

OPTIONAL_VARS=(
    "BOND_MULTIPLIER_BPS"
    "MIN_BOND"
    "CHALLENGE_WINDOW_SECONDS"
    "LP_FEE_BPS"
    "MIN_LIQUIDITY_RATIO_BPS"
    "USD_PEG_THRESHOLD_BPS"
    "ETH_PEG_THRESHOLD_BPS"
    "COMMODITY_PEG_THRESHOLD_BPS"
    "MIN_RESERVE_RATIO_BPS"
    "LIQUIDITY_AMOUNT"
    "RESERVE_AMOUNT"
    "XAU_ADDRESS"
    "MARKET_REPORTING_API_KEY"
)

for var in "${OPTIONAL_VARS[@]}"; do
    if [ ! -z "${!var}" ]; then
        echo "✓ $var: ${!var}"
    else
        echo "○ $var: Not set (using default)"
    fi
done

echo ""
echo "=== Summary ==="
echo ""

if [ ${#MISSING_REQUIRED[@]} -eq 0 ]; then
    echo "✓ All required variables are set"
    echo "  Ready to start deployment"
else
    echo "✗ Missing required variables:"
    for var in "${MISSING_REQUIRED[@]}"; do
        echo "  - $var"
    done
    echo ""
    echo "Please set these variables in .env file before deployment"
fi

echo ""
echo "=== External Dependency Blockers ==="
echo ""
if ! bash "$PROJECT_ROOT/scripts/verify/check-external-dependencies.sh" --advisory; then
    true
fi

echo ""
echo "=== Next Steps ==="
echo ""

if [ ${#MISSING_REQUIRED[@]} -eq 0 ]; then
    echo "1. Run: ./scripts/deployment/phase1-env-setup.sh"
    echo "2. Then proceed with deployment phases"
else
    echo "1. Create/update .env file with required variables"
    echo "2. Run this script again to verify"
    echo "3. Then proceed with deployment"
fi

echo ""
