"""Lightweight, deterministic personalization for the market page's default
product ordering — built entirely from the customer's own real order
history (pickker_orders / pickker_order_items), same data source as
market/spending_analytics.py. No AI/LLM call involved: a live model call on
every market-page load would be slow, costly, and non-deterministic for
what's fundamentally a "rank by what they usually buy" problem — see
market/views.py::_trending_commodities for the same "plain query, no LLM"
precedent this mirrors."""

from collections import defaultdict
from datetime import datetime, timedelta, timezone

from accounts.supabase_client import get_client

# Same exclusion set as market/spending_analytics.py -- a cancelled or
# still-unpaid order was never actually fulfilled, so its items aren't a
# real signal of what this customer wants to see more of.
_EXCLUDED_STATUSES = {'cancelled', 'pending_payment'}


def get_customer_product_quantities(customer_id, days=90):
    """{product_id: total_quantity_ever_bought} for this customer, over the
    last `days` (bounds the query for a long-time customer's history —
    same reasoning as spending_analytics's own window bound). Empty dict
    when there's no real order history yet — the caller (market/views.py::
    market) is expected to fail open on that, showing the page exactly as
    it looks today for a new customer. Deliberately keyed by product_id,
    not product_name (unlike get_top_products) — the caller needs to map
    each id to its CURRENT category from the market page's own
    already-decorated product list, not a point-in-time snapshot name."""
    since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
    orders = (
        get_client()
        .table('pickker_orders')
        .select('id, status')
        .eq('customer_id', customer_id)
        .gte('created_at', since)
        .execute()
        .data
    )
    order_ids = [o['id'] for o in orders if o['status'] not in _EXCLUDED_STATUSES]
    if not order_ids:
        return {}

    items = (
        get_client()
        .table('pickker_order_items')
        .select('product_id, quantity')
        .in_('order_id', order_ids)
        .execute()
        .data
    )

    quantities = defaultdict(int)
    for item in items:
        if item.get('product_id') is not None:
            quantities[item['product_id']] += item['quantity']
    return dict(quantities)
