#!/bin/bash

# Add html_file field to content index JSON files
# This script adds the required html_file field based on the existing source_file field

set -e

# Function to update a single JSON file
update_json_file() {
    local json_file="$1"

    echo "Updating: $json_file"

    # Create a temporary file for the updated JSON
    local temp_file=$(mktemp)

    # Use jq to add html_file field to each item based on source_file
    jq '
        if type == "object" then
            if has("blog") then
                .blog |= map(
                    if .source_file then
                        .html_file = (.source_file | gsub("\\.md$"; ".html") | gsub("^[^/]+/[^/]+/"; ""))
                    else . end
                )
            elif has("recipes") then
                .recipes |= map(
                    if .source_file then
                        .html_file = (.source_file | gsub("\\.md$"; ".html") | gsub("^[^/]+/[^/]+/"; ""))
                    else . end
                )
            else . end
        else . end
    ' "$json_file" > "$temp_file"

    # Check if jq succeeded
    if [ $? -eq 0 ]; then
        mv "$temp_file" "$json_file"
        echo "✅ Successfully updated $json_file"
    else
        echo "❌ Failed to update $json_file"
        rm -f "$temp_file"
        exit 1
    fi
}

# Find all index.json files in content directory
echo "🔍 Looking for index.json files..."

find content -name "index.json" -type f | while read -r json_file; do
    update_json_file "$json_file"
done

echo "🎉 All index.json files have been updated with html_file field!"
