import json


def device_info(dev, testbed_obj, showcmd='show version', save_to_json=False):
    """
    This function connects to the device provided when called (dev) in the instantiated testbed (testbed_obj)
    and executes the provided show command (if none was provided, 'show version' is executed by defulat.

    If the Save option = True (-s in the command line) was provided then the output will be saved to a JSON file in
    the current working directory with the name <device name>.json.  The default behavior is NOT to save the output.

    :param dev: the testbed device to query
    :param testbed_obj:  the testbed object
    :param showcmd: what show command to execute
    :return: Return the device object and the show command response
    """

    device = testbed_obj.devices[dev]
    device.connect()
    response = device.parse(showcmd)
    print(f"Response from {dev} is of type {type(response)} and length {len(response)}")
    print(response)
    print()
    print(json.dumps(response, indent=4))
    print(response.keys())

    if save_to_json:
        json_filename = f"{dev}.json"
        with open(json_filename, 'w', encoding='utf-8') as f:
            json.dump(response, f, ensure_ascii=False, indent=4)
        print(f"\nFILE SAVED: Saved Response to JSON file {json_filename}")

    return device, response