import yaml


def read_config(config_yml):
    """Read and parse run-time yaml configuration file

    Args:
        config_yml (string): File name for yaml configuration file
    
    Returns a dictionary
    """
    with open(config_yml, 'r') as f:
        config = yaml.safe_load(f)

    # Geo
    geobbox = dict(
        south=config['geo']['bbox']['south'],
        west=config['geo']['bbox']['west'],
        north=config['geo']['bbox']['north'],
        east=config['geo']['bbox']['east'],
    )

    to_crs = f"epsg:{config['geo']['to_epsg_crs']}"
    to_resolution = config['geo']['to_epsg_crs']

    # Create a sligthly larger box for the data query, relative to geobbox
    buffered_geobbox = geobbox.copy()
    buffered_geobbox['south'] = geobbox['south'] - config['geo']['bbox']['buffer_north']
    buffered_geobbox['north'] = geobbox['north'] + config['geo']['bbox']['buffer_north']
    buffered_geobbox['west'] = geobbox['west'] - config['geo']['bbox']['buffer_east']
    buffered_geobbox['east'] = geobbox['east'] + config['geo']['bbox']['buffer_east']

    config_out = dict(
        to_crs=to_crs,
        to_resolution=to_resolution,
        geobbox=geobbox,
        buffered_geobbox=buffered_geobbox,
        start_date=config['start_date'],
        end_date=config['end_date'],
        nc_export_fname=config['nc_export_fname'],
        nc_export_fdir=config['nc_export_fdir']
    )

    return config_out