import re


def _verify_host_data(host_hash, zone, host_name):
    """
    Check if hosts conifguration is sane.

    Check if hosts configuration follows some basic rules on which the script's
    main loop depends.

    Args:
        host_hash: A hash containing host's configuration. Fields are as follows:
            ip: mandatory. IP address of the host
            port: optional, default is 53. Port to use while connecting.
            key-id: optional. The ID of the key that should be send to the host.
            key-data: optional. The TSIG key itself.
            master: optional, default is False. Flag depicting whether host is
                master for the zone or not.
        zone: The zone to which host's configuration belongs to.
        host_name: The hostname of the host.

    Returns:
        A string containing description of problems found or an empty string
        if there are none.
    """
    msg = []

    if 'ip' in host_hash:
        ip = host_hash['ip']
        if not re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip):
            msg.append('Zonehost {0} from zone {1} has malformed IP: {2}.'.format(
                host_name, zone, ip))
    else:
        msg.append('Zonehost {0} from zone {1} '.format(host_name, zone) +
                   'does not have mandatory "ip" field.')

    if 'port' in host_hash:
        port = host_hash['port']
        if not isinstance(port, int) or port < 1 or port > 65535:
            msg.append('Zonehost {0} of zone {1} '.format(host_name, zone) +
                       'has malformed port: {0}.'.format(port))

    if "key-id" in host_hash or "key-data" in host_hash:
        if not ("key-id" in host_hash and "key-data" in host_hash):
            msg.append('Zonehost {0} from zone {1} '.format(host_name, zone) +
                       'should have both "key-id" and "key-data" keys ' +
                       'defined or none of them.')
        else:
            if not re.match(r"^[a-zA-Z0-9-\.]+$", host_hash['key-id']):
                msg.append('Zone {0}, zonekey for host {1}'.format(zone, host_name) +
                           ' has invalid "id" entry: {0}.'.format(
                           host_hash['key-id']))
            if not re.match(
                    "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$",
                    host_hash['key-data']):
                msg.append('Zone {0}, zonekey for host {1}'.format(zone, host_name) +
                           ' has non-base64 "data" entry.')

    return msg