#!/bin/bash

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== Astar Network Tracing Runtime Extractor ===${NC}"
echo ""

# Prompt for network
echo -e "${BLUE}Select network:${NC}"
echo "1) Astar"
echo "2) Shiden"
echo "3) Shibuya"
read -p "Enter choice [1-3]: " NETWORK_CHOICE

case ${NETWORK_CHOICE} in
    1)
        NETWORK="astar"
        USE_LEGACY=true
        RENAME_FILES=false
        ;;
    2)
        NETWORK="shiden"
        USE_LEGACY=false
        RENAME_FILES=true
        ;;
    3)
        NETWORK="shibuya"
        USE_LEGACY=false
        RENAME_FILES=true
        ;;
    *)
        echo -e "${RED}Invalid choice${NC}"
        exit 1
        ;;
esac

echo -e "${GREEN}Selected network: ${NETWORK}${NC}"
echo ""

# Configuration
REPO="AstarNetwork/Astar"
OUTPUT_DIR="./tracing-runtimes/${NETWORK}"
TEMP_DIR="/tmp/astar-tracing-download"
LEGACY_ARCHIVE_URL="https://shared-assets.astar.network/files/runtime/astar-tracing-runtimes-3-73.tar.gz"
STOP_AT_VERSION="v5.27.0"

echo "Repository: https://github.com/${REPO}"
echo "Output directory: ${OUTPUT_DIR}"
echo ""

# Create output directory
mkdir -p "${OUTPUT_DIR}"
mkdir -p "${TEMP_DIR}"

# Cleanup function
cleanup() {
    echo -e "${YELLOW}Cleaning up temporary files...${NC}"
    rm -rf "${TEMP_DIR}"
}
trap cleanup EXIT

# Fetch all releases (excluding pre-releases) from GitHub
echo -e "${GREEN}Fetching releases from GitHub...${NC}"
RELEASES_URL="https://api.github.com/repos/${REPO}/releases?per_page=100"

# Get releases JSON
RELEASES_JSON=$(curl -s "${RELEASES_URL}")

# Check if we got valid JSON
if ! echo "${RELEASES_JSON}" | jq empty 2>/dev/null; then
    echo -e "${RED}Error: Failed to fetch releases or invalid JSON response${NC}"
    exit 1
fi

# Extract release information (filter out pre-releases)
RELEASE_COUNT=$(echo "${RELEASES_JSON}" | jq '[.[] | select(.prerelease == false)] | length')
echo -e "${GREEN}Found ${RELEASE_COUNT} non-prerelease releases${NC}"
echo ""

# Counter for processed files
DOWNLOADED=0
SKIPPED=0
FAILED=0

# Download and extract legacy archive (only for Astar)
if [ "${USE_LEGACY}" = true ]; then
    echo -e "${GREEN}Downloading legacy runtimes (pre-${STOP_AT_VERSION})...${NC}"
    LEGACY_ARCHIVE="${TEMP_DIR}/legacy-runtimes.tar.gz"

    if curl -L -s -o "${LEGACY_ARCHIVE}" "${LEGACY_ARCHIVE_URL}"; then
        echo -e "${GREEN}Extracting legacy archive...${NC}"
        if tar -xzf "${LEGACY_ARCHIVE}" -C "${OUTPUT_DIR}" 2>/dev/null; then
            LEGACY_COUNT=$(find "${OUTPUT_DIR}" -type f -name "*.wasm" | wc -l)
            echo -e "${GREEN}✓ Extracted ${LEGACY_COUNT} legacy runtime files${NC}"
            DOWNLOADED=${LEGACY_COUNT}
        else
            echo -e "${RED}Failed to extract legacy archive${NC}"
            FAILED=$((FAILED + 1))
        fi
        rm -f "${LEGACY_ARCHIVE}"
    else
        echo -e "${RED}Failed to download legacy archive${NC}"
        FAILED=$((FAILED + 1))
    fi
    echo ""
fi

# Set processing message based on network
if [ "${USE_LEGACY}" = true ]; then
    echo -e "${GREEN}Processing releases from ${STOP_AT_VERSION} onwards...${NC}"
else
    echo -e "${GREEN}Processing all releases...${NC}"
fi
echo ""

# Create a temporary file to store counters
COUNTER_FILE="${TEMP_DIR}/counters.txt"
echo "${DOWNLOADED} ${SKIPPED} ${FAILED}" > "${COUNTER_FILE}"

