#!/usr/bin/env bash
# Submit Ethereum Lists PR Script
# Automates the creation of a PR to ethereum-lists/chains for ChainID 138

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
CHAIN_DATA_FILE="${PROJECT_ROOT}/metamask/ethereum-lists-chain.json"
PR_TEMPLATE="${PROJECT_ROOT}/metamask/ethereum-lists-pr.md"
TEMP_DIR=$(mktemp -d)
ETHEREUM_LISTS_REPO="https://github.com/ethereum-lists/chains.git"
FORK_REPO=""
BRANCH_NAME="add-chainid-138"

# 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"
}

# Check prerequisites
check_prerequisites() {
    log "Checking prerequisites..."
    
    local missing=0
    
    # Check required tools
    for cmd in git gh jq; do
        if ! command -v "$cmd" &> /dev/null; then
            error "$cmd is not installed"
            missing=1
        fi
    done
    
    # Check GitHub CLI authentication
    if ! gh auth status &> /dev/null; then
        error "GitHub CLI is not authenticated. Run 'gh auth login'"
    fi
    
    if [ $missing -eq 0 ]; then
        log "All prerequisites met"
    fi
}

# Clone ethereum-lists repository
clone_repo() {
    log "Cloning ethereum-lists repository..."
    
    cd "$TEMP_DIR" || error "Failed to change directory to temp directory"
    
    git clone "$ETHEREUM_LISTS_REPO" ethereum-lists || error "Failed to clone repository"
    cd ethereum-lists || error "Failed to change directory to ethereum-lists"
    
    # Create and checkout new branch
    git checkout -b "$BRANCH_NAME" || error "Failed to create branch"
    
    log "Repository cloned and branch created"
}

# Add chain data
add_chain_data() {
    log "Adding chain data..."
    
    cd "$TEMP_DIR/ethereum-lists" || error "Failed to change directory"
    
    # Copy chain data file
    if [ ! -f "$CHAIN_DATA_FILE" ]; then
        error "Chain data file not found: $CHAIN_DATA_FILE"
    fi
    
    # Validate chain data
    if ! jq empty "$CHAIN_DATA_FILE" 2>/dev/null; then
        error "Chain data JSON is invalid"
    fi
    
    # Copy to _data/chains directory
    mkdir -p _data/chains
    cp "$CHAIN_DATA_FILE" "_data/chains/e138.json" || error "Failed to copy chain data file"
    
    log "Chain data added"
}

# Create PR
create_pr() {
    log "Creating PR..."
    
    cd "$TEMP_DIR/ethereum-lists" || error "Failed to change directory"
    
    # Commit changes
    git add _data/chains/e138.json || error "Failed to stage changes"
    git commit -m "Add ChainID 138 - DeFi Oracle Meta Mainnet" || error "Failed to commit changes"
    
    # Get fork repository URL
    if [ -z "$FORK_REPO" ]; then
        # Create fork if it doesn't exist
        log "Creating fork..."
        FORK_REPO=$(gh repo fork ethereum-lists/chains --clone=false --remote-name=origin 2>&1 | grep -oP 'https://github.com/[^/]+/chains\.git' || echo "")
        
        if [ -z "$FORK_REPO" ]; then
            # Fork may already exist, get the URL
            FORK_REPO=$(gh repo view --json url -q .url)/chains.git || error "Failed to get fork URL"
        fi
    fi
    
    # Add fork as remote
    git remote add fork "$FORK_REPO" || warn "Fork remote may already exist"
    git remote set-url fork "$FORK_REPO" || error "Failed to set fork remote URL"
    
    # Push to fork
    log "Pushing to fork..."
    git push fork "$BRANCH_NAME" || error "Failed to push to fork"
    
    # Create PR
    log "Creating pull request..."
    PR_URL=$(gh pr create \
        --repo ethereum-lists/chains \
        --head "$(gh api user --jq .login):$BRANCH_NAME" \
        --title "Add ChainID 138 - DeFi Oracle Meta Mainnet" \
        --body-file "$PR_TEMPLATE" \
        --web) || error "Failed to create PR"
    
    log "PR created: $PR_URL"
    echo "$PR_URL"
}

# Main function
main() {
    log "Starting Ethereum Lists PR submission..."
    
    # Step 1: Check prerequisites
    check_prerequisites
    
    # Step 2: Clone repository
    clone_repo
    
    # Step 3: Add chain data
    add_chain_data
    
    # Step 4: Create PR
    PR_URL=$(create_pr)
    
    log "Ethereum Lists PR submission completed"
    log "PR URL: $PR_URL"
    log "Next steps:"
    log "  1. Review the PR on GitHub"
    log "  2. Wait for maintainer review"
    log "  3. Merge after approval"
    
    # Cleanup
    rm -rf "$TEMP_DIR"
}

# Run main function
main "$@"

