"""
Daraja Direct Developer Payment Service
Handles STK-push payments to the developer via Safaricom Daraja API directly.

API docs : https://developer.safaricom.co.ke
Base URL : https://api.safaricom.co.ke
Auth     : OAuth2 Bearer token obtained from Daraja token endpoint.

Credentials are read exclusively from Django settings (MPESA_DEV_* with
fallback to generic MPESA_* keys). They are NEVER logged or exposed in
responses.

© PhinTech Solutions Company Ltd — System v1.0
"""

import uuid
import logging
import base64
import requests
from datetime import datetime
from django.conf import settings
from django.utils import timezone

logger = logging.getLogger(__name__)

# ── Daraja production endpoints ───────────────────────────────────────────────
DARAJA_BASE_URL = 'https://api.safaricom.co.ke'
DARAJA_OAUTH_URL = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
DARAJA_STK_URL = 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest'

# ── Module-level token cache ──────────────────────────────────────────────────
_token_cache = {'token': None, 'expires_at': None}


# ─────────────────────────────────────────────────────────────────────────────
# Internal helpers
# ─────────────────────────────────────────────────────────────────────────────

def get_daraja_token() -> str:
    """
    Return a valid Daraja Bearer token, using the module-level cache.
    If the cached token is still valid (expires_at > now + 30s), it is
    returned directly.  Otherwise a fresh token is obtained from the Daraja
    OAuth endpoint and the cache is updated.

    Raises ValueError if authentication fails.
    Never logs the token value.
    """
    import time
    now = time.time()
    # Return cached token if still valid (with 30-second buffer)
    if (
        _token_cache['token']
        and _token_cache['expires_at']
        and _token_cache['expires_at'] > now + 30
    ):
        return _token_cache['token']

    consumer_key = getattr(settings, 'MPESA_DEV_CONSUMER_KEY',
                           getattr(settings, 'MPESA_CONSUMER_KEY', '')).strip()
    consumer_secret = getattr(settings, 'MPESA_DEV_CONSUMER_SECRET',
                              getattr(settings, 'MPESA_CONSUMER_SECRET', '')).strip()

    if not consumer_key or not consumer_secret:
        raise ValueError(
            "Daraja credentials not configured. "
            "Set MPESA_DEV_CONSUMER_KEY and MPESA_DEV_CONSUMER_SECRET in settings."
        )

    credentials = base64.b64encode(
        f"{consumer_key}:{consumer_secret}".encode()
    ).decode()

    try:
        resp = requests.get(
            DARAJA_OAUTH_URL,
            headers={'Authorization': f'Basic {credentials}'},
            timeout=30,
        )
        resp.raise_for_status()
        data = resp.json()
    except requests.exceptions.RequestException as exc:
        raise ValueError(
            f"Failed to authenticate with M-Pesa Daraja API: {exc}\n"
            "Check that the production server can reach api.safaricom.co.ke "
            "(run: python check_daraja_connection.py)"
        ) from exc

    token = data.get('access_token')
    if not token:
        raise ValueError(
            "No access_token in Daraja OAuth response. "
            "Check MPESA_DEV_CONSUMER_KEY / MPESA_DEV_CONSUMER_SECRET."
        )

    expires_in = int(data.get('expires_in', 3599))
    _token_cache['token'] = token
    _token_cache['expires_at'] = now + expires_in

    return token


def generate_password(shortcode: str, passkey: str, timestamp: str) -> str:
    """Generate the Daraja STK Push password (base64 of shortcode+passkey+timestamp)."""
    return base64.b64encode(
        (shortcode + passkey + timestamp).encode()
    ).decode()


def generate_reference() -> str:
    """Generate a unique payment reference for this system."""
    ts = timezone.now().strftime('%Y%m%d%H%M%S')
    short_uuid = str(uuid.uuid4()).replace('-', '')[:8].upper()
    return f"PHINT-{ts}-{short_uuid}"


