"""
Africa's Talking SMS Service
Mirrors the old PHP notifs/notifs.php integration.

Every outgoing SMS is logged to the SMSLog table so admins can review
all messages from the SMS Logs page.

Credentials from old system:
  username: Uzuriapps
  apiKey:   atsk_e810a145ccd3a1089769cd17887da70ae76124ff044fa0ab949429e6b388954e6db55009
"""

import logging
from django.conf import settings

logger = logging.getLogger(__name__)


def _get_sms_client():
    """
    Initialise and return the Africa's Talking SMS object.
    
    🔴 SMS DISABLED - API Key commented out to prevent all SMS sending
    This was disabled on 2026-11-11 to stop SMS during data cleanup/re-entry.
    
    TO RE-ENABLE SMS:
    1. Uncomment the lines marked with "# SMS_DISABLED:"
    2. Comment out the "raise Exception" line
    3. Test on one loan/repayment to verify SMS works
    4. Deploy to production
    """
    # SMS_DISABLED: Prevent all SMS from being sent
    raise Exception("SMS functionality is currently disabled. See _get_sms_client() docstring to re-enable.")
    
    # SMS_DISABLED: import africastalking
    # SMS_DISABLED: username = getattr(settings, 'AT_USERNAME', 'Uzuriapps')
    # SMS_DISABLED: api_key  = getattr(settings, 'AT_API_KEY', '')
    # SMS_DISABLED: africastalking.initialize(username, api_key)
    # SMS_DISABLED: return africastalking.SMS


def _admin_numbers():
    """Return the list of admin notification numbers."""
    return ['+254115451752', '+254114457516']


def _normalise_phone(phone):
    """Convert any Kenyan phone format to +2547xxxxxxxx."""
    phone = str(phone).strip()
    if phone.startswith('+'):
        return phone
    if phone.startswith('0'):
        return '+254' + phone[1:]
    if phone.startswith('254'):
        return '+' + phone
    return phone


def _short_name(full_name):
    """
    Return first 2 words of a name to keep SMS short.
    e.g. 'Lucy Wangari Githinji' -> 'Lucy Wangari'
    """
    parts = str(full_name).strip().split()
    return ' '.join(parts[:2]) if parts else full_name


def _log_sms(sms_type, recipients_list, message, sender_id,
             response, loan_number='', borrower_name='', amount=None):
    """Persist every outgoing SMS to SMSLog for admin review."""
    try:
        from payments.sasapay_models import SMSLog

        # Determine delivery status from AT response
        if 'error' in response:
            status = 'failed'
            error_msg = str(response['error'])
        else:
            recips = response.get('SMSMessageData', {}).get('Recipients', [])
            successes = sum(1 for r in recips if r.get('status') == 'Success')
            if successes == 0:
                status = 'failed'
            elif successes < len(recips):
                status = 'partial'
            else:
                status = 'sent'
            error_msg = ''

        SMSLog.objects.create(
            sms_type=sms_type,
            recipients=', '.join(recipients_list),
            message=message,
            sender_id=sender_id,
            status=status,
            at_response=response,
            error_message=error_msg,
            loan_number=loan_number or '',
            borrower_name=borrower_name or '',
            amount=amount,
        )
    except Exception as exc:
        logger.warning(f"Could not save SMS log: {exc}")


def send_sms(recipients, message, sender_id=None,
             sms_type='other', loan_number='', borrower_name='', amount=None):
    """
    Send an SMS via Africa's Talking and log it.

    Args:
        recipients (str | list): Phone number(s) in E.164 or Kenyan format.
        message (str): The SMS body.
        sender_id (str): Alphanumeric sender ID (default: settings.SMS_SENDER_ID).
        sms_type (str): One of the SMS_TYPE_CHOICES keys for the log.
        loan_number (str): Optional loan number for context in the log.
        borrower_name (str): Optional borrower name for context in the log.
        amount (Decimal|float): Optional amount for context in the log.

    Returns:
        dict: The raw AT API response, or an error dict on failure.
    """
    # Check if SMS notifications are enabled system-wide
    from reports.models import SystemSettings
    try:
        settings_obj = SystemSettings.get_settings()
        if not settings_obj.sms_notifications_enabled:
            logger.info(f"SMS notifications disabled - skipping SMS [{sms_type}] to recipients")
            response = {'status': 'skipped', 'message': 'SMS notifications disabled by admin'}
            _log_sms(sms_type, normalised if isinstance(recipients, list) else [recipients], 
                    message, sender_id or 'HavGrazuri', response, loan_number, borrower_name, amount)
            return response
    except Exception as e:
        logger.warning(f"Could not check SMS notifications setting: {e}")
        # Continue with SMS send if we can't check settings
    
    if sender_id is None:
        sender_id = getattr(settings, 'SMS_SENDER_ID', 'HavGrazuri')

    if sender_id == '':
        sender_id = None

    if isinstance(recipients, str):
        recipients = [r.strip() for r in recipients.split(',') if r.strip()]

    normalised = [_normalise_phone(p) for p in recipients]

    try:
        sms      = _get_sms_client()
        response = sms.send(message, normalised, sender_id)
        logger.info(f"SMS [{sms_type}] sent to {normalised}: {response}")
    except Exception as exc:
        logger.error(f"SMS send failed to {normalised}: {exc}")
        response = {'error': str(exc)}

    _log_sms(sms_type, normalised, message, sender_id,
             response, loan_number, borrower_name, amount)
    return response