# Process each release
while read -r release; do
    # Read current counters
    read DOWNLOADED SKIPPED FAILED < "${COUNTER_FILE}"
    
    TAG=$(echo "${release}" | jq -r '.tag')
    
    # Stop processing if we've reached the stop version (only for Astar with legacy archive)
    if [ "${USE_LEGACY}" = true ] && [ "${TAG}" = "${STOP_AT_VERSION}" ]; then
        echo -e "${YELLOW}Reached stop version: ${STOP_AT_VERSION}, stopping...${NC}"
        break
    fi
    
    echo -e "${YELLOW}Processing release: ${TAG}${NC}"
    
    # Look for evm-tracing-artifacts tar.gz files in assets
    TRACING_ASSET=$(echo "${release}" | jq -r '.assets[] | select(.name | test("evm-tracing-artifacts.*\\.tar\\.gz$")) | .browser_download_url' | head -n 1)
    
    if [ -z "${TRACING_ASSET}" ]; then
        echo "  No tracing artifacts found, skipping..."
        SKIPPED=$((SKIPPED + 1))
        echo "${DOWNLOADED} ${SKIPPED} ${FAILED}" > "${COUNTER_FILE}"
        continue
    fi
    
    echo "  Found: $(basename ${TRACING_ASSET})"
    
    # Download the archive
    ARCHIVE_PATH="${TEMP_DIR}/$(basename ${TRACING_ASSET})"
    if ! curl -L -s -o "${ARCHIVE_PATH}" "${TRACING_ASSET}"; then
        echo -e "  ${RED}Failed to download${NC}"
        FAILED=$((FAILED + 1))
        echo "${DOWNLOADED} ${SKIPPED} ${FAILED}" > "${COUNTER_FILE}"
        continue
    fi
    
    # Extract the archive
    EXTRACT_DIR="${TEMP_DIR}/extract-${TAG}"
    mkdir -p "${EXTRACT_DIR}"
    
    if ! tar -xzf "${ARCHIVE_PATH}" -C "${EXTRACT_DIR}" 2>/dev/null; then
        echo -e "  ${RED}Failed to extract archive${NC}"
        FAILED=$((FAILED + 1))
        rm -rf "${EXTRACT_DIR}"
        rm -f "${ARCHIVE_PATH}"
        echo "${DOWNLOADED} ${SKIPPED} ${FAILED}" > "${COUNTER_FILE}"
        continue
    fi
    
    # Find and copy wasm files from evm-tracing-artifacts folder
    WASM_FILES=$(find "${EXTRACT_DIR}/evm-tracing-artifacts" -type f -name "${NETWORK}*.wasm" 2>/dev/null || true)
    
    if [ -z "${WASM_FILES}" ]; then
        echo -e "  ${YELLOW}No ${NETWORK}*.wasm files found in archive${NC}"
        SKIPPED=$((SKIPPED + 1))
    else
        for WASM_FILE in ${WASM_FILES}; do
            FILENAME=$(basename "${WASM_FILE}")
            
            # Rename files with version for Shiden/Shibuya
            if [ "${RENAME_FILES}" = true ]; then
                # Extract version from tag (e.g., v5.27.0 -> 5.27.0 or runtime-1900 -> 1900)
                VERSION=$(echo "${TAG}" | sed 's/^v//' | sed 's/^runtime-//')
                DEST_FILENAME="${VERSION}_${FILENAME}"
            else
                DEST_FILENAME="${FILENAME}"
            fi
            
            cp "${WASM_FILE}" "${OUTPUT_DIR}/${DEST_FILENAME}"
            echo -e "  ${GREEN}✓ Extracted: ${DEST_FILENAME}${NC}"
            DOWNLOADED=$((DOWNLOADED + 1))
        done
    fi
    
    # Save updated counters
    echo "${DOWNLOADED} ${SKIPPED} ${FAILED}" > "${COUNTER_FILE}"
    
    # Clean up extraction
    rm -rf "${EXTRACT_DIR}"
    rm -f "${ARCHIVE_PATH}"
done < <(echo "${RELEASES_JSON}" | jq -c '.[] | select(.prerelease == false) | {tag: .tag_name, assets: .assets}')

# Read final counters
read DOWNLOADED SKIPPED FAILED < "${COUNTER_FILE}"

echo ""
echo -e "${GREEN}=== Summary ===${NC}"
echo -e "Downloaded: ${GREEN}${DOWNLOADED}${NC}"
echo -e "Skipped: ${YELLOW}${SKIPPED}${NC}"
echo -e "Failed: ${RED}${FAILED}${NC}"
echo ""
echo -e "Output directory: ${GREEN}${OUTPUT_DIR}${NC}"

# List downloaded files
if [ ${DOWNLOADED} -gt 0 ]; then
    echo ""
    echo "Downloaded files:"
    ls -lh "${OUTPUT_DIR}"/*.wasm 2>/dev/null || true
fi
