"""
SasaPay Payment Service
Mirrors the old PHP integration exactly:
  - application/include/sapapaystkpush.php          (C2B STK push)
  - application/include/sasapayfundsdisbursement.php (B2C disbursement)
  - SasaPayIPN.php                                   (IPN callback handler)
  - application/include/sasapaystkpushprocessor.php  (STK result callback)
  - application/include/sasapayfundsdisbursementprocessor.php (B2C result callback)

Old PHP credentials (unchanged):
  client_id:     e63utew7Vk3RmwKxjuMY3jocycFb5eoMZkzyKrPQ
  client_secret: 6ysF7fWBESaCNYfsh4aJOWxijTFx4JFIu5LqGFWnMx7TJxKiwaysaiNwe14Wgj9...
  merchant_code: 1122
  network_code:  63902  (M-Pesa via SasaPay)

Old PHP callback base URL: https://grazuri.uzuriapps.xyz (now https://uzuriapps.xyz via SITE_URL)
  STK push callback:    /payments/sasapay/stk-callback/
  Disbursement callback:/payments/sasapay/disbursement-callback/
  IPN (C2B):            /payments/sasapay/ipn/
"""

import requests
import base64
import logging
from datetime import datetime, timedelta
from django.conf import settings

logger = logging.getLogger(__name__)

# VERSION MARKER — update this to confirm server is running latest code
_SASAPAY_SERVICE_VERSION = 'v5-no-silent-drops-2026-06-15'

SASAPAY_BASE_URL = 'https://api.sasapay.app/api/v1'
TOKEN_URL        = f'{SASAPAY_BASE_URL}/auth/token/?grant_type=client_credentials'
STK_PUSH_URL     = f'{SASAPAY_BASE_URL}/payments/request-payment/'
B2C_URL          = f'{SASAPAY_BASE_URL}/payments/b2c/'


def _get_credentials():
    return {
        'client_id':     getattr(settings, 'SASAPAY_CLIENT_ID',
                                 'e63utew7Vk3RmwKxjuMY3jocycFb5eoMZkzyKrPQ'),
        'client_secret': getattr(settings, 'SASAPAY_CLIENT_SECRET',
                                 '6ysF7fWBESaCNYfsh4aJOWxijTFx4JFIu5LqGFWnMx7TJxKiwaysaiNwe14Wgj9'
                                 'FupB6fhtRFZUas2geZZLjHwbHiShbX8w5bvWjy061Bq1SHX9EQtsBCtnuTLgaOmDV'),
        'merchant_code': getattr(settings, 'SASAPAY_MERCHANT_CODE', '1122'),
        'network_code':  getattr(settings, 'SASAPAY_NETWORK_CODE', '63902'),
    }


def _get_base_url():
    """
    Return the base callback URL for this deployment.
    Uses grazuri.uzuriapps.xyz — the domain that actually serves this Django app.
    """
    return getattr(settings, 'SITE_URL', 'https://grazuri.uzuriapps.xyz').rstrip('/')


# ---------------------------------------------------------------------------
# Token management — simple in-memory cache (mirrors PHP's per-request fetch)
# ---------------------------------------------------------------------------
_token_cache = {'token': None, 'expires_at': None}


def get_access_token(force_refresh=False):
    """
    Obtain a SasaPay OAuth2 access token using client credentials.
    Mirrors the curl GET to TOKEN_URL in sapapaystkpush.php / sasapayfundsdisbursement.php.
    Caches the token until it expires (avoids a round-trip on every request).
    """
    now = datetime.utcnow()
    if (not force_refresh
            and _token_cache['token']
            and _token_cache['expires_at']
            and now < _token_cache['expires_at']):
        return _token_cache['token']

    creds = _get_credentials()
    auth_header = base64.b64encode(
        f"{creds['client_id']}:{creds['client_secret']}".encode()
    ).decode()

    try:
        resp = requests.get(TOKEN_URL,
                            headers={'Authorization': f'Basic {auth_header}'},
                            timeout=30)
        resp.raise_for_status()
        data  = resp.json()
        token = data.get('access_token')
        if not token:
            raise ValueError(f"No access_token in response: {data}")

        expires_in = int(data.get('expires_in', 3600))
        _token_cache['token']      = token
        _token_cache['expires_at'] = now + timedelta(seconds=expires_in - 60)
        logger.info("SasaPay access token obtained successfully.")
        return token
    except Exception as exc:
        logger.error(f"Failed to get SasaPay access token: {exc}")
        raise


# ---------------------------------------------------------------------------
# C2B STK Push — mirrors sapapaystkpush.php
# Old PHP callback: https://grazuri.uzuriapps.xyz/application/include/sasapaystkpushprocessor.php
# New Django URL:   /payments/sasapay/stk-callback/
# ---------------------------------------------------------------------------