def _normalize_phone(phone_number: str) -> str:
    """
    Normalise a phone number to the 254XXXXXXXXX format required by Daraja.
    Strips whitespace and a leading '+', then converts common Kenyan formats.
    """
    phone = str(phone_number).strip().lstrip('+')
    if phone.startswith('07'):
        phone = '2547' + phone[2:]
    elif phone.startswith('01'):
        phone = '2541' + phone[2:]
    elif phone.startswith('254'):
        pass  # already correct
    else:
        phone = '254' + phone
    return phone


def _get_callback_url() -> str:
    """Return the Daraja callback URL for developer payments."""
    url = getattr(settings, 'MPESA_DEV_CALLBACK_URL', None)
    if url:
        return url
    site_url = getattr(settings, 'SITE_URL', 'https://grazuri.uzuriapps.xyz').rstrip('/')
    return f"{site_url}/payments/developer/callback/daraja/"


# ─────────────────────────────────────────────────────────────────────────────
# Public API
# ─────────────────────────────────────────────────────────────────────────────

def initiate_developer_payment(phone_number: str, amount: float,
                                reference: str,
                                description: str = 'Developer Service Fee') -> dict:
    """
    Initiate a Daraja STK Push to pay the developer (PhinTech Solutions Company Ltd).

    Returns a dict with keys:
        success (bool), message (str), checkout_id (str|None),
        transaction_reference (str|None), raw_response (dict)
    """
    shortcode = getattr(settings, 'MPESA_DEV_SHORTCODE',
                        getattr(settings, 'MPESA_SHORTCODE', '4501895')).strip()
    passkey = getattr(settings, 'MPESA_DEV_PASSKEY',
                      getattr(settings, 'MPESA_PASSKEY', '')).strip()

    phone = _normalize_phone(phone_number)

    logger.info(
        "[DevPayment] Initiating Daraja STK | ref=%s | phone=%s*** | amount=KES %s",
        reference, phone[:6], amount,
    )

    # ── Obtain OAuth token ────────────────────────────────────────────────────
    try:
        token = get_daraja_token()
    except ValueError as exc:
        logger.error("[DevPayment] Daraja auth failed | ref=%s: %s", reference, exc)
        return {
            'success': False,
            'message': str(exc),
            'checkout_id': None,
            'transaction_reference': None,
            'raw_response': {},
        }

    # ── Build STK Push payload ────────────────────────────────────────────────
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    password = generate_password(shortcode, passkey, timestamp)
    callback_url = _get_callback_url()

    payload = {
        'BusinessShortCode': shortcode,
        'Password': password,
        'Timestamp': timestamp,
        'TransactionType': 'CustomerPayBillOnline',
        'Amount': int(float(amount)),
        'PartyA': phone,
        'PartyB': shortcode,
        'PhoneNumber': phone,
        'CallBackURL': callback_url,
        'AccountReference': reference[:12],
        'TransactionDesc': description[:13],
    }

    try:
        resp = requests.post(
            DARAJA_STK_URL,
            json=payload,
            headers={
                'Authorization': f'Bearer {token}',
                'Content-Type': 'application/json',
            },
            timeout=30,
        )
        resp.raise_for_status()
        data = resp.json()

        success = data.get('ResponseCode') == '0'
        checkout_id = data.get('CheckoutRequestID')
        message = (
            data.get('CustomerMessage')
            or data.get('ResponseDescription')
            or ('STK push sent — check your phone' if success else 'STK push failed')
        )

        logger.info(
            "[DevPayment] Daraja STK response | ref=%s | success=%s | checkout=%s",
            reference, success, checkout_id,
        )

        return {
            'success': success,
            'message': message,
            'checkout_id': checkout_id,
            'transaction_reference': checkout_id,
            'raw_response': data,
        }

    except requests.exceptions.Timeout:
        logger.error("[DevPayment] Daraja timeout | ref=%s", reference)
        return {
            'success': False,
            'message': 'Request timed out. Please retry.',
            'checkout_id': None,
            'transaction_reference': None,
            'raw_response': {},
        }

    except requests.exceptions.HTTPError as exc:
        status_code = exc.response.status_code if exc.response is not None else '?'
        body = ''
        try:
            body = exc.response.text[:300]
        except Exception:
            pass
        logger.error(
            "[DevPayment] Daraja HTTP %s | ref=%s: %s", status_code, reference, body
        )
        return {
            'success': False,
            'message': f'HTTP {status_code} error from Daraja: {body}',
            'checkout_id': None,
            'transaction_reference': None,
            'raw_response': {'error': body, 'status_code': status_code},
        }

    except requests.exceptions.RequestException as exc:
        logger.error("[DevPayment] Daraja network error | ref=%s: %s", reference, exc)
        return {
            'success': False,
            'message': f'Network error: {exc}',
            'checkout_id': None,
            'transaction_reference': None,
            'raw_response': {},
        }

    except Exception as exc:
        logger.error(
            "[DevPayment] Unexpected error | ref=%s: %s", reference, exc, exc_info=True
        )
        return {
            'success': False,
            'message': f'Unexpected error: {exc}',
            'checkout_id': None,
            'transaction_reference': None,
            'raw_response': {},
        }


