"""
WhatsApp messaging service for Syanko <3U loyalty notifications.
Supports WATI / Gupshup / Twilio / Meta via environment variables.
"""
import os
import logging
import requests
import json
from django.conf import settings

logger = logging.getLogger(__name__)

# Provider configuration settings
WHATSAPP_PROVIDER = os.environ.get('WHATSAPP_PROVIDER', getattr(settings, 'WHATSAPP_PROVIDER', '')).lower()

# WATI
WAPI_URL = os.environ.get('WHATSAPP_API_URL', getattr(settings, 'WHATSAPP_API_URL', ''))
WAPI_KEY = os.environ.get('WHATSAPP_API_KEY', getattr(settings, 'WHATSAPP_API_KEY', ''))
WFROM    = os.environ.get('WHATSAPP_FROM_NUMBER', getattr(settings, 'WHATSAPP_FROM_NUMBER', ''))

# Meta Cloud API
META_PHONE_NUMBER_ID = os.environ.get('META_PHONE_NUMBER_ID', getattr(settings, 'META_PHONE_NUMBER_ID', ''))
META_ACCESS_TOKEN = os.environ.get('META_ACCESS_TOKEN', getattr(settings, 'META_ACCESS_TOKEN', ''))
META_LANGUAGE_CODE = os.environ.get('META_LANGUAGE_CODE', getattr(settings, 'META_LANGUAGE_CODE', 'en'))

# Twilio
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID', getattr(settings, 'TWILIO_ACCOUNT_SID', ''))
TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN', getattr(settings, 'TWILIO_AUTH_TOKEN', ''))
TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER', getattr(settings, 'TWILIO_FROM_NUMBER', ''))

# Gupshup
GUPSHUP_API_KEY = os.environ.get('GUPSHUP_API_KEY', getattr(settings, 'GUPSHUP_API_KEY', ''))
GUPSHUP_FROM_NUMBER = os.environ.get('GUPSHUP_FROM_NUMBER', getattr(settings, 'GUPSHUP_FROM_NUMBER', ''))
GUPSHUP_APP_NAME = os.environ.get('GUPSHUP_APP_NAME', getattr(settings, 'GUPSHUP_APP_NAME', ''))

# Interakt
INTERAKT_SECRET_KEY = os.environ.get('INTERAKT_SECRET_KEY', getattr(settings, 'INTERAKT_SECRET_KEY', ''))

TEMPLATES_MAP = {
    'welcome_coins': "Hello {0}, welcome to {1}! You have earned {2} welcome coins. 🪙",
    'coin_expiry_warning': "Hello {0}, you have {1} coins expiring within the next 24 hours at {2}. Use them before they expire! 💰",
    'dead_hour_drop': "Hello {0}! {1} is having a special deal: {2}. Use code {3} within the next {4} hours to claim! ⏳",
    'summit_vip': "Congratulations {0}! You have hit Summit VIP status at {1}! 🎉",
}


def _format_phone(phone: str, provider: str) -> str:
    cleaned = phone.replace('whatsapp:', '').lstrip('+').replace(' ', '').replace('-', '').replace('(', '').replace(')', '')
    # Default to India (+91) if a 10-digit number is provided
    if len(cleaned) == 10 and cleaned.isdigit():
        cleaned = "91" + cleaned
    if provider == 'twilio':
        return f"whatsapp:+{cleaned}"
    return cleaned


def get_whatsapp_provider():
    # Force Interakt as the provider since the user specifically requested it
    return 'interakt'

def _get_interakt_secret_key():
    return os.environ.get('INTERAKT_SECRET_KEY', getattr(settings, 'INTERAKT_SECRET_KEY', '')) or 'ZVFoV1RGR2x1S0JDMHpkZUtYeklmbVNwR3UyOV83X2xFMGRiMWRVZU9zWTo='


