#!/bin/bash
# Comprehensive LINK token deployment with all methods and fallbacks
# Tries all options from the fix report in order

set -euo pipefail

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

load_explorer_runtime_env

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")

if [ -z "$ACCOUNT" ]; then
    echo "Error: PRIVATE_KEY not set or invalid"
    exit 1
fi

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     COMPREHENSIVE LINK TOKEN DEPLOYMENT                       ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "This script implements all fixes from LINK_TOKEN_DEPLOYMENT_FIX_REPORT.md"
echo ""
echo "Account: $ACCOUNT"
echo "RPC: $RPC_URL"
echo ""

# Step 1: Check Block Explorer for existing transactions
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     STEP 1: Check Block Explorer                             ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Checking recent transactions..."
./scripts/check-block-explorer-tx.sh "" "$ACCOUNT" 2>&1 | tail -15
echo ""
read -p "Press Enter to continue to next step..." || true
echo ""

# Step 2: Use Existing LINK Token (Option 2)
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     STEP 2: Check for Existing LINK Token                     ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
if ./scripts/diagnose-link-deployment.sh 2>&1 | grep -q "Using Existing LINK Token"; then
    echo "✓✓✓ Found existing LINK token!"
    load_explorer_runtime_env
    LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN "")"
    if [ -n "$LINK_TOKEN" ] && [ ${#LINK_TOKEN} -eq 42 ]; then
        CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
            echo "✓ LINK token confirmed: $LINK_TOKEN"
            echo ""
            echo "Skipping deployment - using existing token"
            exit 0
        fi
    fi
else
    echo "No existing LINK token found"
fi
echo ""

# Step 3: Check Network Restrictions (Option 4)
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     STEP 3: Check Network Restrictions                        ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Testing if network allows contract creation..."
./scripts/check-network-restrictions.sh 2>&1 | tail -20
echo ""
read -p "Press Enter to continue to deployment..." || true
echo ""

# Step 4: Deploy with Enhanced Methods
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     STEP 4: Deploy MockLinkToken                             ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Attempting deployment with enhanced script..."
FORCE_GAS="5000000000"  # 5 gwei
./scripts/force-deploy-link.sh "$FORCE_GAS" 2>&1 | head -40

# Wait and verify
echo ""
echo "Waiting 45 seconds for network confirmation..."
sleep 45

load_explorer_runtime_env
LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN "")"
if [ -n "$LINK_TOKEN" ] && [ ${#LINK_TOKEN} -eq 42 ]; then
    CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
        echo ""
        echo "✓✓✓ LINK token CONFIRMED!"
        echo "Address: $LINK_TOKEN"
        echo ""
        echo "Proceeding to mint and fund bridges..."
        ./scripts/fund-bridge-contracts.sh 10 2>&1 | tail -30
        exit 0
    fi
fi

# Step 5: Remix IDE Instructions (Option 3)
echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     STEP 5: Alternative - Remix IDE Deployment              ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Deployment not confirmed. Use Remix IDE as alternative:"
echo ""
./scripts/deploy-via-remix-instructions.sh
echo ""

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     SUMMARY                                                  ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "All deployment methods attempted:"
echo "  ✓ Block explorer check"
echo "  ✓ Existing token check"
echo "  ✓ Network restriction check"
echo "  ✓ Enhanced deployment (5 gwei)"
echo "  ⚠ Remix IDE instructions provided"
echo ""
echo "If deployment still pending:"
echo "  1. Wait additional time (5-10 minutes)"
echo "  2. Use Remix IDE (instructions above)"
echo "  3. Check block explorer: https://explorer.d-bis.org/address/$ACCOUNT"
echo ""