def process_daraja_callback(callback_data: dict) -> dict:
    """
    Process an incoming Daraja STK Push callback.

    Daraja STK callback shape:
    {
        "Body": {
            "stkCallback": {
                "MerchantRequestID": "...",
                "CheckoutRequestID": "ws_CO_...",
                "ResultCode": 0,
                "ResultDesc": "The service request is processed successfully.",
                "CallbackMetadata": {
                    "Item": [
                        {"Name": "Amount",             "Value": 500},
                        {"Name": "MpesaReceiptNumber", "Value": "NEF61H8J60"},
                        {"Name": "TransactionDate",    "Value": 20241209143022},
                        {"Name": "PhoneNumber",        "Value": 254712345678}
                    ]
                }
            }
        }
    }

    Only processes callbacks whose CheckoutRequestID matches a DeveloperPayment
    we initiated from this system.
    """
    from .developer_payment_models import DeveloperPayment

    stk = callback_data.get('Body', {}).get('stkCallback', {})

    checkout_id = stk.get('CheckoutRequestID', '').strip()
    result_code = stk.get('ResultCode')
    result_desc = stk.get('ResultDesc', '')

    # Extract metadata items
    items = stk.get('CallbackMetadata', {}).get('Item', [])
    meta = {item['Name']: item.get('Value') for item in items if 'Name' in item}
    receipt = str(meta.get('MpesaReceiptNumber', '')).strip()

    if not checkout_id:
        logger.warning("[DevPayment] Daraja callback missing CheckoutRequestID — ignoring")
        return {'processed': False, 'message': 'No CheckoutRequestID in callback'}

    try:
        payment = DeveloperPayment.objects.get(mpesa_checkout_id=checkout_id)
    except DeveloperPayment.DoesNotExist:
        logger.warning(
            "[DevPayment] No DeveloperPayment found for CheckoutRequestID=%s", checkout_id
        )
        return {'processed': False, 'message': 'Payment record not found'}

    if result_code == 0:
        payment.mark_completed(
            mpesa_receipt=receipt or None,
            transaction_id=receipt or checkout_id,
            callback_data=callback_data,
        )
        logger.info(
            "[DevPayment] COMPLETED | ref=%s | receipt=%s", payment.reference, receipt
        )
        return {'processed': True, 'message': 'Payment completed successfully'}
    else:
        payment.mark_failed(reason=result_desc or 'STK push not completed',
                            callback_data=callback_data)
        logger.warning(
            "[DevPayment] FAILED | ref=%s | reason=%s", payment.reference, result_desc
        )
        return {'processed': True, 'message': f'Payment failed: {result_desc}'}


def verify_callback_is_from_this_system(checkout_id: str) -> bool:
    """
    Verify that a Daraja callback belongs to a payment WE initiated.
    Checks that the CheckoutRequestID exists in our DeveloperPayment table.
    """
    from .developer_payment_models import DeveloperPayment
    return DeveloperPayment.objects.filter(mpesa_checkout_id=checkout_id).exists()