def initiate_stk_push(phone_number, amount, account_reference,
                      transaction_desc='Request Payment for Loan processing fees',
                      callback_url=None):
    """
    Send an STK push to a customer's phone via SasaPay.
    Mirrors the curl POST in sapapaystkpush.php exactly.

    Args:
        phone_number (str): Customer phone — any Kenyan format, normalised to 2547xxxxxxxx.
        amount (float|Decimal): Amount to collect.
        account_reference (str): Loan account number / reference (AccountReference field).
        transaction_desc (str): Short description shown on the phone.
        callback_url (str): Override the default callback URL.
    """
    creds = _get_credentials()
    token = get_access_token()

    if callback_url is None:
        callback_url = getattr(
            settings,
            'SASAPAY_STK_CALLBACK_URL',
            f"{_get_base_url()}/application/include/sasapaystkpushprocessor.php"
        )

    phone = _normalise_phone_e164_no_plus(phone_number)

    payload = {
        'MerchantCode':      creds['merchant_code'],   # '1122'
        'NetworkCode':       creds['network_code'],    # '63902'
        'TransactionFee':    '0',
        'Currency':          'KES',
        'Amount':            str(amount),
        'CallBackURL':       callback_url,
        'PhoneNumber':       phone,
        'TransactionDesc':   transaction_desc,
        'AccountReference':  account_reference,
    }

    try:
        resp = requests.post(STK_PUSH_URL,
                             json=payload,
                             headers={'Authorization': f'Bearer {token}',
                                      'Content-Type': 'application/json'},
                             timeout=30)
        resp.raise_for_status()
        data = resp.json()
        logger.info(f"STK push initiated for {phone}, ref={account_reference}: {data}")
        return data
    except Exception as exc:
        logger.error(f"STK push failed for {phone}: {exc}")
        raise


# ---------------------------------------------------------------------------
# B2C Disbursement — mirrors sasapayfundsdisbursement.php
# Old PHP callback: https://grazuri.uzuriapps.xyz/application/include/sasapayfundsdisbursementprocessor.php
# New Django URL:   /payments/sasapay/disbursement-callback/
# ---------------------------------------------------------------------------

def disburse_loan(phone_number, amount, loan_reference, callback_url=None):
    """
    Disburse loan funds to a borrower via SasaPay B2C.
    Mirrors the curl POST in sasapayfundsdisbursement.php exactly.

    Args:
        phone_number (str): Recipient phone — any Kenyan format.
        amount (float|Decimal): Amount to disburse.
        loan_reference (str): Loan account number (MerchantTransactionReference).
        callback_url (str): Override the default callback URL.
    """
    creds = _get_credentials()
    token = get_access_token()

    if callback_url is None:
        callback_url = getattr(
            settings,
            'SASAPAY_DISB_CALLBACK_URL',
            f"{_get_base_url()}/application/include/sasapayfundsdisbursementprocessor.php"
        )

    phone = _normalise_phone_e164_no_plus(phone_number)

    payload = {
        'MerchantCode':                 creds['merchant_code'],  # '1122'
        'MerchantTransactionReference': loan_reference,
        'Amount':                       str(amount),
        'Currency':                     'KES',
        'ReceiverNumber':               phone,
        'Channel':                      creds['network_code'],   # '63902'
        'Reason':                       'Loan disbursement',
        'CallBackURL':                  callback_url,
    }

    try:
        resp = requests.post(B2C_URL,
                             json=payload,
                             headers={'Authorization': f'Bearer {token}',
                                      'Content-Type': 'application/json'},
                             timeout=30)
        resp.raise_for_status()
        data = resp.json()
        logger.info(f"B2C disbursement initiated for {phone}, ref={loan_reference}: {data}")
        return data
    except Exception as exc:
        logger.error(f"B2C disbursement failed for {phone}: {exc}")
        raise


# ---------------------------------------------------------------------------
# IPN Callback processor — mirrors SasaPayIPN.php (root) exactly
#
# Old PHP matching logic:
#   1. SELECT * FROM borrowers WHERE phone='$billRefNumber' AND status='Active'
#   2. If found and has loan balance → insert into payments table
#   3. If no balance → insert into unknown_payments
#   4. Also check if billRefNumber matches a loan account (STK push for fees)
#
# Key: BillRefNumber = customer's phone number (primary match)
#      ThirdPartyTransID = M-Pesa reference (used in SMS as $reference)
# ---------------------------------------------------------------------------

