"""
SMS Log views — admin can see every SMS sent by the system.
"""

import logging
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q, Count
from django.http import JsonResponse
from django.utils import timezone

from .sasapay_models import SMSLog, SMS_TYPE_CHOICES

logger = logging.getLogger(__name__)


@login_required
@staff_member_required
def sms_logs(request):
    """
    Admin view — full list of every SMS sent by the system with filters.
    """
    logs = SMSLog.objects.all()

    # --- filters ---
    sms_type   = request.GET.get('sms_type', '')
    status     = request.GET.get('status', '')
    search     = request.GET.get('search', '')
    date_from  = request.GET.get('date_from', '')
    date_to    = request.GET.get('date_to', '')

    if sms_type:
        logs = logs.filter(sms_type=sms_type)
    if status:
        logs = logs.filter(status=status)
    if search:
        logs = logs.filter(
            Q(recipients__icontains=search) |
            Q(message__icontains=search) |
            Q(borrower_name__icontains=search) |
            Q(loan_number__icontains=search)
        )
    if date_from:
        logs = logs.filter(created_at__date__gte=date_from)
    if date_to:
        logs = logs.filter(created_at__date__lte=date_to)

    # --- stats ---
    today = timezone.now().date()
    stats = {
        'total':   SMSLog.objects.count(),
        'today':   SMSLog.objects.filter(created_at__date=today).count(),
        'sent':    SMSLog.objects.filter(status='sent').count(),
        'failed':  SMSLog.objects.filter(status='failed').count(),
        'partial': SMSLog.objects.filter(status='partial').count(),
    }

    # type breakdown for today
    type_counts = (
        SMSLog.objects.filter(created_at__date=today)
        .values('sms_type')
        .annotate(count=Count('id'))
        .order_by('-count')
    )

    paginator = Paginator(logs, 30)
    page_obj  = paginator.get_page(request.GET.get('page'))

    context = {
        'page_obj':    page_obj,
        'stats':       stats,
        'type_counts': type_counts,
        'sms_types':   SMS_TYPE_CHOICES,
        'filters': {
            'sms_type':  sms_type,
            'status':    status,
            'search':    search,
            'date_from': date_from,
            'date_to':   date_to,
        },
    }
    return render(request, 'payments/sms_logs.html', context)


@login_required
@staff_member_required
def sms_log_detail(request, log_id):
    """Detail view for a single SMS log entry."""
    log = get_object_or_404(SMSLog, id=log_id)
    return render(request, 'payments/sms_log_detail.html', {'log': log})


@login_required
@staff_member_required
def resend_sms(request, log_id):
    """Re-send a previously failed SMS."""
    log = get_object_or_404(SMSLog, id=log_id)
    if request.method == 'POST':
        try:
            from .sms_service import send_sms
            result = send_sms(
                recipients=log.recipients,
                message=log.message,
                sender_id=log.sender_id,
                sms_type=log.sms_type,
                loan_number=log.loan_number,
                borrower_name=log.borrower_name,
                amount=log.amount,
            )
            recips = result.get('SMSMessageData', {}).get('Recipients', [])
            ok = sum(1 for r in recips if r.get('status') == 'Success')
            messages.success(request, f'SMS re-sent. {ok}/{len(recips)} delivered.')
        except Exception as exc:
            messages.error(request, f'Re-send failed: {exc}')
    return redirect('payments:sms_logs')


@login_required
@staff_member_required
def sms_stats_api(request):
    """JSON endpoint for SMS stats chart on the dashboard."""
    from django.db.models.functions import TruncDate
    from django.db.models import Count
    import datetime

    days = int(request.GET.get('days', 7))
    since = timezone.now().date() - datetime.timedelta(days=days - 1)

    daily = (
        SMSLog.objects
        .filter(created_at__date__gte=since)
        .annotate(day=TruncDate('created_at'))
        .values('day')
        .annotate(total=Count('id'),
                  sent=Count('id', filter=Q(status='sent')),
                  failed=Count('id', filter=Q(status='failed')))
        .order_by('day')
    )

    return JsonResponse({
        'labels': [str(d['day']) for d in daily],
        'sent':   [d['sent']  for d in daily],
        'failed': [d['failed'] for d in daily],
    })
