from django.db.models import Count
from django.utils import timezone
from django.utils.timezone import now
from datetime import datetime, timedelta

from accounts.models import Customers


def get_monthly_customer_data(company):
    """not tested yet"""
    try:
        now = timezone.now()
        start_date = now - timedelta(days=30 * 6)  # approximately 6 months
        monthly_data = {
            'registered': [],
            'unregistered': [],
            'total': [],
            'months': []
        }

        for i in range(6):
            start_of_month = start_date + timedelta(days=30 * i)
            end_of_month = start_of_month + timedelta(days=30)

            monthly_customers = Customers.objects.filter(
                batch__category__created_by__company=company,
                created__gte=timezone.make_aware(start_of_month),
                created__lt=timezone.make_aware(end_of_month)
            )

            registered_count = monthly_customers.exclude(password__in=['', None]).count()
            unregistered_count = monthly_customers.filter(password__in=['', None]).count()
            total_count = monthly_customers.count()

            monthly_data['registered'].append(registered_count)
            monthly_data['unregistered'].append(unregistered_count)
            monthly_data['total'].append(total_count)
            monthly_data['months'].append(start_of_month.strftime('%Y-%m'))

        return monthly_data
    except Exception as e:
        return ""