def process_ipn_callback(data):
    """
    Process an incoming SasaPay IPN (C2B payment notification).

    Design principles:
      - Write IPN log FIRST, before anything else, so no payment is ever
        invisible regardless of what fails later.
      - The duplicate guard is DB-level (trans_id on the log row) not
        application-level, so SasaPay retries are idempotent.
      - Every failure path updates processing_status on the log row so the
        admin dashboard shows exactly what happened to every IPN.
      - The repayment INSERT is raw SQL inside its own atomic() block,
        completely isolated from all other logic, so a receipt-number
        collision or any other error can never roll it back silently.
      - SMS and receipt creation run AFTER the repayment is committed and
        are fully isolated — their failure never affects payment recording.
      - Admin alert SMS is sent for every non-duplicate failure so nothing
        is silent.
    """
    from decimal import Decimal
    from django.utils import timezone

    # ── Extract fields ──────────────────────────────────────────────────────
    trans_id     = (data.get('TransID') or '').strip()
    mpesa_ref    = (data.get('ThirdPartyTransID') or '').strip()
    full_name    = (data.get('FullName') or '').strip()
    first_name   = (data.get('FirstName') or '').strip()
    middle_name  = (data.get('MiddleName') or '').strip()
    last_name    = (data.get('LastName') or '').strip()
    msisdn       = (data.get('MSISDN') or '').strip()
    bill_ref     = (data.get('BillRefNumber') or '').strip()
    trans_time   = datetime.now()

    try:
        trans_amount = Decimal(str(data.get('TransAmount', '0')))
    except Exception:
        trans_amount = Decimal('0')

    logger.info(
        f"SasaPay IPN received: TransID={trans_id!r}, MPesaRef={mpesa_ref!r}, "
        f"Amount={trans_amount}, BillRef={bill_ref!r}, Name={first_name} {last_name}"
    )

    # ── STEP 0: Write IPN log immediately ───────────────────────────────────
    # This happens before ANYTHING else. If we crash after this line the IPN
    # is still visible in the admin and can be replayed.
    ipn_log = _save_sasapay_ipn_log(data, trans_id=trans_id)

    # ── STEP 1: Duplicate guard ─────────────────────────────────────────────
    # Check both the IPN log (new field) and the repayments table.
    # This handles retries from SasaPay and covers legacy rows that predate
    # the trans_id column.
    if trans_id:
        from loans.models import Repayment

        # Check repayments table first (covers all historical payments)
        if Repayment.objects.filter(mpesa_transaction_id=trans_id).exists():
            logger.info(f"SasaPay IPN: {trans_id} already processed (repayment exists) — ack.")
            ipn_log.mark(SasaPayIPNLog.STATUS_DUPLICATE, note='Repayment already exists')
            return {'success': True, 'message': 'Already processed'}

        # Check if another IPN log for this TransID is already processed
        existing = SasaPayIPNLog.objects.filter(
            trans_id=trans_id,
            processing_status=SasaPayIPNLog.STATUS_PROCESSED,
        ).exclude(pk=ipn_log.pk).first()
        if existing:
            logger.info(f"SasaPay IPN: {trans_id} already processed (IPN log) — ack.")
            ipn_log.mark(SasaPayIPNLog.STATUS_DUPLICATE,
                         note=f'Duplicate of IPN log {existing.pk}')
            return {'success': True, 'message': 'Already processed'}

    # ── STEP 2: Match borrower ──────────────────────────────────────────────
    from users.models import CustomUser
    from loans.models import Loan

    borrower      = None
    _matched_loan = None
    match_method  = None

    # 2a. BillRefNumber as phone — tries exact variant match then last-9
    #     fallback, so the format stored in the DB never matters.
    if bill_ref:
        borrower, match_method = _match_borrower_by_phone(bill_ref)
        if borrower:
            match_method = f"BillRef {match_method}"

    # 2b. BillRefNumber as ID number
    if borrower is None and bill_ref:
        try:
            borrower = CustomUser.objects.get(
                id_number=bill_ref, role='borrower', is_active=True,
            )
            match_method = f"BillRef ID number '{bill_ref}'"
        except CustomUser.DoesNotExist:
            pass
        except CustomUser.MultipleObjectsReturned:
            borrower = CustomUser.objects.filter(
                id_number=bill_ref, role='borrower', is_active=True,
            ).first()
            match_method = f"BillRef ID number '{bill_ref}' (first of multiple)"

    # 2c. BillRefNumber as loan number
    if borrower is None and bill_ref:
        try:
            loan_by_ref = Loan.active_objects.get(loan_number=bill_ref, status='active')
            borrower      = loan_by_ref.borrower
            _matched_loan = loan_by_ref
            match_method  = f"loan number '{bill_ref}'"
        except (Loan.DoesNotExist, Loan.MultipleObjectsReturned):
            pass

    # 2d. MSISDN — SasaPay usually hashes this, but try anyway.
    #     Same format-agnostic matching as 2a.
    if borrower is None and msisdn and len(msisdn) < 20:
        borrower, match_method = _match_borrower_by_phone(msisdn)
        if borrower:
            match_method = f"MSISDN {match_method}"

    if borrower is None:
        note = (
            f"No borrower matched. BillRef={bill_ref!r} MSISDN={msisdn!r} "
            f"Name={first_name} {last_name} Amount={trans_amount}"
        )
        logger.warning(f"SasaPay IPN {trans_id}: {note}")
        ipn_log.mark(SasaPayIPNLog.STATUS_NO_MATCH, note=note)
        _save_unknown_sasapay_payment(
            amount=trans_amount, paid_by=full_name or f"{first_name} {last_name}".strip(),
            msisdn=msisdn, bill_ref=bill_ref, reference=mpesa_ref, notes=note,
        )
        _send_admin_alert(
            f"⚠️ SasaPay payment KES {trans_amount} NOT recorded.\n"
            f"No borrower matched.\n"
            f"BillRef: {bill_ref}\nName: {first_name} {last_name}\n"
            f"TransID: {trans_id}\nRef: {mpesa_ref}\n"
            f"Check: /payments/sasapay/unknown-payments/"
        )
        return {'success': False, 'message': 'No matching borrower'}

    logger.info(f"SasaPay IPN {trans_id}: matched borrower {borrower} via {match_method}")

    # ── STEP 3: Find active loan ────────────────────────────────────────────
    if _matched_loan is None:
        _matched_loan = (
            Loan.active_objects
            .filter(borrower=borrower, status='active')
            .order_by('-id')
            .first()
        )

    if _matched_loan is None:
        # Check if this is a processing fee payment (borrower has no active loan)
        # Processing fees are paid before loan approval, so no active loan is expected
        any_loan  = Loan.objects.filter(borrower=borrower).order_by('-id').first()
        loan_hint = (
            f"last loan: {any_loan.loan_number} status={any_loan.status}"
            if any_loan else "no loans at all"
        )
        
        # Treat as processing fee if borrower exists but has no active loan
        note = (
            f"Processing fee payment: Borrower {borrower.get_full_name()} matched via {match_method} "
            f"but has no active loan ({loan_hint}). Amount={trans_amount}"
        )
        logger.info(f"SasaPay IPN {trans_id}: {note}")
        ipn_log.mark(SasaPayIPNLog.STATUS_NO_LOAN, note=note)
        _save_unknown_sasapay_payment(
            amount=trans_amount, paid_by=borrower.get_full_name(),
            msisdn=msisdn, bill_ref=bill_ref, reference=mpesa_ref, notes=note,
        )
        
        # Send processing fee confirmation SMS instead of error alert
        try:
            from .sms_service import send_processing_fee_sms
            customer_phone = _normalise_phone(bill_ref) if bill_ref else _normalise_phone(msisdn)
            borrower_name  = (
                f"{first_name} {middle_name} {last_name}".replace('  ', ' ').strip()
                or full_name
                or borrower.get_full_name()
            )
            send_processing_fee_sms(
                borrower_name=borrower_name,
                amount=trans_amount,
                customer_phone=customer_phone,
                reference=mpesa_ref or trans_id,
                loan_number='',
            )
            logger.info(f"SasaPay IPN {trans_id}: processing fee SMS sent")
        except Exception as sms_exc:
            logger.error(f"SasaPay IPN {trans_id}: processing fee SMS failed: {sms_exc}")
        
        return {'success': True, 'message': 'Processing fee recorded'}

    loan = _matched_loan

    # ── STEP 4: Outstanding balance check ───────────────────────────────────
    # If outstanding_amount property crashes, we proceed anyway (the balance
    # calculation is broken, not the payment itself).
    try:
        outstanding = loan.outstanding_amount
    except Exception as oa_exc:
        logger.error(
            f"SasaPay IPN {trans_id}: outstanding_amount raised for "
            f"{loan.loan_number}: {oa_exc}. Proceeding."
        )
        outstanding = Decimal('999999')

    if outstanding <= 0:
        note = (
            f"Loan {loan.loan_number} outstanding={outstanding} (fully paid). "
            f"Amount={trans_amount}"
        )
        logger.warning(f"SasaPay IPN {trans_id}: {note}")
        ipn_log.mark(SasaPayIPNLog.STATUS_NO_BALANCE, note=note)
        _save_unknown_sasapay_payment(
            amount=trans_amount, paid_by=borrower.get_full_name(),
            msisdn=msisdn, bill_ref=bill_ref, reference=mpesa_ref, notes=note,
        )
        _send_admin_alert(
            f"⚠️ SasaPay payment KES {trans_amount} NOT recorded.\n"
            f"Borrower: {borrower.get_full_name()}\n"
            f"Reason: loan {loan.loan_number} is fully paid (balance=0)\n"
            f"TransID: {trans_id}\nRef: {mpesa_ref}\n"
            f"Check: /payments/sasapay/unknown-payments/"
        )
        return {'success': False, 'message': 'No outstanding balance'}

    # ── STEP 5: Create repayment ────────────────────────────────────────────
    # Raw SQL INSERT inside its own atomic() block, completely bypassing
    # Repayment.save() and its nested savepoints that cause silent rollbacks
    # on MySQL when there's a receipt-number collision.
    import uuid as _uuid
    from django.db import connection as _conn
    from django.db import transaction as _tx

    norm_phone  = _normalise_phone(bill_ref if bill_ref else msisdn)
    if len(norm_phone) > 17:
        norm_phone = norm_phone[:17]
    rep_id      = _uuid.uuid4().hex
    loan_id_str = str(loan.id).replace('-', '')

    # Pick receipt number under advisory lock — prevents race conditions
    # between concurrent IPN callbacks arriving simultaneously.
    LOCK_NAME    = 'havengrazuri_ipn_receipt_lock'
    LOCK_TIMEOUT = 10
    BLACKLISTED  = {1618, 2440}
    receipt_num  = None

    try:
        with _conn.cursor() as _cur:
            _cur.execute("SELECT GET_LOCK(%s, %s)", [LOCK_NAME, LOCK_TIMEOUT])
            lock_result = _cur.fetchone()[0]
            if not lock_result:
                raise RuntimeError("Could not acquire IPN receipt lock after 10s")
            try:
                _cur.execute(
                    "SELECT MAX(CAST(SUBSTRING(receipt_number,5) AS UNSIGNED)) "
                    "FROM repayments WHERE receipt_number REGEXP '^RCP-[0-9]+$'"
                )
                max_rep = _cur.fetchone()[0] or 0
                _cur.execute(
                    "SELECT MAX(CAST(SUBSTRING(receipt_number,5) AS UNSIGNED)) "
                    "FROM receipts WHERE receipt_number REGEXP '^RCP-[0-9]+$'"
                )
                max_rec = _cur.fetchone()[0] or 0
                next_n = max(max_rep, max_rec) + 1
                while next_n in BLACKLISTED:
                    next_n += 1
                receipt_num = f"RCP-{next_n:06d}"
            finally:
                _cur.execute("SELECT RELEASE_LOCK(%s)", [LOCK_NAME])

        # Insert repayment and update loan cache in one atomic block.
        # This is the ONLY write that matters — everything else is cosmetic.
        with _tx.atomic():
            with _conn.cursor() as _cur:
                _cur.execute("""
                    INSERT INTO repayments
                        (id, loan_id, amount, payment_method, payment_source,
                         mpesa_transaction_id, mpesa_phone_number,
                         receipt_number, payment_date, created_at)
                    VALUES (%s, %s, %s, 'mpesa', 'automatic', %s, %s, %s, %s, NOW())
                """, [rep_id, loan_id_str, float(trans_amount),
                      trans_id, norm_phone, receipt_num, trans_time])

                _cur.execute("""
                    UPDATE loans SET
                        amount_paid = COALESCE(
                            (SELECT SUM(amount) FROM repayments WHERE loan_id=%s), 0),
                        last_payment_date = %s,
                        updated_at = NOW()
                    WHERE id = %s
                """, [loan_id_str, trans_time, loan_id_str])

        # Mark IPN log as successfully processed
        ipn_log.mark(SasaPayIPNLog.STATUS_PROCESSED,
                     note=f"Repayment {receipt_num} created for loan {loan.loan_number}",
                     receipt=receipt_num)

        logger.info(
            f"SasaPay IPN {trans_id}: repayment {receipt_num} committed "
            f"for loan {loan.loan_number}, amount={trans_amount}"
        )

    except Exception as exc:
        note = f"Repayment INSERT failed: {exc}"
        logger.error(f"SasaPay IPN {trans_id}: {note}", exc_info=True)
        ipn_log.mark(SasaPayIPNLog.STATUS_FAILED, note=note)
        _send_admin_alert(
            f"🚨 SasaPay payment KES {trans_amount} FAILED to record!\n"
            f"Borrower: {borrower.get_full_name()}\n"
            f"Loan: {loan.loan_number}\n"
            f"TransID: {trans_id}\nRef: {mpesa_ref}\n"
            f"Error: {exc}\n"
            f"IPN IS LOGGED — payment can be recovered from:\n"
            f"/payments/sasapay/ipn-gaps/"
        )
        # Return success=True so SasaPay stops retrying (the IPN IS logged
        # and can be replayed manually). Returning failure causes SasaPay
        # to retry, which can create duplicates once the DB recovers.
        return {'success': True, 'message': 'Logged — processing error, will be recovered'}

    # ── STEP 6: Create Receipt row (isolated — failure is non-fatal) ────────
    try:
        from utils.models import Receipt
        from loans.models import Repayment as _Rep, Loan as _Loan
        from django.db.models import Sum as _Sum

        _rep_obj  = _Rep.objects.get(pk=rep_id)
        _loan_obj = _Loan.objects.get(pk=loan.id)

        if not Receipt.objects.filter(repayment=_rep_obj).exists():
            prev_paid = _Rep.objects.filter(
                loan_id=_loan_obj.id,
                payment_date__lt=trans_time,
            ).exclude(pk=rep_id).aggregate(t=_Sum('amount'))['t'] or Decimal('0')

            Receipt.objects.create(
                repayment      = _rep_obj,
                loan           = _loan_obj,
                borrower       = borrower,
                receipt_number = receipt_num,
                amount_paid    = trans_amount,
                payment_method = 'mpesa',
                payment_date   = trans_time,
                previous_balance = _loan_obj.principal_amount - prev_paid,
                new_balance      = _loan_obj.principal_amount - prev_paid - trans_amount,
            )
            logger.info(f"SasaPay IPN {trans_id}: Receipt {receipt_num} created.")
    except Exception as receipt_exc:
        logger.error(
            f"SasaPay IPN {trans_id}: Receipt creation failed "
            f"(repayment IS committed): {receipt_exc}",
            exc_info=True,
        )

    # ── STEP 7: Confirmation SMS ────────────────────────────────────────────
    try:
        from .sms_service import send_payment_confirmation_sms
        try:
            loan.refresh_from_db()
            new_balance = float(loan.outstanding_amount)
        except Exception:
            new_balance = max(0.0, float(outstanding) - float(trans_amount))

        customer_phone = _normalise_phone(bill_ref) if bill_ref else _normalise_phone(msisdn)
        borrower_name  = (
            f"{first_name} {middle_name} {last_name}".replace('  ', ' ').strip()
            or full_name
            or borrower.get_full_name()
        )
        send_payment_confirmation_sms(
            borrower_name  = borrower_name,
            amount         = float(trans_amount),
            reference      = mpesa_ref or trans_id,
            loan_number    = loan.loan_number,
            new_balance    = new_balance,
            customer_phone = customer_phone,
        )
    except Exception as sms_exc:
        logger.error(f"SasaPay IPN {trans_id}: confirmation SMS failed: {sms_exc}")

    return {
        'success':        True,
        'message':        'Payment processed',
        'receipt_number': receipt_num,
        'loan_number':    loan.loan_number,
    }


