#!/bin/bash

# Fix JSON structure to match ContentIndexItem model requirements
# Adds missing fields with appropriate default values

set -e

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

    echo "Updating structure: $json_file"

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

    # Use jq to ensure all required fields are present
    jq '
        if type == "object" then
            if has("blog") then
                .blog |= map(
                    . + {
                        "subtitle": (.subtitle // null),
                        "excerpt": (.excerpt // ""),
                        "author": (.author // null),
                        "date": (.created_at // null),
                        "published": (.published // true),
                        "translations": (.translations // []),
                        "category": (if .categories and (.categories | length > 0) then .categories[0] else null end),
                        "difficulty": (.difficulty // null),
                        "prep_time": (.prep_time // null),
                        "localized_slug": (.localized_slug // null)
                    }
                )
            elif has("recipes") then
                .recipes |= map(
                    . + {
                        "subtitle": (.subtitle // null),
                        "excerpt": (.excerpt // ""),
                        "author": (.author // null),
                        "date": (.created_at // null),
                        "published": (.published // true),
                        "translations": (.translations // []),
                        "category": (if .categories and (.categories | length > 0) then .categories[0] else null end),
                        "difficulty": (.difficulty // null),
                        "prep_time": (.prep_time // null),
                        "localized_slug": (.localized_slug // null)
                    }
                )
            else . end
        else . end
    ' "$json_file" > "$temp_file"

    # Check if jq succeeded
    if [ $? -eq 0 ]; then
        mv "$temp_file" "$json_file"
        echo "✅ Successfully updated structure for $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 to fix structure..."

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

echo "🎉 All index.json files now have the complete required structure!"
