#!/usr/bin/env bash
# Complete All Prerequisites - One Script to Rule Them All
# Deploys LINK token, mints tokens, and funds bridges
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"
load_explorer_runtime_env

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN "")"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"
ACCOUNT=$(cast wallet address "$PRIVATE_KEY")

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     COMPLETE ALL PREREQUISITES                               ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Account: $ACCOUNT"
echo "RPC: $RPC_URL"
echo ""

# Step 1: Check if LINK token exists and is confirmed
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 already deployed: $LINK_TOKEN"
        LINK_CONFIRMED=true
    else
        echo "⏳ LINK Token not yet confirmed: $LINK_TOKEN"
        LINK_CONFIRMED=false
    fi
else
    echo "❌ LINK Token not configured"
    LINK_CONFIRMED=false
fi

# Step 2: Deploy LINK token if not confirmed
if [ "${LINK_CONFIRMED:-false}" != "true" ]; then
    echo ""
    echo "=== Deploying LINK Token ==="
    DEPLOY_OUTPUT=$("$SCRIPT_DIR/force-deploy-link.sh" $(cast --to-wei 10 gwei) 2>&1 || true)
    echo "$DEPLOY_OUTPUT"
    
    # Extract deployed address
    NEW_LINK=$(echo "$DEPLOY_OUTPUT" | grep -oE "0x[0-9a-fA-F]{40}" | head -1 || echo "")
    
    if [ -n "$NEW_LINK" ] && [ ${#NEW_LINK} -eq 42 ]; then
        echo ""
        echo "✓ Deployment transaction sent: $NEW_LINK"
        echo "Waiting 60 seconds for network confirmation..."
        sleep 60
        
        # Keep address inventory as the script-facing source of truth for addresses.
        persist_inventory_value "LINK_TOKEN" "$NEW_LINK" || true
        persist_inventory_value "CCIP_CHAIN138_FEE_TOKEN" "$NEW_LINK" || true
        export LINK_TOKEN="$NEW_LINK"
        
        # Verify
        CODE=$(cast code "$NEW_LINK" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
            echo "✅ LINK Token confirmed!"
            LINK_CONFIRMED=true
        else
            echo "⏳ Still waiting for confirmation..."
            echo "   Check with: cast code $NEW_LINK --rpc-url $RPC_URL"
            exit 0
        fi
    else
        echo ""
        echo "❌ Deployment failed. Check output above."
        echo "   Try manual deployment: ./scripts/deploy-via-remix-instructions.sh"
        exit 1
    fi
fi

# Step 3: Mint tokens if balance is low
if [ "${LINK_CONFIRMED:-false}" = "true" ]; then
    echo ""
    echo "=== Checking LINK Balance ==="
    BALANCE=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    BALANCE_ETH=$(cast --from-wei "$BALANCE" ether 2>/dev/null || echo "0")
    echo "Current Balance: $BALANCE_ETH LINK"
    
    if (( $(echo "$BALANCE_ETH < 20" | bc -l 2>/dev/null || echo 1) )); then
        echo ""
        echo "=== Minting 1M LINK Tokens ==="
        MINT_AMOUNT="1000000000000000000000000"
        cast send "$LINK_TOKEN" "mint(address,uint256)" "$ACCOUNT" "$MINT_AMOUNT" \
            --rpc-url "$RPC_URL" \
            --private-key "$PRIVATE_KEY" \
            --gas-price $(cast --to-wei 10 gwei) \
            --legacy \
            2>&1 | tail -5
        
        echo "Waiting 20 seconds for mint confirmation..."
        sleep 20
        
        BALANCE=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        BALANCE_ETH=$(cast --from-wei "$BALANCE" ether 2>/dev/null || echo "0")
        echo "New Balance: $BALANCE_ETH LINK"
    else
        echo "✓ Sufficient balance"
    fi
fi

# Step 4: Fund bridges
if [ "${LINK_CONFIRMED:-false}" = "true" ]; then
    echo ""
    echo "=== Funding Bridge Contracts ==="
    export LINK_TOKEN
    "$SCRIPT_DIR/fund-bridge-contracts.sh" 10 2>&1 | tail -25
    
    echo ""
    echo "=== Verifying Bridge Funding ==="
    WETH9_LINK=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH9_LINK_ETH=$(cast --from-wei "$WETH9_LINK" ether 2>/dev/null || echo "0")
    WETH10_LINK=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH10_LINK_ETH=$(cast --from-wei "$WETH10_LINK" ether 2>/dev/null || echo "0")
    
    echo "WETH9 Bridge: $WETH9_LINK_ETH LINK"
    echo "WETH10 Bridge: $WETH10_LINK_ETH LINK"
    
    if (( $(echo "$WETH9_LINK_ETH >= 10" | bc -l 2>/dev/null || echo 0) )) && \
       (( $(echo "$WETH10_LINK_ETH >= 10" | bc -l 2>/dev/null || echo 0) )); then
        echo ""
        echo "✅✅✅ ALL PREREQUISITES COMPLETE!"
        echo "   ✓ LINK token deployed"
        echo "   ✓ LINK tokens minted"
        echo "   ✓ Bridges funded"
        echo ""
        echo "🎉 SYSTEM FULLY OPERATIONAL!"
    else
        echo ""
        echo "⚠ Some bridges may still need funding"
    fi
fi

echo ""
