#!/bin/bash

# Configuration
INPUT_FILE="zukan_hashes.json"
OUTPUT_DIR="zukan_images"
BASE_URL="https://zukan.inazuma.jp/assets/img/chara"
PARALLEL_JOBS=10  # Reduced to avoid being blocked, increase if safe

# Ensure dependencies
if ! command -v jq &> /dev/null; then
    echo "jq is required but not installed. Please install jq."
    exit 1
fi

if ! command -v start_agent &> /dev/null; then
    # Create output directory
    mkdir -p "$OUTPUT_DIR"
fi

echo "Extracting hashes from $INPUT_FILE..."

# Extract hashes and download in parallel
# We use curl with -f (fail), -s (silent), -S (show error), --create-dirs (create path structure)
# The URL structure uses the hash path from the json directly.
# Example hash: k/7/z/7zu952j85pc
# URL: https://zukan.inazuma.jp/assets/img/chara/k/7/z/7zu952j85pc.png
# Local Path: zukan_images/k/7/z/7zu952j85pc.png

jq -r '.[].zukan_hash' "$INPUT_FILE" | while read -r hash; do
    if [[ "$hash" != "null" && "$hash" != "" ]]; then
        echo "$hash"
    fi
done | xargs -P "$PARALLEL_JOBS" -I {} bash -c "
    hash=\"{}\"
    url=\"$BASE_URL/\$hash.png\"
    file=\"$OUTPUT_DIR/\$hash.png\"
    dir=\$(dirname \"\$file\")
    
    mkdir -p \"\$dir\"
    
    if [ ! -f \"\$file\" ]; then
        echo \"Downloading: \$hash\"
        curl -f -s -S --create-dirs -o \"\$file\" \"\$url\" || echo \"Failed: \$hash\"
    else
        echo \"Skipping: \$hash (Already exists)\"
    fi
"

echo "Download process completed."
