import requests
import warnings
import re


def determine_downloadable_file_url(base_url, folder, variable, year, ignore_warnings=False):
    """
    PIOMAS data files can have two types of files names, `area.H2019.gz` and `area.H2020`. Usually the latter is
    uncompressed and it is because it has just been generated. This function determines the actual file name to
    download by probing the data repository and check whether the uncompressed or the compressed file exists.

    :param base_url: The source URL, usually `https://pscfiles.apl.washington.edu/zhang/PIOMAS/data/v2.1`
    :param folder: The folder name following the base url
    :param variable: The variable name at the beginning of the file name
    :param year: The year at the end of the file name
    :param ignore_warnings: Whether to ignore warning
    :return: A downloadable URL
    """

    # Define the regular expression to identify the file name to download
    regex = f'>({variable}.H{year}.*?)<'

    # Download the index page
    index_url = '/'.join([base_url, folder])
    index_page = requests.get(index_url, verify=False)

    if index_page.status_code != 200:
        if not ignore_warnings:
            warnings.warn('Failed to reach {}. Skipped.'.format(index_url))

        return None

    # Find the file name
    match = re.findall(regex, index_page.text)

    if len(match) == 0:
        if not ignore_warnings:
            warnings.warn("No files found for '{}' on {}".format(regex, index_url))

        return None

    elif len(match) > 1:
        if not ignore_warnings:
            warnings.warn("Multiple files found for '{}' on {}".format(regex, index_url))

        return None

    return '/'.join([index_url, match[0]])