#!/usr/bin/env bash
# Chainlist Submission Script - ChainID 138
# This script prepares the chain-138.json file for Chainlist submission

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHAIN_FILE="$SCRIPT_DIR/chain-138.json"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

log_info "=== Chainlist Submission Preparation ==="
log_info ""

# Validate JSON
log_info "1. Validating chain-138.json..."
if python3 -c "import json; json.load(open('$CHAIN_FILE'))" 2>/dev/null; then
    log_success "  JSON is valid"
else
    log_warn "  JSON validation failed"
    exit 1
fi

# Check required fields
log_info ""
log_info "2. Checking required fields..."
python3 << 'PYTHON'
import json
import sys

try:
    with open('chain-138.json', 'r') as f:
        data = json.load(f)
    
    required = ['name', 'shortName', 'chain', 'chainId', 'networkId', 'rpc', 'faucets', 'infoURL', 'nativeCurrency']
    missing = [field for field in required if field not in data]
    
    if missing:
        print(f"  ❌ Missing required fields: {missing}")
        sys.exit(1)
    else:
        print("  ✅ All required fields present")
    
    # Check nativeCurrency
    if 'nativeCurrency' in data:
        nc_required = ['name', 'symbol', 'decimals']
        nc_missing = [field for field in nc_required if field not in data['nativeCurrency']]
        if nc_missing:
            print(f"  ❌ NativeCurrency missing: {nc_missing}")
            sys.exit(1)
        else:
            print("  ✅ NativeCurrency complete")
    
    print(f"\n  Chain: {data.get('name', 'N/A')}")
    print(f"  ChainID: {data.get('chainId', 'N/A')}")
    print(f"  RPC URLs: {len(data.get('rpc', []))}")
    print(f"  Explorers: {len(data.get('explorers', []))}")
    
except Exception as e:
    print(f"  ❌ Error: {e}")
    sys.exit(1)
PYTHON

log_info ""
log_success "=== Chainlist Configuration Validated ==="
log_info ""

# Instructions
log_info "Next Steps:"
log_info "1. Fork Chainlist repository: https://github.com/ethereum-lists/chains"
log_info "2. Clone your fork: git clone https://github.com/YOUR_USERNAME/chains.git"
log_info "3. Create branch: git checkout -b add-dbis-chain-138"
log_info "4. Copy file: cp $CHAIN_FILE chains/_data/chains/eip155-138.json"
log_info "5. Commit: git add _data/chains/eip155-138.json && git commit -m 'Add DBIS Chain (ChainID 138)'"
log_info "6. Push: git push origin add-dbis-chain-138"
log_info "7. Create PR: Visit GitHub and create pull request"
log_info ""
log_info "See CHAINLIST_PR_TEMPLATE.md for PR description template"
