from datetime import datetime


def get_airing(mal, anilist, kitsu_attr):
    """
    Get the airing dates for the search.
    :param mal: The MAL search result.
    :param anilist: The anilist search result.
    :param kitsu_attr: The attributes of kitsu search result.
    :return: the airing dates for the search.
    """

    def anilist_date(d):
        if not d:
            return
        year = d.get('year')
        month = d.get('month')
        day = d.get('day')
        if not (year and month and day):
            return
        return f'{year}-{month}-{day}'

    start = None
    end = None
    next_ = None

    mal_start = mal.get('start_date')
    if mal_start and not mal_start.startswith('0000'):
        start = mal_start

    mal_end = mal.get('end_date')
    if mal_end and not mal_end.startswith('0000'):
        end = mal_end

    anilist_start = anilist.get('startDate')
    if not start:
        start = anilist_date(anilist_start)

    anilist_end = anilist.get('endDate')
    if not end:
        end = anilist_date(anilist_end)

    anilist_next = anilist.get('nextAiringEpisode', {})

    if anilist_next:
        anilist_next = anilist_next.get('airingAt')
        try:
            next_ = datetime.fromtimestamp(anilist_next).strftime('%Y-%m-%d')
        except TypeError:
            next_ = None

    kitsu_start = kitsu_attr.get('startDate')
    if not start:
        start = kitsu_start
    kitsu_end = kitsu_attr.get('endDate')
    if not end:
        end = kitsu_end

    if start and end:
        return f'Start date: {start} | End date: {end}'
    elif start and next_:
        return f'Start date: {start} | Next: {next_}'
    elif start:
        return f'Start date: {start}'
    elif next_:
        return f'Next: {next_}'