def _send_meta(phone: str, template_name: str, params: list) -> bool:
    if not META_ACCESS_TOKEN or not META_PHONE_NUMBER_ID:
        logger.warning("Meta WhatsApp API not configured — message not sent to %s", phone)
        return False
    
    clean_phone = _format_phone(phone, 'meta')
    url = f"https://graph.facebook.com/v17.0/{META_PHONE_NUMBER_ID}/messages"
    payload = {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": clean_phone,
        "type": "template",
        "template": {
            "name": template_name,
            "language": {
                "code": META_LANGUAGE_CODE
            },
            "components": [
                {
                    "type": "body",
                    "parameters": [{"type": "text", "text": str(v)} for v in params]
                }
            ]
        }
    }
    headers = {
        "Authorization": f"Bearer {META_ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    try:
        resp = requests.post(url, json=payload, headers=headers, timeout=10)
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        logger.error("Meta WhatsApp send failed for %s: %s", phone, exc)
        return False


def _send_reply_meta(phone: str, message: str) -> bool:
    if not META_ACCESS_TOKEN or not META_PHONE_NUMBER_ID:
        logger.warning("Meta WhatsApp API not configured — reply not sent to %s", phone)
        return False
    
    clean_phone = _format_phone(phone, 'meta')
    url = f"https://graph.facebook.com/v17.0/{META_PHONE_NUMBER_ID}/messages"
    payload = {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": clean_phone,
        "type": "text",
        "text": {
            "body": message
        }
    }
    headers = {
        "Authorization": f"Bearer {META_ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    try:
        resp = requests.post(url, json=payload, headers=headers, timeout=10)
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        logger.error("Meta WhatsApp reply failed for %s: %s", phone, exc)
        return False


def _send_reply_twilio(phone: str, message: str) -> bool:
    if not TWILIO_ACCOUNT_SID or not TWILIO_AUTH_TOKEN or not TWILIO_FROM_NUMBER:
        logger.warning("Twilio WhatsApp API not configured — reply not sent to %s", phone)
        return False
    
    clean_phone = _format_phone(phone, 'twilio')
    clean_from = _format_phone(TWILIO_FROM_NUMBER, 'twilio')
    url = f"https://api.twilio.com/2010-04-01/Accounts/{TWILIO_ACCOUNT_SID}/Messages.json"
    payload = {
        "From": clean_from,
        "To": clean_phone,
        "Body": message
    }
    try:
        resp = requests.post(
            url,
            data=payload,
            auth=(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN),
            headers={"Content-Type": "application/x-www-form-urlencoded"},
            timeout=10
        )
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        err_msg = exc.response.text if exc.response else str(exc)
        logger.error("Twilio WhatsApp reply failed for %s: %s | Details: %s", phone, exc, err_msg)
        print("TWILIO ERROR:", err_msg)
        return False


def _send_twilio(phone: str, template_name: str, params: list) -> bool:
    tmpl = TEMPLATES_MAP.get(template_name)
    if tmpl:
        try:
            body_text = tmpl.format(*params)
        except Exception:
            body_text = f"Notification: {template_name} - " + ", ".join(map(str, params))
    else:
        body_text = f"Notification: {template_name} - " + ", ".join(map(str, params))
    
    return _send_reply_twilio(phone, body_text)


def _send_gupshup(phone: str, template_name: str, params: list) -> bool:
    if not GUPSHUP_API_KEY or not GUPSHUP_FROM_NUMBER:
        logger.warning("Gupshup WhatsApp API not configured — message not sent to %s", phone)
        return False
    
    clean_phone = _format_phone(phone, 'gupshup')
    url = "https://api.gupshup.io/sm/api/v1/template/msg"
    template_data = {
        "id": template_name,
        "params": [str(v) for v in params]
    }
    payload = {
        "source": GUPSHUP_FROM_NUMBER,
        "destination": clean_phone,
        "template": json.dumps(template_data)
    }
    headers = {
        "apikey": GUPSHUP_API_KEY,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    try:
        resp = requests.post(url, data=payload, headers=headers, timeout=10)
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        logger.error("Gupshup WhatsApp template send failed for %s: %s", phone, exc)
        return False


def _send_reply_gupshup(phone: str, message: str) -> bool:
    if not GUPSHUP_API_KEY or not GUPSHUP_FROM_NUMBER:
        logger.warning("Gupshup WhatsApp API not configured — reply not sent to %s", phone)
        return False
    
    clean_phone = _format_phone(phone, 'gupshup')
    url = "https://api.gupshup.io/sm/api/v1/msg"
    message_data = {
        "isHSM": "false",
        "type": "text",
        "text": message
    }
    payload = {
        "channel": "whatsapp",
        "source": GUPSHUP_FROM_NUMBER,
        "destination": clean_phone,
        "message": json.dumps(message_data)
    }
    if GUPSHUP_APP_NAME:
        payload["src.name"] = GUPSHUP_APP_NAME
        
    headers = {
        "apikey": GUPSHUP_API_KEY,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    try:
        resp = requests.post(url, data=payload, headers=headers, timeout=10)
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        logger.error("Gupshup WhatsApp reply failed for %s: %s", phone, exc)
        return False


def _send_wati(phone: str, template_name: str, params: list) -> bool:
    if not WAPI_URL or not WAPI_KEY:
        logger.warning("WATI WhatsApp API not configured — message not sent to %s", phone)
        return False

    clean_phone = _format_phone(phone, 'wati')
    payload = {
        "template_name": template_name,
        "broadcast_name": template_name,
        "parameters": [{"name": str(i + 1), "value": str(v)} for i, v in enumerate(params)],
    }
    try:
        resp = requests.post(
            f"{WAPI_URL}/api/v1/sendTemplateMessage?whatsappNumber={clean_phone}",
            json=payload,
            headers={"Authorization": f"Bearer {WAPI_KEY}"},
            timeout=10,
        )
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        logger.error("WATI WhatsApp send failed for %s: %s", phone, exc)
        return False


def _send_reply_wati(phone: str, message: str) -> bool:
    if not WAPI_URL or not WAPI_KEY:
        logger.warning("WATI WhatsApp API not configured — reply not sent to %s", phone)
        return False

    clean_phone = _format_phone(phone, 'wati')
    try:
        resp = requests.post(
            f"{WAPI_URL}/api/v1/sendSessionMessage?whatsappNumber={clean_phone}",
            json={"messageText": message},
            headers={"Authorization": f"Bearer {WAPI_KEY}"},
            timeout=10,
        )
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        logger.error("WATI WhatsApp reply failed for %s: %s", phone, exc)
        return False


def _send_interakt(phone: str, template_name: str, params: list) -> bool:
    secret_key = _get_interakt_secret_key()
    if not secret_key:
        logger.warning("Interakt API not configured — message not sent to %s", phone)
        return False

    clean_phone = _format_phone(phone, 'interakt')
    if clean_phone.startswith('91') and len(clean_phone) == 12:
        country_code = '+91'
        phone_number = clean_phone[2:]
    else:
        # Fallback simplistic split for testing
        country_code = '+91'
        phone_number = clean_phone[-10:] if len(clean_phone) >= 10 else clean_phone

    url = "https://api.interakt.ai/v1/public/message/"
    payload = {
        "countryCode": country_code,
        "phoneNumber": phone_number,
        "type": "Template",
        "template": {
            "name": template_name,
            "languageCode": "en",
            "bodyValues": [str(v) for v in params]
        }
    }
    headers = {
        "Authorization": f"Basic {secret_key}",
        "Content-Type": "application/json"
    }
    try:
        resp = requests.post(url, json=payload, headers=headers, timeout=10)
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        err_msg = exc.response.text if exc.response else str(exc)
        logger.error("Interakt WhatsApp send failed for %s: %s | %s", phone, exc, err_msg)
        return False


def _send_reply_interakt(phone: str, message: str) -> bool:
    secret_key = _get_interakt_secret_key()
    if not secret_key:
        logger.warning("Interakt API not configured — reply not sent to %s", phone)
        return False

    clean_phone = _format_phone(phone, 'interakt')
    if clean_phone.startswith('91') and len(clean_phone) == 12:
        country_code = '+91'
        phone_number = clean_phone[2:]
    else:
        country_code = '+91'
        phone_number = clean_phone[-10:] if len(clean_phone) >= 10 else clean_phone

    url = "https://api.interakt.ai/v1/public/message/"
    payload = {
        "countryCode": country_code,
        "phoneNumber": phone_number,
        "type": "Text",
        "data": {
            "message": message
        }
    }
    headers = {
        "Authorization": f"Basic {secret_key}",
        "Content-Type": "application/json"
    }
    try:
        resp = requests.post(url, json=payload, headers=headers, timeout=10)
        resp.raise_for_status()
        return True
    except requests.RequestException as exc:
        err_msg = exc.response.text if exc.response else str(exc)
        logger.error("Interakt WhatsApp reply failed for %s: %s | %s", phone, exc, err_msg)
        return False


def _send(phone: str, template_name: str, params: list) -> bool:
    provider = get_whatsapp_provider()
    if not provider:
        logger.warning("WhatsApp API not configured — message not sent to %s", phone)
        return False
    
    if provider == 'meta':
        return _send_meta(phone, template_name, params)
    elif provider == 'twilio':
        return _send_twilio(phone, template_name, params)
    elif provider == 'gupshup':
        return _send_gupshup(phone, template_name, params)
    elif provider == 'wati':
        return _send_wati(phone, template_name, params)
    elif provider == 'interakt':
        return _send_interakt(phone, template_name, params)
    
    return False


def send_welcome_message(wallet) -> bool:
    """Triggered when a new wallet is created."""
    phone = getattr(wallet.customer, 'phone', None) or getattr(wallet.customer, 'phone_number', None) or getattr(wallet.customer, 'contact', None)
    if not phone:
        return False
    try:
        program_name = wallet.restaurant.loyalty_program.program_name
        balance = str(wallet.coin_balance)
    except Exception:
        program_name = wallet.restaurant.name
        balance = '0'
    return _send(phone, 'welcome_coins', [wallet.customer.first_name or wallet.customer.username, program_name, balance])


def send_coin_expiry_warning(wallet) -> bool:
    """Warn customer about coins expiring in the next 24 hours."""
    from django.utils import timezone
    from .models import CoinTransaction
    cutoff = timezone.now() + timezone.timedelta(hours=24)
    expiring = CoinTransaction.objects.filter(
        wallet=wallet,
        is_expired=False,
        expires_at__isnull=False,
        expires_at__lte=cutoff,
        coins__gt=0,
    )
    total = sum(tx.coins for tx in expiring)
    if total <= 0:
        return False

    phone = getattr(wallet.customer, 'phone', None) or getattr(wallet.customer, 'phone_number', None) or getattr(wallet.customer, 'contact', None)
    if not phone:
        return False
    return _send(phone, 'coin_expiry_warning', [
        wallet.customer.first_name or wallet.customer.username,
        str(int(total)),
        wallet.restaurant.name,
    ])


def send_dead_hour_drop(restaurant, message: str, discount_code: str, valid_hours: int) -> int:
    """
    Broadcast a dead-hour promotional drop to all wallets with a known phone number.
    Returns number of messages successfully queued.
    """
    from .models import CustomerWallet
    wallets = CustomerWallet.objects.filter(restaurant=restaurant).select_related('customer')
    sent = 0
    for wallet in wallets:
        phone = getattr(wallet.customer, 'phone', None) or getattr(wallet.customer, 'phone_number', None) or getattr(wallet.customer, 'contact', None)
        if not phone:
            continue
        success = _send(phone, 'dead_hour_drop', [
            wallet.customer.first_name or wallet.customer.username,
            restaurant.name,
            message,
            discount_code,
            str(valid_hours),
        ])
        if success:
            sent += 1
    return sent


def send_reply(phone: str, message: str) -> bool:
    """
    Send a freeform session message back to an inbound WhatsApp conversation.
    Must be called within 24 h of the customer's last inbound message.
    """
    provider = get_whatsapp_provider()
    if not provider:
        logger.warning("WhatsApp API not configured — reply not sent to %s", phone)
        return False
    
    if provider == 'meta':
        return _send_reply_meta(phone, message)
    elif provider == 'twilio':
        return _send_reply_twilio(phone, message)
    elif provider == 'gupshup':
        return _send_reply_gupshup(phone, message)
    elif provider == 'wati':
        return _send_reply_wati(phone, message)
    elif provider == 'interakt':
        return _send_reply_interakt(phone, message)
    
    return False


def _fallback_interactive(phone: str, text: str, buttons: list) -> bool:
    """Fallback for providers that don't support interactive buttons natively."""
    fallback_text = text + "\n\n"
    for i, btn in enumerate(buttons, 1):
        fallback_text += f"{i}️⃣  {btn['title']}\n"
    fallback_text += "\nReply with a number or the exact text."
    return send_reply(phone, fallback_text)


def send_interactive_buttons(phone: str, text: str, buttons: list) -> bool:
    """
    Send an interactive button message.
    buttons: list of dicts [{'id': 'btn_1', 'title': 'Yes'}, ...] (max 3)
    """
    provider = get_whatsapp_provider()
    
    secret_key = _get_interakt_secret_key()
    if provider == 'interakt' and secret_key:
        clean_phone = _format_phone(phone, 'interakt')
        country_code = '+91'
        phone_number = clean_phone[2:] if clean_phone.startswith('91') and len(clean_phone) == 12 else (clean_phone[-10:] if len(clean_phone) >= 10 else clean_phone)
        url = "https://api.interakt.ai/v1/public/message/"
        payload = {
            "countryCode": country_code,
            "phoneNumber": phone_number,
            "type": "InteractiveButton",
            "data": {
                "message": {
                    "type": "button",
                    "body": {"text": text},
                    "action": {
                        "buttons": [
                            {"type": "reply", "reply": {"id": btn['id'], "title": btn['title'][:20]}}
                            for btn in buttons[:3]
                        ]
                    }
                }
            }
        }
        headers = {"Authorization": f"Basic {secret_key}", "Content-Type": "application/json"}
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            resp.raise_for_status()
            return True
        except requests.RequestException as exc:
            logger.error("Interakt interactive reply failed for %s: %s", phone, exc)
            return _fallback_interactive(phone, text, buttons)

    if provider == 'meta' and META_ACCESS_TOKEN and META_PHONE_NUMBER_ID:
        clean_phone = _format_phone(phone, 'meta')
        url = f"https://graph.facebook.com/v17.0/{META_PHONE_NUMBER_ID}/messages"
        payload = {
            "messaging_product": "whatsapp",
            "recipient_type": "individual",
            "to": clean_phone,
            "type": "interactive",
            "interactive": {
                "type": "button",
                "body": {"text": text},
                "action": {
                    "buttons": [
                        {
                            "type": "reply",
                            "reply": {
                                "id": btn['id'],
                                "title": btn['title'][:20]
                            }
                        } for btn in buttons[:3]
                    ]
                }
            }
        }
        headers = {
            "Authorization": f"Bearer {META_ACCESS_TOKEN}",
            "Content-Type": "application/json"
        }
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            resp.raise_for_status()
            return True
        except requests.RequestException as exc:
            logger.error("Meta WhatsApp interactive reply failed for %s: %s", phone, exc)
            return False
            
    # Fallback for Interakt/Twilio/Wati
    return _fallback_interactive(phone, text, buttons)


def send_interactive_list(phone: str, text: str, button_text: str, sections: list) -> bool:
    """
    Send an interactive list message.
    sections: [{'title': 'Starters', 'rows': [{'id': 's1', 'title': 'Paneer', 'description': '...'}]}, ...]
    """
    provider = get_whatsapp_provider()
    
    secret_key = _get_interakt_secret_key()
    if provider == 'interakt' and secret_key:
        clean_phone = _format_phone(phone, 'interakt')
        country_code = '+91'
        phone_number = clean_phone[2:] if clean_phone.startswith('91') and len(clean_phone) == 12 else (clean_phone[-10:] if len(clean_phone) >= 10 else clean_phone)
        url = "https://api.interakt.ai/v1/public/message/"
        payload = {
            "countryCode": country_code,
            "phoneNumber": phone_number,
            "type": "InteractiveList",
            "data": {
                "message": {
                    "type": "list",
                    "body": {"text": text},
                    "action": {
                        "button": button_text[:20],
                        "sections": sections
                    }
                }
            }
        }
        headers = {"Authorization": f"Basic {secret_key}", "Content-Type": "application/json"}
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            resp.raise_for_status()
            return True
        except requests.RequestException as exc:
            logger.error("Interakt interactive list failed for %s: %s", phone, exc)
            return _fallback_list(phone, text, sections)

    if provider == 'meta' and META_ACCESS_TOKEN and META_PHONE_NUMBER_ID:
        clean_phone = _format_phone(phone, 'meta')
        url = f"https://graph.facebook.com/v17.0/{META_PHONE_NUMBER_ID}/messages"
        payload = {
            "messaging_product": "whatsapp",
            "recipient_type": "individual",
            "to": clean_phone,
            "type": "interactive",
            "interactive": {
                "type": "list",
                "body": {"text": text},
                "action": {
                    "button": button_text[:20],
                    "sections": sections
                }
            }
        }
        headers = {
            "Authorization": f"Bearer {META_ACCESS_TOKEN}",
            "Content-Type": "application/json"
        }
        try:
            resp = requests.post(url, json=payload, headers=headers, timeout=10)
            resp.raise_for_status()
            return True
        except requests.RequestException as exc:
            logger.error("Meta WhatsApp interactive list failed for %s: %s", phone, exc)
            return False
            
    return _fallback_list(phone, text, sections)


def _fallback_list(phone: str, text: str, sections: list) -> bool:
    fallback_text = text + "\n\n"
    idx = 1
    for sec in sections:
        fallback_text += f"*{sec.get('title', 'Options')}*\n"
        for row in sec.get('rows', []):
            fallback_text += f"{idx}. {row['title']} - {row.get('description', '')}\n"
            idx += 1
    fallback_text += "\nReply with the item number or name."
    return send_reply(phone, fallback_text)


def send_summit_vip_notification(wallet) -> bool:
    """Congratulate a customer who just hit Summit VIP status."""
    phone = getattr(wallet.customer, 'phone', None) or getattr(wallet.customer, 'phone_number', None) or getattr(wallet.customer, 'contact', None)
    if not phone:
        return False
    return _send(phone, 'summit_vip', [
        wallet.customer.first_name or wallet.customer.username,
        wallet.restaurant.name,
    ])


# ─────────────────────────────────────────────────────────────────────
# Order lifecycle notifications (new)
# ─────────────────────────────────────────────────────────────────────

STATUS_MESSAGES = {
    'CONFIRMED': "✅ Your order #{order_id} at *{restaurant}* has been confirmed!\n⏱️ The kitchen will start preparing shortly.",
    'PREPARING': "👨‍🍳 Your order #{order_id} at *{restaurant}* is now being prepared!\n⏱️ Estimated: {prep_time} minutes.",
    'READY': "🎉 Your order #{order_id} at *{restaurant}* is *READY*!\n🛍️ Please pick it up at the counter.",
    'PARTNER_ASSIGNED': "🛵 A delivery partner has been assigned to your order #{order_id}!\n📍 Your food will be on its way soon.",
    'OUT_FOR_DELIVERY': "🛵 Your order #{order_id} from *{restaurant}* is *out for delivery*!\n📍 Track your order in the HotelFinder app.",
    'DELIVERED': "📦 Your order #{order_id} from *{restaurant}* has been *delivered*!\n⭐ Enjoy your meal! Rate us on the app.",
    'COMPLETED': "✅ Order #{order_id} from *{restaurant}* is *complete*!\n💰 Check your loyalty coins — you may have earned rewards! 🪙",
    'CANCELLED': "❌ Order #{order_id} from *{restaurant}* has been *cancelled*.\nIf you didn't request this, please contact the restaurant.",
}


def send_order_status_update(booking) -> bool:
    """
    Send a WhatsApp notification when booking status changes.
    Called from the Booking post_save signal.
    """
    phone = booking.contact_number
    if not phone:
        phone = getattr(booking.customer, 'phone', None)
    if not phone:
        return False

    template = STATUS_MESSAGES.get(booking.status)
    if not template:
        return False

    # Estimate prep time from menu items
    prep_time = 15
    try:
        max_prep = booking.items.aggregate(
            max_prep=__import__('django.db.models', fromlist=['Max']).Max('menu_item__preparation_time_minutes')
        ).get('max_prep')
        if max_prep:
            prep_time = max_prep
    except Exception:
        pass

    message = template.format(
        order_id=booking.id,
        restaurant=booking.restaurant.name,
        prep_time=prep_time,
    )
    return send_reply(phone, message)


def send_order_confirmation(booking) -> bool:
    """
    Send a rich order confirmation after placement.
    This is separate from the status update — it includes item details.
    """
    phone = booking.contact_number
    if not phone:
        phone = getattr(booking.customer, 'phone', None)
    if not phone:
        return False

    try:
        items_text = "\n".join(
            f"  • {item.quantity}× {item.menu_item.name} — ₹{item.total_price}"
            for item in booking.items.all()
        )
        message = (
            f"📋 *Order #{booking.id} — Receipt*\n\n"
            f"🍽️ {booking.restaurant.name}\n"
            f"📦 {booking.get_booking_type_display()}\n\n"
            f"*Items:*\n{items_text}\n\n"
            f"Subtotal: ₹{booking.subtotal}\n"
            f"Total:    ₹{booking.total_amount}\n\n"
            f"Payment:  {booking.get_payment_status_display()}\n"
            f"Status:   {booking.get_status_display()}\n\n"
            "Thank you for ordering! 🙏"
        )
        return send_reply(phone, message)
    except Exception as exc:
        logger.error("Order confirmation WhatsApp failed for booking %d: %s", booking.id, exc)
        return False