# ---------------------------------------------------------------------------
# STK Push result callback — mirrors sasapaystkpushprocessor.php
# Old PHP: INSERT INTO stkpushresults (MerchantLoanRef, SasaPayRef, ResultCode,
#          ResultDesc, TransAmount, TransactionDate)
# ---------------------------------------------------------------------------

def process_stk_callback(data):
    """
    Process the STK push result callback from SasaPay.
    Mirrors sasapaystkpushprocessor.php exactly.

    Expected fields:
        CheckoutRequestID, ResultCode, ResultDesc, SourceChannel,
        TransAmount, TransactionDate
    """
    checkout_id  = data.get('CheckoutRequestID', '')
    result_code  = str(data.get('ResultCode', ''))
    result_desc  = data.get('ResultDesc', '')
    trans_amount = data.get('TransAmount', 0)
    # Old PHP also stored MerchantLoanRef from the most recent loan — we store
    # it in the checkout_request_id field and leave merchant_loan_ref blank
    # since we don't have session context here.

    logger.info(
        f"SasaPay STK callback: CheckoutID={checkout_id}, "
        f"ResultCode={result_code}, Desc={result_desc}"
    )
    _save_stk_result(checkout_id, result_code, result_desc, trans_amount)
    return {'success': result_code == '0', 'result_desc': result_desc}


