from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from django.db.models import Count, Max

from apps.customers.models import Customer
from apps.calls.serializers import CallActivitySerializer
from apps.calls.serializers import DateRangeSerializer
from apps.calls.utils import get_date_range_from_request


class TopCallersMixin:
    """
    Analytics: Top callers by frequency.
    """

    @action(detail=False, methods=["get"], url_path="top-callers")
    def top_callers(self, request):
        start_dt, end_dt = get_date_range_from_request(
            request,
            DateRangeSerializer
        )

        base_qs = (
            self.filter_queryset(self.get_queryset())
            .filter(
                created_at__gte=start_dt,
                created_at__lte=end_dt
            )
        )

        top_callers = (
            base_qs
            .exclude(twilio_call_sid__isnull=True)
            .values("from_number")
            .annotate(
                # call_count=Count("id"),
                call_count=Count("twilio_call_sid", distinct=True),
                latest_call_time=Max("created_at"),
            )
            .order_by("-call_count")[:10]
        )

        phone_numbers = [row["from_number"] for row in top_callers]

        latest_calls = (
            base_qs
            .exclude(twilio_call_sid__isnull=True)
            .filter(from_number__in=phone_numbers)
            .order_by("from_number", "-created_at")
            .distinct("from_number")
            .prefetch_related("activities")
        )

        latest_call_map = {
            call.from_number: call
            for call in latest_calls
        }
        for call in latest_calls:
            if call.from_number not in latest_call_map:
                latest_call_map[call.from_number] = call

        customers = {
            c.phone: c
            for c in Customer.objects.filter(
                phone__in=phone_numbers,
                company=request.user.active_company
            )
        }

        result = []

        for row in top_callers:
            phone = row["from_number"]
            call = latest_call_map.get(phone)
            if not call:
                continue

            customer = customers.get(phone)

            duration_seconds = int(call.duration or 0)
            duration_formatted = (
                f"{duration_seconds // 3600}:"
                f"{(duration_seconds % 3600) // 60:02d}:"
                f"{duration_seconds % 60:02d}"
            )

            activities_data = CallActivitySerializer(
                call.activities.all(), many=True
            ).data

            result.append({
                "call_id": call.id,
                "twilio_call_id": call.twilio_call_sid,
                "call_date_time": call.created_at,
                "customer_name": customer.name if customer else "Unknown",
                "customer_number": phone,
                "call_count": row["call_count"],
                "duration": duration_formatted,
                "transcript": "",#call.transcript,
                "partner_call_id": call.call_id,
                "sentiment": call.sentiment,
                "call_summary": call.summary,
                "call_activities": activities_data,
            })

        return Response(result, status=status.HTTP_200_OK)
