from django.db import models
from django.db.models import Count, Sum

from apps.herd.models import Rancher, Herd
from apps.livestock.models import LiveStock


class FarmerDashboardService:
    """ Dashboard aggregation service for Rancher """

    @staticmethod
    def get_basic_info(rancher: Rancher):
        return {
            "id": rancher.id,
            "name": f"{rancher.first_name} {rancher.last_name}",
            "mobile": rancher.mobile,
            "national_code": rancher.national_code,
            "province": rancher.province.name if rancher.province else None,
            "city": rancher.city.name if rancher.city else None,
        }

    @staticmethod
    def get_herd_counts(rancher_id):
        return Herd.objects.filter(rancher_id=rancher_id).aggregate(
            total_herds=Count('id'),
            total_heavy=Sum('heavy_livestock_number'),
            total_light=Sum('light_livestock_number'),
        )

    @staticmethod
    def get_livestock_counts(rancher_id):
        return LiveStock.objects.filter(herd__rancher_id=rancher_id, archive=False).aggregate(
            total=Count('id'),
            heavy=Count('id', filter=models.Q(weight_type='H')),
            light=Count('id', filter=models.Q(weight_type='L')),
        )

    @staticmethod
    def get_livestock_by_type(rancher_id):
        return (
            LiveStock.objects.filter(herd__rancher_id=rancher_id, archive=False)
            .values("type__name")
            .annotate(count=Count("id"))
        )

# @staticmethod
# def get_dashboard(rancher_id):
