# sales/suspicious.py
"""
Suspicious activity detection engine for SwiftPOS.
Called after every order completion to auto-flag unusual patterns.
"""
from decimal import Decimal
from django.utils import timezone
from datetime import timedelta


# Configurable thresholds
LARGE_ORDER_MULTIPLIER = 3.0       # Flag if order > 3× today's average
HIGH_DISCOUNT_PCT = 30.0            # Flag if discount > 30%
RAPID_ORDER_COUNT = 20              # Flag if cashier processes > N orders in 1 hr
HIGH_CREDIT_BALANCE = Decimal('50000')  # Flag credit balance > this amount


def detect_suspicious(order):
    """
    Check a completed POSOrder for suspicious patterns.
    Creates UnusualTransaction records for any matches found.
    Returns list of reason strings (empty if none).
    """
    from sales.models import POSOrder, UnusualTransaction

    reasons = []

    # 1. Large discount check
    if order.total_amount and order.discount_amount:
        if order.total_amount > 0:
            discount_pct = float(order.discount_amount) / float(order.total_amount) * 100
            if discount_pct > HIGH_DISCOUNT_PCT:
                reasons.append(f"High discount: {discount_pct:.1f}% off total")

    # 2. Large order vs daily average
    today = timezone.now().date()
    today_orders = POSOrder.objects.filter(
        created_at__date=today,
        status='completed',
    ).exclude(id=order.id)

    if today_orders.exists():
        from django.db.models import Avg
        avg_result = today_orders.aggregate(avg=Avg('final_amount'))
        avg_val = avg_result['avg'] or Decimal('0')
        if float(avg_val) > 0 and float(order.final_amount) > LARGE_ORDER_MULTIPLIER * float(avg_val):
            reasons.append(
                f"Order value ({order.final_amount:,.0f}) is {float(order.final_amount)/float(avg_val):.1f}× today's average"
            )

    # 3. Rapid order processing by same cashier
    one_hour_ago = timezone.now() - timedelta(hours=1)
    cashier_orders_1h = POSOrder.objects.filter(
        cashier=order.cashier,
        created_at__gte=one_hour_ago,
        status='completed',
    ).count()
    if cashier_orders_1h > RAPID_ORDER_COUNT:
        reasons.append(
            f"Cashier '{order.cashier}' processed {cashier_orders_1h} orders in the last hour"
        )

    # 4. High credit balance
    if order.balance_amount and order.balance_amount > HIGH_CREDIT_BALANCE:
        reasons.append(
            f"High credit balance: {order.balance_amount:,.0f} outstanding"
        )

    # Create UnusualTransaction records
    for reason in reasons:
        UnusualTransaction.objects.get_or_create(
            order=order,
            reason=reason,
            defaults={'flagged_by': 'system', 'company': order.company}
        )

    return reasons