# ---------------------------------------------------------------------------
# B2C Disbursement result callback — mirrors sasapayfundsdisbursementprocessor.php
# Old PHP: INSERT INTO b2cpaymentsresults (MerchantLoanRef, SasaPayRef, MPesaRef,
#          ResultCode, ResultDesc, TransAmount, SasaPayAccBalance, TransactionDate)
# Then Querysasapayfundsdisbursement.php updates loan status and GL accounts.
# ---------------------------------------------------------------------------

def process_disbursement_callback(data):
    """
    Process the B2C disbursement result callback from SasaPay.
    Mirrors sasapayfundsdisbursementprocessor.php + Querysasapayfundsdisbursement.php.

    Expected fields:
        SasaPayTransactionID, ResultCode, ResultDesc, SourceChannel,
        ThirdPartyTransactionCode (M-Pesa ref), TransactionAmount,
        MerchantAccountBalance, MerchantTransactionReference (loan ref),
        TransactionDate
    """
    sasapay_tx_id = data.get('SasaPayTransactionID', '')
    result_code   = str(data.get('ResultCode', ''))
    result_desc   = data.get('ResultDesc', '')
    mpesa_ref     = data.get('ThirdPartyTransactionCode', '')
    amount        = data.get('TransactionAmount', 0)
    balance       = data.get('MerchantAccountBalance', 0)
    loan_ref      = data.get('MerchantTransactionReference', '')

    logger.info(
        f"SasaPay disbursement callback: TxID={sasapay_tx_id}, "
        f"ResultCode={result_code}, LoanRef={loan_ref}, MPesaRef={mpesa_ref}"
    )

    # Persist result (mirrors INSERT INTO b2cpaymentsresults)
    _save_disbursement_result(
        loan_ref, sasapay_tx_id, mpesa_ref,
        result_code, result_desc, amount, balance,
    )

    if result_code == '0':
        # Mirrors Querysasapayfundsdisbursement.php: update loan status to active
        try:
            from loans.models import Loan
            loan = Loan.active_objects.filter(loan_number=loan_ref).first()
            if loan and loan.status == 'approved':
                loan.status = 'active'
                loan.save(update_fields=['status'])
                logger.info(f"Loan {loan_ref} activated after successful disbursement.")

                # Send disbursement SMS to borrower + admins
                try:
                    from .sms_service import send_loan_disbursement_sms
                    phone = _normalise_phone(
                        getattr(loan.borrower, 'phone_number', '')
                        or getattr(loan.borrower, 'phone', '')
                    )
                    send_loan_disbursement_sms(
                        borrower_name=loan.borrower.get_full_name(),
                        amount=float(amount),
                        loan_number=loan_ref,
                        customer_phone=phone,
                    )
                except Exception as sms_exc:
                    logger.error(f"Disbursement SMS failed: {sms_exc}")
        except Exception as exc:
            logger.error(f"Failed to update loan after disbursement: {exc}")

    return {'success': result_code == '0', 'result_desc': result_desc}


# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------

def _normalise_phone(phone):
    """
    Convert any Kenyan phone format to +254XXXXXXXXX (E.164).

    Handles all Kenyan prefixes — 07x (Safaricom/Telkom/Equitel),
    01x (Airtel/Faiba) — and all common storage variants:
        0XXXXXXXXX   → +254XXXXXXXXX
        254XXXXXXXXX → +254XXXXXXXXX
        +254XXXXXXXXX → unchanged
    """
    phone = str(phone).strip()
    if not phone:
        return phone
    if phone.startswith('+254'):
        return phone
    if phone.startswith('254'):
        return '+' + phone
    if phone.startswith('0'):
        return '+254' + phone[1:]
    return phone


def _normalise_phone_e164_no_plus(phone):
    """
    Convert any Kenyan phone format to 254XXXXXXXXX (no leading +),
    as required by the SasaPay API.

    Handles 07x, 01x, +254x, and 254x prefixes.
    """
    phone = str(phone).strip()
    if phone.startswith('+'):
        phone = phone[1:]
    if phone.startswith('0'):
        phone = '254' + phone[1:]
    return phone


def _phone_variants(phone):
    """
    Return ALL storage-format variants of a Kenyan phone number.

    Kenyan mobile numbers use both 07x (Safaricom, Telkom, Equitel)
    and 01x (Airtel, Faiba) prefixes.  The local part after the country
    code is always 9 digits.  Recognised input formats:

        0XXXXXXXXX   (10 digits, local format)
        +254XXXXXXXXX (12 chars,  E.164 with plus)
        254XXXXXXXXX  (12 digits, E.164 without plus)

    All three variants are generated regardless of whether the subscriber
    prefix is 01x or 07x, so a DB match succeeds no matter which format
    was stored at registration time.
    """
    phone = str(phone).strip()
    if not phone:
        return []
    variants = {phone}

    if phone.startswith('0') and len(phone) == 10:
        # 0XXXXXXXXX → +254XXXXXXXXX and 254XXXXXXXXX
        variants.add('+254' + phone[1:])
        variants.add('254' + phone[1:])

    elif phone.startswith('+254') and len(phone) == 13:
        # +254XXXXXXXXX → 254XXXXXXXXX and 0XXXXXXXXX
        variants.add(phone[1:])          # 254XXXXXXXXX
        variants.add('0' + phone[4:])    # 0XXXXXXXXX

    elif phone.startswith('254') and len(phone) == 12:
        # 254XXXXXXXXX → +254XXXXXXXXX and 0XXXXXXXXX
        variants.add('+' + phone)        # +254XXXXXXXXX
        variants.add('0' + phone[3:])    # 0XXXXXXXXX

    # If the length doesn't match exactly (e.g. partial/truncated numbers),
    # still return at least the original so the last-9 fallback can run.
    return list(dict.fromkeys(variants))  # deduplicate, preserve insertion order


