#!/usr/bin/env bash

# Deploy all CCIP contracts to Ethereum Mainnet
# This script deploys CCIPLogger which receives Chain-138 transactions

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"


# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
else
    log_error "Error: .env file not found"
    exit 1
fi

log_info "=== Deploying CCIP Contracts to Ethereum Mainnet ==="

# Check prerequisites
if [ -z "$PRIVATE_KEY" ]; then
    log_error "Error: PRIVATE_KEY not set in .env"
    exit 1
fi

if [ -z "$ETHEREUM_MAINNET_RPC" ]; then
    log_warn "Warning: ETHEREUM_MAINNET_RPC not set, using default"
fi

# Configuration
CCIP_ETH_ROUTER="${CCIP_ETH_ROUTER:-0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D}"
AUTHORIZED_SIGNER="${AUTHORIZED_SIGNER:-}"
CHAIN138_SELECTOR="${CHAIN138_SELECTOR:-0x000000000000008a}"

echo "Configuration:"
echo "  CCIP Router (Ethereum): $CCIP_ETH_ROUTER"
echo "  Authorized Signer: ${AUTHORIZED_SIGNER:-Not set (optional)}"
echo "  Chain-138 Selector: $CHAIN138_SELECTOR"

# Deploy CCIPLogger
log_warn "Deploying CCIPLogger..."
export CCIP_ETH_ROUTER
export AUTHORIZED_SIGNER
export CHAIN138_SELECTOR

npx hardhat run scripts/ccip-deployment/deploy-ccip-logger.js --network mainnet

CCIP_LOGGER_ADDRESS=$(grep "CCIPLogger deployed to:" <<< "$(npx hardhat run scripts/ccip-deployment/deploy-ccip-logger.js --network mainnet 2>&1)" | awk '{print $NF}')

if [ -z "$CCIP_LOGGER_ADDRESS" ]; then
    log_error "Error: Failed to extract CCIPLogger address"
    exit 1
fi

log_success "✅ CCIPLogger deployed: $CCIP_LOGGER_ADDRESS"

# Update .env
log_warn "Updating .env file..."
if grep -q "CCIP_LOGGER_ETH_ADDRESS=" "$PROJECT_ROOT/.env"; then
    sed -i "s|CCIP_LOGGER_ETH_ADDRESS=.*|CCIP_LOGGER_ETH_ADDRESS=$CCIP_LOGGER_ADDRESS|" "$PROJECT_ROOT/.env"
else
    echo "CCIP_LOGGER_ETH_ADDRESS=$CCIP_LOGGER_ADDRESS" >> "$PROJECT_ROOT/.env"
fi

if ! grep -q "CCIP_ETH_ROUTER=" "$PROJECT_ROOT/.env"; then
    echo "CCIP_ETH_ROUTER=$CCIP_ETH_ROUTER" >> "$PROJECT_ROOT/.env"
fi

if ! grep -q "CHAIN138_SELECTOR=" "$PROJECT_ROOT/.env"; then
    echo "CHAIN138_SELECTOR=$CHAIN138_SELECTOR" >> "$PROJECT_ROOT/.env"
fi

log_success "✅ .env file updated"

log_info "=== Deployment Summary ==="
echo "Deployed Contracts:"
echo "  CCIPLogger: $CCIP_LOGGER_ADDRESS"
echo "Next Steps:"
echo "  1. Verify contract on Etherscan"
echo "  2. Set CHAIN138_CCIP_REPORTER for the historical Chain-138 sender if that flow is still active"
echo "     Archived source: archive/solidity/contracts/ccip-integration/CCIPTxReporter.sol"
echo "  3. Configure watcher/relayer service"
echo "  4. Start monitoring"
