import json
import os

# Load the metadata.json file
with open("metadata.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# Ensure data is a list of dictionaries
if not isinstance(data, list):
    raise ValueError("The JSON file must contain a list of dictionaries.")

# Create output directory if needed
output_dir = "separated_jsons"
os.makedirs(output_dir, exist_ok=True)

# Iterate over each dictionary in the list
for entry in data:
    if not isinstance(entry, dict):
        continue  # Skip non-dictionary elements
    
    item_name = entry.get("item_name")
    if not item_name:
        continue  # Skip if there's no valid item_name
    
    # Define the output file path
    filename = os.path.join(output_dir, f"{item_name}.json")
    
    # Write the single-element list containing the dictionary
    with open(filename, "w", encoding="utf-8") as out_f:
        json.dump([entry], out_f, indent=4, ensure_ascii=False)

print(f"Saved {len(data)} JSON files in '{output_dir}'")

