"""Bilingual product name — admin enters both languages at product-create/
edit time (or leaves the Kiswahili side blank), and a customer sees
whichever matches the site's current language, falling back to English
automatically so nothing shows blank just because a product hasn't been
translated yet."""


def localize_product(product, lang):
    """Mutates the given product dict in place, adding display_name for the
    given language code ('en'/'sw'), plus a customer-visible market_name
    badge whenever the product is tied to one specific market/shop (see
    pickker_products.market_id) — so a customer can tell at a glance that
    an item is shop-exclusive, and why it can't be combined with another
    shop's exclusive item in one order."""
    if lang == 'sw':
        product['display_name'] = product.get('name_sw') or product.get('name')
    else:
        product['display_name'] = product.get('name')
    if product.get('market_id'):
        from .markets import get_market
        market = get_market(product['market_id'])
        product['market_name'] = market['name'] if market else None
        product['market_logo_url'] = market.get('logo_url') if market else None
    else:
        product['market_name'] = None
        product['market_logo_url'] = None

    # Same badge, for the two newer non-market source types (see
    # market/vendors.py) — a customer sees at a glance that an item comes
    # from a specific warehouse/industry, and why it can't be combined with
    # a market or generic item in one order (see
    # market/views.py::_required_vendor_ties).
    if product.get('vendor_type') in ('warehouse', 'industry') and product.get('vendor_id'):
        from .vendors import get_vendor
        vendor = get_vendor(product['vendor_type'], product['vendor_id'])
        product['vendor_name'] = vendor['name'] if vendor else None
        product['vendor_logo_url'] = vendor.get('logo_url') if vendor else None
    else:
        product['vendor_name'] = None
        product['vendor_logo_url'] = None
    return product


def get_product_display_names(product_ids, lang):
    """{product_id: display_name} for a batch of products, resolved to
    whichever language the CURRENT viewer has active — used to re-localize
    an order item's product name at render time instead of trusting the
    plain-English name frozen onto the order at checkout (a customer or
    picker toggling their language later should still see "Ndizi"/"Karoti",
    not the English name captured back when the order was placed)."""
    product_ids = list({pid for pid in product_ids if pid})
    if not product_ids:
        return {}
    from accounts.supabase_client import get_client
    resp = get_client().table('pickker_products').select('id, name, name_sw').in_('id', product_ids).execute()
    return {p['id']: localize_product(p, lang)['display_name'] for p in resp.data}


def get_product_badges(product_ids):
    """{product_id: {'market_name': str|None, 'market_logo_url': str|None,
    'quality_grade': str|None}} for a batch of products — re-fetched live
    (not trusted from the order-time
    snapshot) so a customer/picker viewing a past order always sees the
    product's current market tie and grade label, same freshness rule as
    get_product_display_names above."""
    product_ids = list({pid for pid in product_ids if pid})
    if not product_ids:
        return {}
    from accounts.supabase_client import get_client
    from .markets import get_market
    resp = get_client().table('pickker_products').select('id, market_id, quality_grade').in_('id', product_ids).execute()
    badges = {}
    for p in resp.data:
        market = get_market(p['market_id']) if p.get('market_id') else None
        badges[p['id']] = {
            'market_name': market['name'] if market else None,
            'market_logo_url': market.get('logo_url') if market else None,
            'quality_grade': (p.get('quality_grade') or '').strip() or None,
        }
    return badges
