#!/usr/bin/env bash
# Update Token List Script
# Updates token-list.json with deployed contract addresses

set -euo pipefail


# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
CONTRACT_ADDRESSES_FILE="${PROJECT_ROOT}/contracts-deployed.json"
TOKEN_LIST_FILE="${PROJECT_ROOT}/metamask/token-list.json"

# Logging function
log() {
    log_success "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

error() {
    log_error "[ERROR] $1"
    exit 1
}

warn() {
    log_warn "[WARNING] $1"
}

# Validate contract address
validate_address() {
    local address=$1
    if [[ ! "$address" =~ ^0x[a-fA-F0-9]{40}$ ]]; then
        return 1
    fi
    return 0
}

# Update token in token list
update_token() {
    local token_address=$1
    local token_symbol=$2
    local token_name=$3
    local token_decimals=${4:-18}
    local token_logo=${5:-}
    
    if ! validate_address "$token_address"; then
        error "Invalid token address: $token_address"
    fi
    
    log "Updating token: $token_symbol ($token_name) at $token_address"
    
    # Check if token already exists in list
    local token_exists=$(jq -r ".tokens[] | select(.address == \"$token_address\") | .address" "$TOKEN_LIST_FILE")
    
    if [ -n "$token_exists" ]; then
        log "Token already exists in list, updating..."
        # Update existing token
        jq --arg address "$token_address" \
           --arg symbol "$token_symbol" \
           --arg name "$token_name" \
           --argjson decimals "$token_decimals" \
           --arg logo "$token_logo" \
           '(.tokens[] | select(.address == $address)) |= . + {
               symbol: $symbol,
               name: $name,
               decimals: $decimals,
               logoURI: $logo
           }' "$TOKEN_LIST_FILE" > "${TOKEN_LIST_FILE}.tmp" && \
        mv "${TOKEN_LIST_FILE}.tmp" "$TOKEN_LIST_FILE"
    else
        log "Adding new token to list..."
        # Add new token
        local new_token=$(jq -n \
            --argjson chainId 138 \
            --arg address "$token_address" \
            --arg name "$token_name" \
            --arg symbol "$token_symbol" \
            --argjson decimals "$token_decimals" \
            --arg logo "$token_logo" \
            '{
                chainId: $chainId,
                address: $address,
                name: $name,
                symbol: $symbol,
                decimals: $decimals,
                logoURI: $logo
            }')
        
        jq ".tokens += [$new_token]" "$TOKEN_LIST_FILE" > "${TOKEN_LIST_FILE}.tmp" && \
        mv "${TOKEN_LIST_FILE}.tmp" "$TOKEN_LIST_FILE"
    fi
    
    # Update timestamp
    jq ".timestamp = \"$(date -u +%Y-%m-%dT%H:%M:%S.000Z)\"" "$TOKEN_LIST_FILE" > "${TOKEN_LIST_FILE}.tmp" && \
    mv "${TOKEN_LIST_FILE}.tmp" "$TOKEN_LIST_FILE"
    
    log "Token updated successfully"
}

# Validate token list
validate_token_list() {
    log "Validating token list..."
    
    # Validate JSON schema
    if command -v ajv &> /dev/null; then
        if ajv validate -s "${PROJECT_ROOT}/metamask/token-list.schema.json" -d "$TOKEN_LIST_FILE"; then
            log "Token list schema validation passed"
        else
            error "Token list schema validation failed"
        fi
    else
        warn "ajv-cli not installed, skipping schema validation"
    fi
    
    # Validate JSON syntax
    if jq empty "$TOKEN_LIST_FILE" 2>/dev/null; then
        log "Token list JSON syntax is valid"
    else
        error "Token list JSON syntax is invalid"
    fi
}

# Main function
main() {
    log "Updating token list..."
    
    # Check if contract addresses file exists
    if [ ! -f "$CONTRACT_ADDRESSES_FILE" ]; then
        error "Contract addresses file not found: $CONTRACT_ADDRESSES_FILE"
    fi
    
    # Check if token list file exists
    if [ ! -f "$TOKEN_LIST_FILE" ]; then
        error "Token list file not found: $TOKEN_LIST_FILE"
    fi
    
    # Read contract addresses
    WETH_ADDRESS=$(jq -r '.weth // empty' "$CONTRACT_ADDRESSES_FILE")
    
    # Update WETH token
    if [ -n "$WETH_ADDRESS" ] && [ "$WETH_ADDRESS" != "null" ]; then
        update_token \
            "$WETH_ADDRESS" \
            "WETH" \
            "Wrapped Ether" \
            18 \
            "https://explorer.d-bis.org/images/tokens/weth.png"
    else
        warn "WETH address not found in contract addresses file"
    fi
    
    # Validate token list
    validate_token_list
    
    log "Token list updated successfully"
    log "Token list file: $TOKEN_LIST_FILE"
    log "Next steps:"
    log "  1. Commit token list changes: git add $TOKEN_LIST_FILE && git commit -m 'Update token list with deployed addresses'"
    log "  2. Submit token list: ./scripts/deployment/submit-token-list.sh"
}

# Run main function
main "$@"

