"""Admin broadcast — a one-off update sent by SMS and/or email to every
customer, every picker, or everyone, for site-wide announcements that don't
belong to any single order (service changes, market trend updates, etc).
Distinct from the passive homepage News & Announcements list — this actually
reaches people's phones/inboxes rather than waiting to be seen on a visit."""

from accounts.supabase_client import get_client
from .emailer import send_email
from .price_trends import get_overall_trend_badge
from .sms import send_sms


def get_broadcast_recipients(audience):
    """audience: 'customers' | 'pickers' | 'everyone'."""
    query = get_client().table('pickker_users').select('id, email, phone_number, first_name, role').eq('is_active', True)
    if audience == 'customers':
        query = query.eq('role', 'customer')
    elif audience == 'pickers':
        query = query.eq('role', 'picker')
    else:
        query = query.in_('role', ['customer', 'picker'])
    return query.execute().data


def send_broadcast(audience, subject, message, use_sms, use_email):
    """Best-effort — one recipient's failed send never stops the rest, same
    fail-safe spirit as every other notification in this app."""
    recipients = get_broadcast_recipients(audience)
    sms_sent = 0
    email_sent = 0
    for recipient in recipients:
        if use_sms and recipient.get('phone_number'):
            if send_sms(recipient['phone_number'], message):
                sms_sent += 1
        if use_email and recipient.get('email'):
            send_email(recipient['email'], subject, message)
            email_sent += 1
    return {'recipient_count': len(recipients), 'sms_sent': sms_sent, 'email_attempted': email_sent}


def build_market_trend_message():
    """A short customer-facing summary of what's rising/falling right now —
    a starting draft for the admin to review and edit before broadcasting.
    Swahili by default, matching this app's SMS-language convention."""
    resp = (
        get_client()
        .table('pickker_products')
        .select('id, name')
        .eq('is_trending', True)
        .eq('is_active', True)
        .order('name')
        .limit(10)
        .execute()
    )
    products = resp.data

    rising, falling = [], []
    for product in products:
        badge = get_overall_trend_badge(product['id'])
        if not badge or badge['change_pct'] is None or badge['direction'] == 'tied':
            continue
        line = f"{product['name']} {'juu' if badge['direction'] == 'up' else 'chini'} {badge['change_pct']}%"
        (rising if badge['direction'] == 'up' else falling).append(line)

    if not (rising or falling):
        return 'Taarifa ya bei za soko — PickkerMarket: Bei za soko ni tulivu wiki hii, hakuna mabadiliko makubwa kwa sasa.'

    parts = ['Taarifa ya bei za soko — PickkerMarket:']
    if falling:
        parts.append('Zinazoshuka bei: ' + ', '.join(falling))
    if rising:
        parts.append('Zinazopanda bei: ' + ', '.join(rising))
    return '\n'.join(parts)
