import re


def calculate_image_info(svg_file_path, aspect_ratio):
    """ Interrogate svg file, extract dimensions, calculate values necessary for export to png

    :param svg_file_path: location of the svg file to process
    :param aspect_ratio: the required aspect ratio for exported png images
    :return: a dict containing calculated values for the image sizes

    Exceptions:
    :raise if anything other than 1 regex match is found on the first line of the svg file
    :raise if anything other than 2 dimension floats are extracted from the regex match
    """
    # First get the dimensions of the svg file. We use a regex pattern to look for the height and width attributes
    regex_pattern = 'width="(\d*\.?\d*)px" height="(\d*\.?\d*)px".*?'
    dimension_strings = re.findall(regex_pattern, open(svg_file_path).readline())

    if len(dimension_strings) != 1:
        raise Exception('svg_to_webm: Did not successfully extract svg dimensions from ' + svg_file_path)

    # Convert the dimension string to two floats, and validate
    dimensions = [float(s) for s in dimension_strings[0]]
    if len(dimensions) != 2:
        raise Exception('svg_to_webm: Did not successfully extract svg dimensions from ' + svg_file_path)

    # Generate the file info dict
    file_info = {'svg_width': dimensions[0],
                 'svg_height': dimensions[1],
                 'png_width': int(dimensions[0]),
                 'png_height': int(dimensions[0] / aspect_ratio),
                 'png_y_offset': int(0.5 * (dimensions[1] - dimensions[1] / aspect_ratio))}

    # Add the crop_string in a format to be passed to inkscape
    file_info['crop_string'] = '{0}:{1}:{2}:{3}'.format(str(0),
                                                        str(file_info['png_y_offset']),
                                                        str(file_info['png_width']),
                                                        str(file_info['png_y_offset'] + file_info['png_height']))

    return file_info