#!/usr/bin/env bash
# Configure LINK Token for ChainID 138
# Uses Ethereum Mainnet canonical LINK token address
# Updates: .env, token lists, CCIP configs, and database

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

# Ethereum Mainnet canonical LINK token address
LINK_TOKEN_MAINNET="0x514910771AF9Ca656af840dff83E8264EcF986CA"
CCIP_ROUTER="$(resolve_address_value CCIP_ROUTER_ADDRESS CCIP_ROUTER_ADDRESS 0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817)"
CHAIN_ID=138

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     CONFIGURE LINK TOKEN FOR CHAINID 138                     ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "LINK Token Address: $LINK_TOKEN_MAINNET"
echo "Chain ID: $CHAIN_ID"
echo ""

# Step 1: Update address inventory
echo "=== Step 1: Updating address inventory ==="
if [ -f "$EXPLORER_ADDRESS_INVENTORY_FILE" ]; then
    persist_inventory_value "LINK_TOKEN" "$LINK_TOKEN_MAINNET"
    persist_inventory_value "LINK_TOKEN_138" "$LINK_TOKEN_MAINNET"
    persist_inventory_value "LINK_TOKEN_MAINNET" "$LINK_TOKEN_MAINNET"
    persist_inventory_value "CCIP_CHAIN138_FEE_TOKEN" "$LINK_TOKEN_MAINNET"
    echo "✓ Updated config/address-inventory.json"
else
    echo "⚠ Address inventory not found at $EXPLORER_ADDRESS_INVENTORY_FILE"
fi
echo ""

# Step 2: Update token list files
echo "=== Step 2: Updating token lists ==="

# Update dbis-138.tokenlist.json
TOKEN_LIST_FILE="$PROJECT_ROOT/../token-lists/lists/dbis-138.tokenlist.json"
if [ -f "$TOKEN_LIST_FILE" ]; then
    # Check if LINK already exists
    if grep -q "$LINK_TOKEN_MAINNET" "$TOKEN_LIST_FILE"; then
        echo "✓ LINK token already in dbis-138.tokenlist.json"
    else
        # Use jq to add LINK token
        if command -v jq &> /dev/null; then
            jq --arg address "$LINK_TOKEN_MAINNET" --arg chainId "$CHAIN_ID" '
                .tokens += [{
                    "chainId": ($chainId | tonumber),
                    "address": $address,
                    "name": "Chainlink Token",
                    "symbol": "LINK",
                    "decimals": 18,
                    "logoURI": "https://raw.githubusercontent.com/chainlink/chainlink-docs/main/docs/images/chainlink-logo.svg",
                    "tags": ["defi", "oracle", "ccip"]
                }] |
                .version.patch += 1 |
                .timestamp = (now | strftime("%Y-%m-%dT%H:%M:%S.000Z"))
            ' "$TOKEN_LIST_FILE" > "${TOKEN_LIST_FILE}.tmp" && mv "${TOKEN_LIST_FILE}.tmp" "$TOKEN_LIST_FILE"
            echo "✓ Added LINK token to dbis-138.tokenlist.json"
        else
            echo "⚠ jq not found, skipping token list update"
        fi
    fi
else
    echo "⚠ Token list file not found at $TOKEN_LIST_FILE"
fi

# Update token-list.json
TOKEN_LIST_FILE2="$PROJECT_ROOT/../token-list.json"
if [ -f "$TOKEN_LIST_FILE2" ]; then
    if grep -q "$LINK_TOKEN_MAINNET" "$TOKEN_LIST_FILE2"; then
        echo "✓ LINK token already in token-list.json"
    else
        if command -v jq &> /dev/null; then
            jq --arg address "$LINK_TOKEN_MAINNET" --arg chainId "$CHAIN_ID" '
                .tokens += [{
                    "chainId": ($chainId | tonumber),
                    "address": $address,
                    "name": "Chainlink Token",
                    "symbol": "LINK",
                    "decimals": 18,
                    "logoURI": "https://raw.githubusercontent.com/chainlink/chainlink-docs/main/docs/images/chainlink-logo.svg",
                    "tags": ["defi", "oracle", "ccip"]
                }] |
                .version.patch += 1 |
                .timestamp = (now | strftime("%Y-%m-%dT%H:%M:%S.000Z"))
            ' "$TOKEN_LIST_FILE2" > "${TOKEN_LIST_FILE2}.tmp" && mv "${TOKEN_LIST_FILE2}.tmp" "$TOKEN_LIST_FILE2"
            echo "✓ Added LINK token to token-list.json"
        fi
    fi
fi
echo ""

# Step 3: Add to database
echo "=== Step 3: Adding LINK token to database ==="

DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-explorer}"
DB_USER="${DB_USER:-postgres}"
DB_PASSWORD="${DB_PASSWORD:-}"

if [ -n "$DB_PASSWORD" ]; then
    export PGPASSWORD="$DB_PASSWORD"
fi

# Insert or update LINK token in database
psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" <<EOF 2>/dev/null || echo "⚠ Database update skipped (database may not be accessible)"
INSERT INTO tokens (chain_id, address, type, name, symbol, decimals, verified, description)
VALUES ($CHAIN_ID, '$LINK_TOKEN_MAINNET', 'ERC20', 'Chainlink Token', 'LINK', 18, true, 'Official Chainlink LINK token from Ethereum Mainnet. Used for CCIP fees and Chainlink services.')
ON CONFLICT (chain_id, address) DO UPDATE SET
    name = EXCLUDED.name,
    symbol = EXCLUDED.symbol,
    decimals = EXCLUDED.decimals,
    verified = EXCLUDED.verified,
    description = EXCLUDED.description,
    updated_at = NOW();
EOF

if [ $? -eq 0 ]; then
    echo "✓ LINK token added to database"
else
    echo "⚠ Database update skipped (run manually if needed)"
fi
echo ""

# Step 4: Update CCIP documentation
echo "=== Step 4: Updating CCIP documentation ==="
CCIP_DOC="$PROJECT_ROOT/docs/CCIP_ROUTER_CONFIGURATION.md"
if [ -f "$CCIP_DOC" ]; then
    if grep -q "Fee Token.*0x514910771AF9Ca656af840dff83E8264EcF986CA" "$CCIP_DOC"; then
        echo "✓ CCIP documentation already has correct LINK address"
    else
        sed -i "s|Fee Token.*0x[0-9a-fA-F]\{40\}|Fee Token: \`$LINK_TOKEN_MAINNET\` (LINK)|g" "$CCIP_DOC" 2>/dev/null || true
        echo "✓ Updated CCIP documentation"
    fi
fi
echo ""

# Step 5: Summary
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     CONFIGURATION COMPLETE                                    ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "LINK Token Address: $LINK_TOKEN_MAINNET"
echo ""
echo "Updated:"
echo "  ✓ Address inventory (LINK_TOKEN and CCIP_CHAIN138_FEE_TOKEN)"
echo "  ✓ Token list files (dbis-138.tokenlist.json, token-list.json)"
echo "  ✓ Database tokens table (if accessible)"
echo "  ✓ CCIP documentation"
echo ""
echo "Next steps:"
echo "  1. Verify LINK token on ChainID 138:"
echo "     cast code $LINK_TOKEN_MAINNET --rpc-url <RPC_URL>"
echo ""
echo "  2. Check CCIP Router fee token:"
echo "     cast call $CCIP_ROUTER \"getFeeToken()\" --rpc-url <RPC_URL>"
echo ""
echo "  3. Fund bridge contracts with LINK if needed:"
echo "     ./scripts/fund-bridge-contracts.sh 10"
echo ""
