#!/bin/bash

# Variables
re=""
pk=""
timestamp=$(date +%Y%m%d_%H%M%S)
base_dir="./results_$timestamp"

# Create timestamped folder with lists and sets subfolders
mkdir -p "$base_dir/lists" "$base_dir/sets"

# Log file for debugging
log_file="$base_dir/debug.log"
touch "$log_file"

echo -e "How many events of each type should I try to retrieve? \r"
read nu

# Log the user input
echo "Number of events to retrieve: $nu" | tee -a "$log_file"

# Fetch main events and log the command
echo "Fetching main events" | tee -a "$log_file"
nak req -k 1 -l "$nu" -a "$pk" "$re" | jq > "$base_dir/main_event.json"
if [[ $? -ne 0 ]]; then
    echo "Error fetching main event!" | tee -a "$log_file"
else
    echo "Main event fetched successfully" | tee -a "$log_file"
fi

# Debugging for kinds.json existence
if [[ ! -f "kinds.json" ]]; then
    echo "Error: kinds.json not found!" | tee -a "$log_file"
    exit 1
fi

# Loop through each kind in the JSON file
for item in $(jq -c '.kinds[]' kinds.json); do
    # Log the current item being processed
    echo "Processing item: $item" | tee -a "$log_file"

    kind=$(echo "$item" | jq -r '.kind')
    description=$(echo "$item" | jq -r '.description')
    category=$(echo "$item" | jq -r '.category')

    # Clean the description for filenames (remove special characters)
    safe_description=$(echo "$description" | sed 's/[^a-zA-Z0-9]/_/g')
    
    # Determine the output directory
    if [[ "$category" == "list" ]]; then
        output_dir="$base_dir/lists"
    elif [[ "$category" == "set" ]]; then
        output_dir="$base_dir/sets"
    else
        echo "Skipping unknown category: $category" | tee -a "$log_file"
        continue
    fi
    
    # Fetch and save data, with logging and error handling
    echo "Getting Kind $kind ($description)" | tee -a "$log_file"
    nak req -k "$kind" -a "$pk" "$re" | jq > "$output_dir/${safe_description}.json"
    if [[ $? -ne 0 ]]; then
        echo "Error fetching Kind $kind ($description)" | tee -a "$log_file"
    else
        # Log the successful fetch and save
        echo "Fetched and saved $output_dir/${safe_description}.json" | tee -a "$log_file"
    fi
done

# Log completion
echo "Script finished at $(date)" | tee -a "$log_file"
exit