"""
White label admin site.

The header, title and tab name come from the tenant this install serves, so the
Django admin carries the client's name rather than the name of whoever built
the software. Nothing here is hardcoded to one company.
"""
from django.contrib import admin
from django.db.models import Count, Sum, Q
from django.utils import timezone
from django.utils.html import format_html


class PanelAdminSite(admin.AdminSite):
    # Fallbacks only. The real labels are resolved per request in each_context,
    # because a blank install has no name yet and must not borrow one.
    site_header  = 'Admin'
    site_title   = 'Admin'
    index_title  = 'Dashboard'

    def _site_label(self, request):
        """The name this install goes by: tenant first, then Settings."""
        tenant = getattr(request, 'tenant', None)
        label = (getattr(tenant, 'name', '') or '').strip()
        if label:
            return label
        try:
            from apps.pages.models import SiteSettings
            site = SiteSettings.load(tenant if getattr(tenant, 'pk', 0) else None)
            return (getattr(site, 'site_name', '') or '').strip()
        except Exception:
            return ''

    def each_context(self, request):
        context = super().each_context(request)
        label = self._site_label(request)
        if label:
            context['site_header'] = f'{label} Admin'
            context['site_title'] = label
        return context

    def index(self, request, extra_context=None):
        extra_context = extra_context or {}

        now   = timezone.now()
        today = now.date()
        month_start = now.replace(day=1, hour=0, minute=0, second=0)

        try:
            from apps.tickets.models import Ticket
            from apps.sales.models import SalesLead, DomainInquiry
            from apps.contact.models import ContactEnquiry

            extra_context['stats'] = {
                # Tickets
                'tickets_new':        Ticket.objects.filter(status='new').count(),
                'tickets_open':       Ticket.objects.filter(status__in=['new','open','in_progress']).count(),
                'tickets_today':      Ticket.objects.filter(created_at__date=today).count(),
                'tickets_month':      Ticket.objects.filter(created_at__gte=month_start).count(),

                # Sales
                'leads_new':          SalesLead.objects.filter(status='new').count(),
                'leads_won_month':    SalesLead.objects.filter(status='won', closed_at__gte=month_start).count(),
                'leads_pipeline':     SalesLead.objects.filter(status__in=['new','contacted','quoted']).count(),
                'leads_value':        SalesLead.objects.filter(status='won', closed_at__gte=month_start).aggregate(t=Sum('quoted_value'))['t'] or 0,

                # Domains
                'domains_new':        DomainInquiry.objects.filter(status='new').count(),
                'domains_month':      DomainInquiry.objects.filter(created_at__gte=month_start).count(),
                'domains_margin':     DomainInquiry.objects.filter(
                                          status='complete',
                                          created_at__gte=month_start
                                      ).aggregate(
                                          m=Sum('our_price') - Sum('reg_price')
                                      )['m'] or 0,

                # Enquiries
                'enquiries_month':    ContactEnquiry.objects.filter(created_at__gte=month_start).count(),
                'enquiries_unread':   ContactEnquiry.objects.filter(
                                          ticket__isnull=True
                                      ).count(),
            }
        except Exception:
            extra_context['stats'] = {}

        return super().index(request, extra_context)


# ── Swap the default admin site to use our version ────────────────────────────
# Every @admin.register() decorator uses admin.site, so this gives them all the
# dashboard, the live stats and the white label header without touching a single
# admin.py.
from django.contrib import admin as _admin
_admin.site.__class__ = PanelAdminSite
_admin.site.site_header  = PanelAdminSite.site_header
_admin.site.site_title   = PanelAdminSite.site_title
_admin.site.index_title  = PanelAdminSite.index_title
