#!/bin/bash
# Script to set up repositories for creating pull requests
# This clones repos separately (not as submodules) for easier PR workflow

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PR_WORKSPACE="${PROJECT_ROOT}/../pr-workspace"

# Colors
RED='\033[0;31m'
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_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "========================================="
log_info "Setting up PR Workspace"
log_info "========================================="
log_info ""

# Create PR workspace directory
mkdir -p "$PR_WORKSPACE"
cd "$PR_WORKSPACE"

# Repositories to set up
# Format: repo_name|repo_url|branch_name (using | instead of : to avoid URL conflicts)
REPOS=(
    "ethereum-lists/chains|https://github.com/ethereum-lists/chains.git|update-chainid-138-rpc-endpoints"
    "Defi-Oracle-Meta-Blockchain/Cross-Chain-Mirroring|https://github.com/Defi-Oracle-Meta-Blockchain/Cross-Chain-Mirroring.git|update-chainid-138-rpc-endpoints"
    "Defi-Oracle-Meta-Blockchain/app-ethereum|https://github.com/Defi-Oracle-Meta-Blockchain/app-ethereum.git|add-chainid-138-support"
)

log_info "PR Workspace: $PR_WORKSPACE"
log_info ""
log_warn "IMPORTANT: You need to fork these repositories first!"
log_warn "1. Go to each repository on GitHub"
log_warn "2. Click 'Fork' to create your fork"
log_warn "3. Then run this script with your GitHub username"
log_info ""

# Get GitHub username
read -p "Enter your GitHub username: " GITHUB_USERNAME
if [ -z "$GITHUB_USERNAME" ]; then
    log_error "GitHub username is required"
    exit 1
fi

log_info ""
log_info "Setting up repositories..."
log_info ""

for repo_info in "${REPOS[@]}"; do
    IFS='|' read -r repo_name repo_url branch_name <<< "$repo_info"
    
    log_info "Processing: $repo_name"
    
    # Extract repo directory name from URL
    # Example: https://github.com/ethereum-lists/chains.git -> chains
    if [[ "$repo_url" =~ github\.com[:/][^/]+/([^/]+)\.git$ ]]; then
        repo_dir="${BASH_REMATCH[1]}"
    else
        # Fallback: extract last component before .git
        repo_dir=$(echo "$repo_url" | sed 's|.*/||' | sed 's|\.git$||')
    fi
    
    # Check if already cloned
    if [ -d "$repo_dir" ]; then
        log_warn "  Repository already exists: $repo_dir"
        read -p "  Remove and re-clone? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            rm -rf "$repo_dir"
        else
            log_info "  Skipping $repo_dir"
            continue
        fi
    fi
    
    # Clone from user's fork (or original if fork doesn't exist)
    FORK_URL="https://github.com/${GITHUB_USERNAME}/${repo_dir}.git"
    ORIGINAL_URL="$repo_url"
    
    log_info "  Attempting to clone from fork: $FORK_URL"
    if git clone "$FORK_URL" "$repo_dir" 2>/dev/null; then
        log_success "  Cloned from fork: $FORK_URL"
        cd "$repo_dir"
        
        # Add upstream remote
        git remote add upstream "$ORIGINAL_URL" 2>/dev/null || git remote set-url upstream "$ORIGINAL_URL"
        log_success "  Added upstream remote"
        
    else
        log_warn "  Fork not found, cloning from original"
        if git clone "$ORIGINAL_URL" "$repo_dir"; then
            log_success "  Cloned from original: $ORIGINAL_URL"
            cd "$repo_dir"
            log_warn "  Remember to fork this repository and update remote!"
        else
            log_error "  Failed to clone $repo_name"
            continue
        fi
    fi
    
    # Create branch for PR
    if git checkout -b "$branch_name" 2>/dev/null; then
        log_success "  Created branch: $branch_name"
    else
        log_warn "  Branch already exists or on different branch"
        git checkout "$branch_name" 2>/dev/null || log_warn "  Could not checkout branch"
    fi
    
    cd "$PR_WORKSPACE"
    log_info ""
done

log_success "========================================="
log_success "Setup Complete!"
log_success "========================================="
log_info ""
log_info "Next steps:"
log_info "1. Review each repository in: $PR_WORKSPACE"
log_info "2. Make your changes"
log_info "3. Commit and push:"
log_info "   cd pr-workspace/<repo>"
log_info "   git add ."
log_info "   git commit -m 'Your commit message'"
log_info "   git push origin <branch-name>"
log_info "4. Create PR on GitHub from your fork to upstream"
log_info ""
log_info "See: explorer-monorepo/docs/PULL_REQUEST_GUIDE.md for detailed instructions"

