#!/bin/bash

# Set the target directory
DIR="$1"

# Check if directory exists
if [[ ! -d "$DIR" ]]; then
    echo "Error: Directory $DIR does not exist."
    exit 1
fi

# Initialize the JSON-LD structure
output_file="$DIR/graph.jsonld"
context_file="$DIR/_context_"

# Read main context
if [[ ! -f "$context_file" ]]; then
    echo "Error: Context file $context_file not found."
    exit 1
fi

main_context=$(jq '.["@context"]' "$context_file")

# Process relative paths in the main context
relative_paths=$(jq -r '.["@context"] | if type == "array" then .[] else . end | select(type == "string" and startswith("../"))' "$context_file")

updated_contexts=()
while read -r relative_path; do
    if [[ -f "$DIR/$relative_path" ]]; then
        # Extract the '@context' from the referenced file
        subcontext=$(jq '.["@context"]' "$DIR/$relative_path")
        updated_contexts+=("$relative_path|$subcontext")
    else
        echo "Warning: File $DIR/$relative_path not found. Skipping."
    fi
done <<< "$relative_paths"

# Replace relative paths with resolved contexts
for item in "${updated_contexts[@]}"; do
    path="${item%%|*}"
    subcontext="${item#*|}"

    # echo "Replacing $path with $subcontext"

    main_context="${main_context//\"$path\"/$subcontext}"

    # main_context=$(jq --arg path "$path" --argjson subcontext "$subcontext" '
    #     .["@context"] |= map(if . == $path then $subcontext else . end)
    # ' <<< "$main_context")
done

# flatten the context to a single object
main_context=$(jq '. |= reduce .[] as $item ({}; . * $item)' <<< "$main_context")

# Start building the JSON-LD file
echo '{' > "$output_file"
echo '  "@context": '"$main_context," >> "$output_file"
echo '  "@graph": [' >> "$output_file"

# Append all JSON-LD files in the directory to the graph
first=true
for file in "$DIR"/*.json; do
    [[ "$file" == "$context_file" ]] && continue  # Skip the context file
    content=$(jq 'del(."@context")' "$file")
    if $first; then
        echo "    $content" >> "$output_file"
        first=false
    else
        echo "    ,$content" >> "$output_file"
    fi
done

# Close the JSON-LD structure
echo '  ]' >> "$output_file"
echo '}' >> "$output_file"

echo "Combined JSON-LD file created at $output_file"
