import json
import logging


def process_covid_api_data(area_type: str) -> tuple:
    """ Function to process data from the covid API.

    Loads data from json files - 'region_covid_data.json' and
    'nation_covid_data.json'. Calculates 7 day infection rate
    based on api data.

    Arguments:
        area_type: the area that the data is being fetched for, determines how data is processed

    Returns:
        seven_day_rate: Cumulative cases in last 7 days, excluding empty and
            incomplete cell
        hospital_cases: current number of hospitalisations
        deaths: total number of deaths in desired region
    """
    seven_day_rate = 0
    no_of_days_ignore = 2 # the number of days of data skipped due to no data uploaded
    no_of_days_counted = 0
    hospital_cases = None
    deaths = None
    # load covid data from json
    if area_type == 'region':
        with open('region_covid_data.json', 'r', encoding='UTF-8') as covid_json:
            covid_data = json.load(covid_json)
    else:
        with open('nation_covid_data.json', 'r', encoding='UTF-8') as covid_json:
            covid_data = json.load(covid_json)

    covid_data_entries = covid_data['data']
    for daily_data in covid_data_entries:
        if daily_data['newCasesBySpecimenDate'] is None: # if the data column is empty
            no_of_days_ignore +=1
            logging.warning("Warning: More case data than expected empty.\
 Data for %s missing. API may not be up to date.", str(daily_data['date']))
            # adds an extra day to skip over to find complete data for 7 day rate
        no_of_days_ignore -= 1
        if area_type == 'nation': # if data is for nation, more is processed
            if deaths is None and daily_data['cumDailyNsoDeathsByDeathDate'] is not None:
                deaths = daily_data['cumDailyNsoDeathsByDeathDate']
            if daily_data['hospitalCases'] is not None and hospital_cases is None:
                hospital_cases = daily_data['hospitalCases']
        if no_of_days_ignore <= 0 and no_of_days_counted <= 6:
            seven_day_rate += daily_data['newCasesBySpecimenDate']
            no_of_days_counted +=1
    if area_type == 'nation': # returns data
        logging.info('Returning API data for: %s', area_type)
        return 'England', seven_day_rate, hospital_cases, deaths
    else:
        logging.info('Returning API data for: %s', area_type)
        return 'Exeter', seven_day_rate