from datetime import timedelta

from django.db.models import Count, Q, Sum
from django.utils import timezone
from rest_framework import views, viewsets
from rest_framework.response import Response

from reminders.models import Reminder
from sessions.models import StudyPrayerSession

from .models import StreakHistory
from .serializers import StreakHistorySerializer


class StreakHistoryViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = StreakHistorySerializer

    def get_queryset(self):
        return StreakHistory.objects.filter(user=self.request.user)


class AnalyticsSummaryView(views.APIView):
    def get(self, request):
        user = request.user
        today = timezone.localdate()
        week_start = today - timedelta(days=today.weekday())
        sessions = StudyPrayerSession.objects.filter(user=user)
        weekly = sessions.filter(started_at__date__gte=week_start)
        completed = sessions.filter(status=StudyPrayerSession.Status.COMPLETED)
        total_week = weekly.count()
        completed_week = weekly.filter(status=StudyPrayerSession.Status.COMPLETED).count()

        by_category = completed.values("category").annotate(total=Count("id"), minutes=Sum("duration_minutes"))
        category_map = {item["category"]: item for item in by_category}
        latest_streak = StreakHistory.objects.filter(user=user).order_by("-date").first()

        today_reminders = Reminder.objects.filter(user=user, is_active=True).order_by("preferred_time")[:8]
        upcoming_reminders = Reminder.objects.filter(user=user, is_active=True).order_by("preferred_time")[8:14]

        return Response(
            {
                "today_reminders": [
                    {"id": r.id, "title": r.title, "category": r.category, "preferred_time": r.preferred_time, "duration_minutes": r.duration_minutes}
                    for r in today_reminders
                ],
                "upcoming_reminders": [
                    {"id": r.id, "title": r.title, "category": r.category, "preferred_time": r.preferred_time, "duration_minutes": r.duration_minutes}
                    for r in upcoming_reminders
                ],
                "completed_sessions": completed.count(),
                "missed_sessions": sessions.filter(status=StudyPrayerSession.Status.MISSED).count(),
                "streak_count": latest_streak.streak_count if latest_streak else 0,
                "weekly_completion_rate": round((completed_week / total_week) * 100) if total_week else 0,
                "prayer_consistency": category_map.get("prayer", {}).get("total", 0),
                "study_consistency": category_map.get("bible_study", {}).get("total", 0)
                + category_map.get("academic_study", {}).get("total", 0),
                "streak_history": StreakHistorySerializer(StreakHistory.objects.filter(user=user)[:30], many=True).data,
            }
        )
