from django.db.models import Count

from blog.models import (
    BlogPost,
    BlogStatus,
)

from analytics.models import (
    BlogView,
    CTAEvent,
)

from adverts.models import (
    BannerEvent,
    AdBanner
)


class DashboardService:
    """
    Handles dashboard analytics and reporting.
    """

    @staticmethod
    def get_summary():
        """
        Returns high-level CMS metrics.
        """

        total_posts = BlogPost.objects.count()

        published_posts = BlogPost.objects.filter(
            status=BlogStatus.PUBLISHED
        ).count()

        draft_posts = BlogPost.objects.filter(
            status=BlogStatus.DRAFT
        ).count()

        archived_posts = BlogPost.objects.filter(
            status=BlogStatus.ARCHIVED
        ).count()

        total_views = BlogView.objects.count()

        unique_visitors = (
            BlogView.objects
            .values("visitor_id")
            .distinct()
            .count()
        )

        total_cta_events = CTAEvent.objects.count()

        total_banner_clicks = BannerEvent.objects.filter(
            event_type="click"
        ).count()

        total_banner_impressions = BannerEvent.objects.filter(
            event_type="impression"
        ).count()

        return {
            "total_posts": total_posts,
            "published_posts": published_posts,
            "draft_posts": draft_posts,
            "archived_posts": archived_posts,
            "total_views": total_views,
            "unique_visitors": unique_visitors,
            "total_cta_events": total_cta_events,
            "total_banner_clicks": total_banner_clicks,
            "total_banner_impressions": total_banner_impressions,
        }
    
    @staticmethod
    def get_top_posts(limit=10):

        posts = (
            BlogPost.objects
            .select_related("author", "category")
            .order_by("-views_count")[:limit]
        )

        return [
            {
                "id": post.id,
                "title": post.title,
                "slug": post.slug,
                "views": post.views_count,
                "status": post.status,
                "author": post.author.display_name,
                "published_at": post.published_at,
            }
            for post in posts
        ]
    
    @staticmethod
    def get_recent_posts(limit=10):

        posts = (
            BlogPost.objects
            .select_related("author")
            .order_by("-created_at")[:limit]
        )

        return [
            {
                "id": post.id,
                "title": post.title,
                "status": post.status,
                "author": post.author.display_name,
                "created_at": post.created_at,
            }
            for post in posts
        ]
    
    @staticmethod
    def get_cta_breakdown():

        data = (
            CTAEvent.objects
            .values("event_type")
            .annotate(total=Count("id"))
            .order_by("-total")
        )

        return list(data)
    
    


    @staticmethod
    def get_banner_performance():

        banners = AdBanner.objects.filter(
            is_active=True
        )

        results = []

        for banner in banners:

            impressions = BannerEvent.objects.filter(
                banner=banner,
                event_type="impression"
            ).count()

            clicks = BannerEvent.objects.filter(
                banner=banner,
                event_type="click"
            ).count()

            ctr = 0

            if impressions > 0:
                ctr = round(
                    (clicks / impressions) * 100,
                    2
                )

            results.append({
                "id": banner.id,
                "title": banner.title,
                "impressions": impressions,
                "clicks": clicks,
                "ctr": ctr,
            })

        return results
    
  