# ---------------------------------------------------------------------------
# Convenience helpers — each maps to a specific notification event
# ---------------------------------------------------------------------------

def send_payment_confirmation_sms(borrower_name, amount, reference,
                                   loan_number, new_balance, customer_phone):
    """
    Payment confirmed — sent to admin numbers + customer.
    Format: Confirmed KES X paid to Haven Grazuri by NAME on DATE. New loan bal KES X
    """
    from datetime import datetime
    date_only = datetime.now().strftime('%d/%m/%Y')
    name = _short_name(borrower_name)
    message = (
        f"{reference} Confirmed KES {amount:,.2f} paid to Haven Grazuri by "
        f"{name} on {date_only}. "
        f"New loan bal KES {new_balance:,.2f}."
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='payment_confirmation',
                    loan_number=loan_number,
                    borrower_name=borrower_name,
                    amount=amount)


def send_unknown_payment_sms(full_name, bill_ref, amount, reference, customer_phone):
    """Unrecognised payment — notify admins + sender."""
    from datetime import datetime
    date_only = datetime.now().strftime('%d/%m/%Y')
    name = _short_name(full_name)
    message = (
        f"Confirmed KES {amount:,.2f} unknown payment to Haven Grazuri "
        f"by {name} on {date_only}. Ref: {reference}"
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='unknown_payment',
                    borrower_name=full_name,
                    amount=amount)


def send_loan_disbursement_sms(borrower_name, amount, loan_number, customer_phone):
    """Loan disbursed — notify borrower + admins."""
    from datetime import datetime
    date_only = datetime.now().strftime('%d/%m/%Y')
    name = _short_name(borrower_name)
    message = (
        f"Dear {name}, KES {amount:,.2f} disbursed to your M-Pesa "
        f"for loan {loan_number} on {date_only}. HAVEN GRAZURI."
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='loan_disbursement',
                    loan_number=loan_number,
                    borrower_name=borrower_name,
                    amount=amount)


def send_loan_approval_sms(borrower_name, amount, loan_number, customer_phone):
    """Loan approved — notify borrower + admin numbers."""
    name = _short_name(borrower_name)
    message = (
        f"Dear {name}, your loan {loan_number} for "
        f"KES {amount:,.2f} has been APPROVED. "
        f"Disbursement follows shortly. HAVEN GRAZURI."
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='loan_approval',
                    loan_number=loan_number,
                    borrower_name=borrower_name,
                    amount=amount)


def send_overdue_reminder_sms(borrower_name, overdue_amount, loan_number, customer_phone):
    """Overdue payment reminder — notify borrower + admin numbers."""
    name = _short_name(borrower_name)
    message = (
        f"Dear {name}, loan {loan_number} has an overdue balance of "
        f"KES {overdue_amount:,.2f}. Pay now to avoid penalties. "
        f"HAVEN GRAZURI."
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='overdue_reminder',
                    loan_number=loan_number,
                    borrower_name=borrower_name,
                    amount=overdue_amount)


def send_processing_fee_sms(borrower_name, amount, customer_phone, reference='', loan_number=''):
    """Processing fee paid — notify borrower + admin numbers."""
    from datetime import datetime
    date_only = datetime.now().strftime('%d/%m/%Y')
    name = _short_name(borrower_name)
    ref_prefix = f"{reference} " if reference else ''
    message = (
        f"{ref_prefix}Confirmed KES {float(amount):,.2f} processing fee paid to "
        f"Haven Grazuri by {name} on {date_only}."
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='processing_fee',
                    loan_number=loan_number,
                    borrower_name=borrower_name,
                    amount=amount)


def send_stk_push_initiated_sms(customer_phone, amount, loan_number):
    """STK push sent — notify borrower + admin numbers."""
    message = (
        f"Payment request KES {float(amount):,.2f} for loan {loan_number} "
        f"sent to {customer_phone}. Enter M-Pesa PIN to complete. "
        f"HAVEN GRAZURI."
    )
    recipients = _admin_numbers() + [customer_phone]
    return send_sms(recipients, message,
                    sms_type='stk_push',
                    loan_number=loan_number,
                    amount=amount)
