# analytics/email_reports.py
"""
Automated Email Business Reports.
Sends daily summary email at midnight WAT (Africa/Lagos).
Company-specific — enabled only if company.settings.enable_email = True.
"""
import logging
from datetime import timedelta
from decimal import Decimal

from django.core.mail import send_mail
from django.utils import timezone
from django.db.models import Sum, Count

logger = logging.getLogger(__name__)


def send_daily_report(company):
    """
    Send a daily business summary email to the company admin.
    Only runs if enable_email is True in company settings.
    """
    cs = getattr(company, 'settings', None)
    if not cs or not cs.enable_email:
        return False

    # Get admin email
    recipient = cs.business_email or company.email
    if not recipient:
        from accounts.models import CustomUser
        admin_user = CustomUser.objects.filter(company=company, role='admin').first()
        recipient = admin_user.email if admin_user else None

    if not recipient:
        logger.warning(f"[EmailReport] No email for company: {company.name}")
        return False

    today = timezone.now().date()
    yesterday = today - timedelta(days=1)

    from sales.models import POSOrder, POSOrderItem
    from analytics.models import Insight

    # Yesterday's data
    orders = POSOrder.objects.filter(
        company=company, status='completed', created_at__date=yesterday
    )
    revenue = orders.aggregate(t=Sum('final_amount'))['t'] or Decimal('0')
    order_count = orders.count()

    # Profit calculation
    total_profit = Decimal('0')
    items = POSOrderItem.objects.filter(order__in=orders).select_related('product')
    for item in items:
        cost = (item.product.cost_price or Decimal('0')) if item.product else Decimal('0')
        total_profit += (item.unit_price - cost) * item.quantity

    # Top 3 insights from today
    top_insights = Insight.objects.filter(
        company=company, created_at__date=today
    ).order_by('-priority', '-created_at')[:5]

    sym = cs.currency_symbol or '₦'
    biz_name = cs.business_name or company.name

    # Build plain text fallback
    subject = f"Daily Business Summary — {biz_name} ({yesterday.strftime('%d %b %Y')})"

    body = f"Daily Business Summary for {biz_name}\n"
    body += f"Revenue: {sym}{revenue:,.2f} | Estimated Profit: {sym}{total_profit:,.2f} | Orders: {order_count}\n\nToday's Insights:\n"
    for insight in top_insights:
        body += f"- {insight.title}: {insight.description}\n"

    # Render HTML template
    from django.template.loader import render_to_string
    context = {
        'company': company,
        'slug': company.slug,
        'biz_name': biz_name,
        'sym': sym,
        'yesterday': yesterday,
        'revenue': revenue,
        'total_profit': total_profit,
        'order_count': order_count,
        'top_insights': top_insights,
    }
    try:
        html_content = render_to_string('emails/daily_report.html', context)
    except Exception as e:
        logger.error(f"[EmailReport] Failed to render HTML template: {e}")
        html_content = None

    try:
        send_mail(
            subject=subject,
            message=body,
            html_message=html_content,
            from_email=None,  # uses DEFAULT_FROM_EMAIL
            recipient_list=[recipient],
            fail_silently=False,
        )
        logger.info(f"[EmailReport] Daily report sent to {recipient} for {company.name}")
        return True
    except Exception as e:
        logger.error(f"[EmailReport] Failed to send for {company.name}: {e}")
        return False