def _phone_last9(phone: str) -> str:
    """
    Strip all non-digit characters and return the last 9 digits.
    This is the format-independent core of any Kenyan mobile number
    (e.g. 07XXXXXXXX, +2547XXXXXXXX, 2547XXXXXXXX all share the same last 9).
    Used as a fallback when the explicit variant list doesn't match.
    """
    digits = ''.join(c for c in str(phone) if c.isdigit())
    return digits[-9:] if len(digits) >= 9 else digits


def _match_borrower_by_phone(phone_value: str):
    """
    Try every possible format of *phone_value* against CustomUser.phone_number.

    Strategy (in order of precision):
      1. Exact match on any of the three standard Kenyan variants.
         Uses a single DB query with __in for efficiency.
      2. Last-9-digits suffix match — catches any unexpected format stored
         in the DB (e.g. spaces, dots, truncated country code, etc.).

    Returns (borrower, match_description) or (None, None).
    """
    from users.models import CustomUser

    if not phone_value or str(phone_value).startswith('NOPHONE-'):
        return None, None

    # ── Pass 1: exact variant match (one query) ──────────────────────────
    variants = _phone_variants(phone_value)
    qs = CustomUser.objects.filter(
        phone_number__in=variants, role='borrower', is_active=True,
    )
    hits = list(qs[:2])  # fetch at most 2 to detect multiples cheaply
    if len(hits) == 1:
        return hits[0], f"phone variant match '{phone_value}' → '{hits[0].phone_number}'"
    if len(hits) > 1:
        return hits[0], f"phone variant match '{phone_value}' (first of {len(hits)} duplicates)"

    # ── Pass 2: last-9-digits suffix (format-agnostic fallback) ─────────
    suffix = _phone_last9(phone_value)
    if not suffix:
        return None, None

    # Django doesn't have a built-in "last N digits" filter, so we use
    # __endswith on the suffix.  This may return false positives for very
    # short suffixes, but 9 digits is specific enough for Kenyan numbers.
    qs2 = CustomUser.objects.filter(
        phone_number__endswith=suffix, role='borrower', is_active=True,
    )
    hits2 = list(qs2[:2])
    if len(hits2) == 1:
        return hits2[0], f"phone last-9 match '{suffix}' (stored: '{hits2[0].phone_number}')"
    if len(hits2) > 1:
        return hits2[0], f"phone last-9 match '{suffix}' (first of {len(hits2)} — ambiguous)"

    return None, None


