import json

# Function to recursively trim spaces and convert numerical values to strings in a JSON object
def clean_json(obj):
    if isinstance(obj, dict):
        cleaned_obj = {}
        for key, value in obj.items():
            cleaned_value = clean_json(value)
            if isinstance(cleaned_value, (int, float)):
                cleaned_value = str(cleaned_value)  # Convert numerical values to strings
            cleaned_obj[key.strip()] = cleaned_value
        return cleaned_obj
    elif isinstance(obj, list):
        return [clean_json(item) for item in obj]
    elif isinstance(obj, str):
        return obj.strip()
    else:
        return obj

# Read JSON data from new file
with open('pathologie_new.json', 'r') as file:
    new_json_data = json.load(file)

# Read JSON data from old file
with open('pathologie_old.json', 'r') as file:
    old_json_data = json.load(file)

# Create a dictionary to map ids to logos from the old file
id_to_logo = {item['id']: item['logo'] for item in old_json_data if 'logo' in item and item['logo'] is not None}

# Loop through each object in the new array, clean data, and trim spaces
for obj in new_json_data:
    obj = clean_json(obj)
    
    # Replace null with empty string for 'symptoms' and 'init_symptoms'
    if obj['symptoms'] is None:
        obj['symptoms'] = ""

    if obj['init_symptoms'] is None:
        obj['init_symptoms'] = ""

    # Remove the empty key if it exists (although this is redundant after trimming spaces)
    if "" in obj:
        del obj[""]

    # Copy the logo from the old data if it exists
    if obj['id'] in id_to_logo:
        obj['logo'] = id_to_logo[obj['id']]

# Print the modified JSON data
print(json.dumps(new_json_data, indent=4))

# Write the modified JSON data to a new file
with open('pathologie_parsed.json', 'w') as file:
    json.dump(new_json_data, file, indent=4)
