import json
from cloudwatch_logger import print_log


def search_key_in_json(json_str, key_to_find):
    def search_recursive(data, key):
        if isinstance(data, dict):
            for k, v in data.items():
                if k == key:
                    return v
                result = search_recursive(v, key)
                if result is not None:
                    return result
        elif isinstance(data, list):
            for item in data:
                result = search_recursive(item, key)
                if result is not None:
                    return result
        return None

    try:
        json_data = json.loads(json_str)
        if key_to_find:
            result = search_recursive(json_data, key_to_find)
            return [result] if isinstance(result, dict) else result
        return json_data
    except json.JSONDecodeError as e:
        print_log(f"Error decoding JSON: {e}")
        return None

# Currently not in use, but can be used for future search operations
def is_no_record_found(json_str, message_key="UserMessageText", no_record_code="SYS100004"):
    '''
    Check if the JSON data represents a "No record found" response,
    i.e. a `UserMessageText` (or given message_key) is set and its value
    matches the no-record code (default SYS100004).

    Handles the bureau response shape:
        ... "UserMessage": {"UserMessageText": "SYS100004 (No record found)"} ...

    Parameters:
    - json_str (str or dict): JSON data as a string or a Python dictionary/list.
    - message_key (str): The key whose value indicates the response status.
    - no_record_code (str): The value that denotes "No record found".

    Returns:
    - bool: True if the no-record structure is found, otherwise False.
    '''
    if isinstance(json_str, str):
        try:
            data = json.loads(json_str)
        except json.JSONDecodeError as e:
            print_log(f"Error decoding JSON: {e}")
            return False
    else:
        data = json_str

    def recursive_search(data):
        if isinstance(data, dict):
            for k, v in data.items():
                if k == message_key and isinstance(v, str) and no_record_code in v:
                    return True
                if recursive_search(v):
                    return True
            return False
        elif isinstance(data, list):
            return any(recursive_search(item) for item in data)
        return False

    return recursive_search(data)


def find_key(json_str, target_key):
    '''
    Check if a given key exists in the JSON data regardless of its value.

    Parameters:
    - json_str (str or dict): JSON data as a string or a Python dictionary/list.
    - target_key (str): The key to search for.

    Returns:
    - bool: True if the key exists in the JSON data, otherwise False.
    '''
    # Convert JSON string to Python object if necessary
    if isinstance(json_str, str):
        try:
            data = json.loads(json_str)
        except json.JSONDecodeError as e:
            raise ValueError("Invalid JSON data. Error occurred: " + str(e))
    else:
        data = json_str

    def recursive_search(data):
        if isinstance(data, dict):
            if target_key in data:
                return True
            return any(recursive_search(value) for value in data.values())
        elif isinstance(data, list):
            return any(recursive_search(item) for item in data)
        return False

    return recursive_search(data)

