import logging


def infer_header(input_path, expected_lines, method_name=None):
    """
    Method that infers the length of the header of a given file from the number of lines and of expected lines.

    Parameters
    ----------
    input_path : file or string
        File or filename to read.
    expected_lines : int
        Number of expected lines in the input file.
    method_name : string, optional
        A string indicating the name of the method being evaluated. If provided will be used when logging an error.
        Default is None.

    Returns
    -------
    header_len : int
        The length of the header.

    Raises
    ------
    ValueError
        If more lines are expected than those in the file.
    """
    # Autodetect header of input as (num_lines_in_input - expected_lines)
    num_lines = sum(1 for _ in open(input_path))
    header_len = num_lines - expected_lines

    if header_len < 0:
        raise ValueError('Exception, not enough lines in input file! Expected {} lines, obtained {}.'
                         .format(expected_lines, num_lines))
    elif header_len > 0:
        if method_name is not None:
            logging.warning('Output of method `{}` contains {} more lines than expected. Will consider them part '
                            'of the header and ignore them... Expected num_lines {}, obtained lines {}.'
                            .format(method_name, header_len, expected_lines, num_lines))
        else:
            logging.warning('Output contains {} more lines than expected. Will consider them part '
                            'of the header and ignore them... Expected num_lines {}, obtained lines {}.'
                            .format(header_len, expected_lines, num_lines))

    # Return the header length
    return header_len