"""
Expo Push Notification sender utility.

Uses the Expo Push API to deliver notifications to mobile devices.
https://docs.expo.dev/push-notifications/sending-notifications/
"""

import json
import urllib.request

EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'


def send_push_notification(expo_token, title, body, data=None):
    """
    Send a single push notification via Expo Push API.

    Args:
        expo_token: Expo push token string (e.g. "ExponentPushToken[xxx]")
        title: Notification title
        body: Notification body text
        data: Optional dict of extra data to include
    """
    if not expo_token:
        return None

    message = {
        'to': expo_token,
        'sound': 'default',
        'title': title,
        'body': body,
        'channelId': 'default',   # Must match the channel created in the app
        'priority': 'high',       # Immediate delivery on Android (maps to FCM high priority)
    }
    if data:
        message['data'] = data

    return _send_messages([message])


def send_push_notifications(messages):
    """
    Batch send push notifications.

    Args:
        messages: list of dicts, each with keys:
            - to (str): Expo push token
            - title (str): notification title
            - body (str): notification body
            - data (dict, optional): extra data

    Expo supports up to 100 messages per request.
    """
    if not messages:
        return None

    formatted = []
    for msg in messages:
        if not msg.get('to'):
            continue
        item = {
            'to': msg['to'],
            'sound': 'default',
            'title': msg.get('title', ''),
            'body': msg.get('body', ''),
            'channelId': 'default',
            'priority': 'high',
        }
        if msg.get('data'):
            item['data'] = msg['data']
        formatted.append(item)

    if not formatted:
        return None

    # Expo supports up to 100 per batch
    results = []
    for i in range(0, len(formatted), 100):
        batch = formatted[i:i + 100]
        result = _send_messages(batch)
        if result:
            results.extend(result)
    return results


def _send_messages(messages):
    """
    Internal helper to POST messages to Expo Push API.
    """
    payload = json.dumps(messages).encode('utf-8')
    req = urllib.request.Request(
        EXPO_PUSH_URL,
        data=payload,
        headers={
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Accept-Encoding': 'gzip, deflate',
        },
        method='POST',
    )

    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            data = json.loads(resp.read().decode('utf-8'))
            return data.get('data', [])
    except Exception as e:
        print(f'[Push] Error sending notifications: {e}')
        return None
