import re
import json


def replace_pattern_properties_and_jsons(event):
    """Replaces pattern properties matching regex with a single pattern.

    And replaces JSON strings with dictionaries (adding _JSON suffix to the keys).

    This reduces the JSON schema size, genson treats each pattern property as an optional property.
    Example:
        Replaces `cc2a00e69f7a4dd8b560f4e48911206f_3_1` with `MD5HASH_int_int_0`.
        Replaces `"key": "{\"foo\": {}}"` with `"key_JSON": { "foo": {}}`
    """

    count = 0
    result = {}
    for key, item in event.items():
        if re.match(r"^[a-f0-9]{32}_[0-9]+_[0-9]+$", key):
            key = f"MD5HASH_int_int_{count}"
            count += 1
        if isinstance(item, dict):
            result[key] = replace_pattern_properties_and_jsons(item)
            continue
        if isinstance(item, str):
            # Try to parse JSON:
            try:
                parsed_item = json.loads(item)
                if isinstance(parsed_item, dict):
                    result[key + "_JSON"] = replace_pattern_properties_and_jsons(
                        parsed_item
                    )
                    continue
            except (json.JSONDecodeError, TypeError):
                pass
        result[key] = item
    return result