def _save_sasapay_ipn_log(data, trans_id=''):
    """
    Persist the raw IPN payload for audit purposes.
    Returns the SasaPayIPNLog instance so the caller can update its status.
    On failure returns a stub object with a no-op mark() so callers don't crash.
    """
    try:
        log = SasaPayIPNLog.objects.create(
            raw_data=data,
            trans_id=(trans_id or '').strip(),
        )
        return log
    except Exception as exc:
        logger.warning(f"Could not save IPN log: {exc}")
        # Return a stub so callers can call .mark() without crashing
        class _Stub:
            pk = None
            def mark(self, *a, **kw): pass
        return _Stub()


def _save_unknown_sasapay_payment(amount, paid_by, msisdn, bill_ref, reference, notes=None):
    """
    Save an unrecognised SasaPay payment for admin review.
    Mirrors old PHP: INSERT INTO unknown_payments(paidamt, paidby, paidon, msisdn, reference, notes)
    """
    try:
        SasaPayUnknownPayment.objects.create(
            amount=amount,
            paid_by=paid_by,
            msisdn=msisdn,
            bill_ref=bill_ref,
            reference=reference,
            notes=notes or 'Unrecognised payment',
        )
    except Exception as exc:
        logger.warning(f"Could not save unknown payment: {exc}")


def _save_stk_result(checkout_id, result_code, result_desc, trans_amount,
                     merchant_loan_ref=''):
    """
    Persist STK push result.
    Mirrors old PHP: INSERT INTO stkpushresults
    """
    try:
        SasaPaySTKResult.objects.create(
            checkout_request_id=checkout_id,
            merchant_loan_ref=merchant_loan_ref,
            result_code=result_code,
            result_desc=result_desc,
            trans_amount=trans_amount,
        )
    except Exception as exc:
        logger.warning(f"Could not save STK result: {exc}")


def _save_disbursement_result(loan_ref, sasapay_tx_id, mpesa_ref,
                               result_code, result_desc, amount, balance):
    """
    Persist B2C disbursement result.
    Mirrors old PHP: INSERT INTO b2cpaymentsresults
    """
    try:
        SasaPayDisbursementResult.objects.create(
            loan_reference=loan_ref,
            sasapay_transaction_id=sasapay_tx_id,
            mpesa_reference=mpesa_ref,
            result_code=result_code,
            result_desc=result_desc,
            trans_amount=amount,
            merchant_balance=balance,
        )
    except Exception as exc:
        logger.warning(f"Could not save disbursement result: {exc}")


def _send_admin_alert(message):
    """
    Send an SMS alert to all configured admin numbers.
    Called whenever a payment is dropped for any reason, so nothing is silent.
    Admin numbers are read from settings.ADMIN_ALERT_PHONES (list of strings).
    Falls back to settings.BRANCH_SETTINGS['COMPANY_PHONE'] if not set.
    Silently swallowed on failure — never crashes IPN processing.
    """
    try:
        from .sms_service import send_sms
        admin_phones = getattr(settings, 'ADMIN_ALERT_PHONES', None)
        if not admin_phones:
            company_phone = (
                getattr(settings, 'BRANCH_SETTINGS', {}).get('COMPANY_PHONE') or ''
            )
            admin_phones = [company_phone] if company_phone else []
        if not admin_phones:
            logger.warning("_send_admin_alert: no ADMIN_ALERT_PHONES configured — alert not sent")
            return
        send_sms(admin_phones, message, sms_type='other')
        logger.info(f"Admin alert sent to {admin_phones}")
    except Exception as exc:
        logger.error(f"Admin alert SMS failed: {exc}")


def _save_sasapay_ipn_log_note(trans_id, note):
    """
    Legacy helper — kept for any callers outside this file.
    New code uses SasaPayIPNLog.mark() directly.
    """
    if not trans_id:
        return
    try:
        log = SasaPayIPNLog.objects.filter(
            trans_id=trans_id,
        ).order_by('-created_at').first()
        if log:
            log.mark(SasaPayIPNLog.STATUS_FAILED, note=note)
    except Exception as exc:
        logger.debug(f"Could not update IPN log note for {trans_id}: {exc}")


# Lazy imports to avoid circular dependency at module load time
from payments.sasapay_models import (  # noqa: E402
    SasaPayIPNLog,
    SasaPayUnknownPayment,
    SasaPaySTKResult,
    SasaPayDisbursementResult,
)