# ─────────────────────────────────────────────────────────────────────────────
# STK Push Status Query
# ─────────────────────────────────────────────────────────────────────────────

def query_stk_status(checkout_request_id: str) -> dict:
    """
    Query the status of an STK Push transaction from Daraja.

    If the query returns a definitive result (ResultCode present), the
    matching DeveloperPayment is automatically updated:
      - ResultCode 0    → mark_completed
      - non-zero ResultCode → mark_failed

    Returns a dict with keys:
        success (bool), result_code (str|None), result_desc (str),
        updated (bool), payment_status (str|None), message (str)
    """
    from .developer_payment_models import DeveloperPayment

    shortcode = getattr(settings, 'MPESA_DEV_SHORTCODE',
                        getattr(settings, 'MPESA_SHORTCODE', '4501895')).strip()
    passkey = getattr(settings, 'MPESA_DEV_PASSKEY',
                      getattr(settings, 'MPESA_PASSKEY', '')).strip()

    if not passkey:
        return {
            'success': False,
            'result_code': None,
            'result_desc': 'Passkey not configured',
            'updated': False,
            'payment_status': None,
            'message': 'MPESA_DEV_PASSKEY not configured',
        }

    # Get OAuth token
    try:
        token = get_daraja_token()
    except ValueError as exc:
        return {
            'success': False,
            'result_code': None,
            'result_desc': str(exc),
            'updated': False,
            'payment_status': None,
            'message': str(exc),
        }

    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    password = generate_password(shortcode, passkey, timestamp)

    try:
        resp = requests.post(
            'https://api.safaricom.co.ke/mpesa/stkpushquery/v1/query',
            headers={
                'Authorization': f'Bearer {token}',
                'Content-Type': 'application/json',
            },
            json={
                'BusinessShortCode': shortcode,
                'Password': password,
                'Timestamp': timestamp,
                'CheckoutRequestID': checkout_request_id,
            },
            timeout=30,
        )
        resp.raise_for_status()
        data = resp.json()

        result_code = str(data.get('ResultCode', ''))
        result_desc = data.get('ResultDesc', '')

        # Try to find the matching payment
        try:
            payment = DeveloperPayment.objects.get(mpesa_checkout_id=checkout_request_id)
        except DeveloperPayment.DoesNotExist:
            payment = None

        # Auto-update the payment if we have a definitive result
        updated = False
        if payment and result_code != '':
            if result_code == '0':
                # Success — but we don't have the receipt number from a query
                # (only callbacks carry CallbackMetadata). Mark as completed
                # with the checkout_id as the transaction ID.
                if payment.status != 'completed':
                    payment.mark_completed(
                        mpesa_receipt=None,
                        transaction_id=checkout_request_id,
                        callback_data=data,
                    )
                    updated = True
                    logger.info(
                        '[DevPayment] STK query auto-completed | ref=%s | checkout=%s',
                        payment.reference, checkout_request_id,
                    )
            else:
                # Failed
                if payment.status not in ('failed', 'cancelled'):
                    payment.mark_failed(reason=result_desc, callback_data=data)
                    updated = True
                    logger.info(
                        '[DevPayment] STK query auto-failed | ref=%s | reason=%s',
                        payment.reference, result_desc,
                    )

        return {
            'success': True,
            'result_code': result_code or None,
            'result_desc': result_desc,
            'updated': updated,
            'payment_status': payment.status if payment else None,
            'message': result_desc or 'Query completed',
            'raw_response': data,
        }

    except requests.exceptions.Timeout:
        return {
            'success': False,
            'result_code': None,
            'result_desc': 'Request timed out',
            'updated': False,
            'payment_status': None,
            'message': 'Daraja STK query timed out',
        }
    except Exception as exc:
        logger.error('[DevPayment] STK query error | checkout=%s: %s', checkout_request_id, exc)
        return {
            'success': False,
            'result_code': None,
            'result_desc': str(exc),
            'updated': False,
            'payment_status': None,
            'message': f'Error querying STK status: {exc}',
        }
