import re
from datetime import datetime


def filter_files(file_list, start_time, end_time, issues, is_forecast_product):
    """
    Filter files in file_list for matching time range and issues. If is_forecast_product is False,
    treats product as non-forecast. This means it will match files only based on start and end time.
    :param file_list: List of file names
    :param start_time: Request start time
    :param end_time: Request end time
    :param issues: Issues to match or empty list or None
    :param is_forecast_product: True iff the product is to be treated as forecast product, with issues and horizons
    :return: List of matched file names, sorted by start date
    """
    parsed_files = []
    for file_name in file_list:
        name_components = re.search(r'(.*)_(\d{12}).nc', file_name)
        if name_components:
            try:
                file_start_datetime = datetime.strptime(name_components.group(2), '%Y%m%d%H%M')
                parsed_files.append((file_name, file_start_datetime))
            except ValueError:
                raise Exception('Invalid product file name: ', file_name)
        else:
            raise Exception('Could not parse product file name: ', file_name)

    matched_files = []
    for file_name, file_start_datetime in sorted(parsed_files, key=lambda f: f[1]):
        if not is_forecast_product:
            if file_start_datetime <= start_time and len(matched_files) > 0:
                matched_files.pop()  # the previous file contains data that is too early. Remove it.
            if file_start_datetime <= end_time:
                matched_files.append(file_name)
        elif file_start_datetime.time() in issues \
                and (start_time.date() <= file_start_datetime.date() <= end_time.date()):
            # Forecast product
            matched_files.append(file_name)

    return matched_files