from datetime import timedelta
from core.utils.helper import duration_string_to_timedelta, timedelta_to_custom_format, format_amount_with_currency

from decimal import Decimal

import pendulum


def get_activities_by_week(data, total_sum_data):
    filtered_data = []

    if(len(data) > 0):
        dates = sorted(list(set([d['start_date_time'] for d in data])))

        start_date = pendulum.parse(dates[0]).start_of('month')
        end_date = pendulum.parse(dates[-1]).end_of('month')

        interval = pendulum.interval(start_date, end_date)

        for start_date in interval.range('months'):
            current_date = start_date
            end_date = start_date.end_of('month')

            while current_date <= end_date:
                start_of_week = current_date
                end_of_week = min(current_date + timedelta(days=6), end_date)

                total_duration = timedelta(hours=0, minutes=0, seconds=0)
                day_interval = pendulum.interval(start_of_week, end_of_week)
                for interval_date in day_interval.range('days'):
                    interval_date_duration = next((i['total_duration_sum'] for i in total_sum_data if i['date'] == interval_date.to_date_string()), timedelta(hours=0, minutes=0, seconds=0))
                    if interval_date_duration:
                        total_duration = duration_string_to_timedelta(interval_date_duration) + total_duration

                weekly_data = get_activities_by_days(data, total_sum_data, start_of_week, end_of_week)
                if(len(weekly_data) > 0):
                    filtered_data.append({
                        'start_date': start_of_week.date(),
                        'end_date': end_of_week.date(),
                        'week_range': f"{start_of_week.date()} to {end_of_week.date()}",
                        'weekly_total_duration': timedelta_to_custom_format(total_duration),
                        'days': weekly_data[::-1]
                    })

                current_date = end_of_week + timedelta(days=1)

    return filtered_data


def get_activities_by_days(data, total_sum_data, start_of_week, end_of_week):
    interval = pendulum.interval(start_of_week, end_of_week)

    daily_activities = []

    for range_date in interval.range('days'):

        total_duration = next((i['total_duration_sum'] for i in total_sum_data if i['date'] == range_date.to_date_string()), timedelta(hours=0, minutes=0, seconds=0))

        day_total_amount = sum(
             float(item.get('total_amount', '0').replace('₹', '').replace(',', ''))
            for item in data
            if range_date.to_date_string() == pendulum.parse(item['start_date_time']).to_date_string()
        )

        daily_data = [
            {**item, 'total_duration': timedelta_to_custom_format(duration_string_to_timedelta(item['total_duration']))}
            for item in data
            if range_date.to_date_string() == pendulum.parse(item['start_date_time']).to_date_string()
        ]

        if len(daily_data) > 0:

            daily_activities.append({
                'date': range_date.date(),
                'total_duration': timedelta_to_custom_format(duration_string_to_timedelta(total_duration)),
                'day_total_amount': format_amount_with_currency(day_total_amount),
                'activities': daily_data[::-1]
            })

    return daily_activities
