#!/bin/bash

# Start Deployment Process
# This script initiates the deployment with proper checks

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 "=========================================="
echo "  Trustless Bridge Deployment"
echo "=========================================="
echo ""

# Check prerequisites
echo "=== Pre-Deployment Checks ==="
echo ""

# Check Foundry
if ! command -v forge &> /dev/null; then
    echo "✗ Error: Foundry/Forge not installed"
    echo "  Install with: curl -L https://foundry.paradigm.xyz | bash && foundryup"
    exit 1
fi
echo "✓ Foundry installed"

# Check required variables
MISSING=0
for var in PRIVATE_KEY ETHEREUM_MAINNET_RPC RPC_URL_138 ETHERSCAN_API_KEY; do
    if [ -z "${!var:-}" ] || [ "${!var:-}" == "0x..." ] || [ "${!var:-}" == "your_etherscan_api_key" ]; then
        echo "✗ $var: Not set"
        MISSING=1
    fi
done

if [ $MISSING -eq 1 ]; then
    echo ""
    echo "Error: Missing required environment variables"
    echo "Run: ./scripts/deployment/check-env-requirements.sh"
    exit 1
fi
echo "✓ Required variables set"

echo ""
echo "=== Ready to Deploy ==="
echo ""
echo "This will deploy contracts to:"
echo "  - Ethereum Mainnet: $ETHEREUM_MAINNET_RPC"
echo "  - ChainID 138: $RPC_URL_138"
echo ""
echo "⚠️  WARNING: This will use real ETH for gas fees!"
echo ""
read -p "Continue with deployment? (yes/no): " -r
echo ""

if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
    echo "Deployment cancelled"
    exit 0
fi

echo ""
echo "Starting deployment process..."
echo ""

# Run the deployment script
exec ./scripts/deployment/deploy-all-phases.sh
