"""
inventory/services/pos_mpesa_service.py
────────────────────────────────────────
M-Pesa STK Push for the admin POS. Same Daraja integration and callback URL
as store orders (store/services/mpesa_service.py); results land on
PosMpesaPayment instead of an Order.

Rules match store/services/payment_service.py:
• Duplicate callbacks are harmless.
• A success always counts (money has moved), even after a failure.
• The paid amount is checked against what M-Pesa was asked to charge
  (KES 1 in sandbox, the full amount live).
"""

import logging
from decimal import Decimal
from typing import Any

from django.db import transaction
from django.utils import timezone

from inventory.models import PosMpesaPayment, Sale
from system_logs.models import SystemLog
from system_logs.services import log_event
from store.services.mpesa_service import (
    QUERY_FAILED,
    QUERY_PROCESSING,
    QUERY_SUCCESS,
    MpesaError,
    MpesaService,
)

logger = logging.getLogger(__name__)

# Give the customer time to act before asking Daraja (and stay inside its
# rate limits — bursts get blocked by Safaricom's firewall).
MIN_PROMPT_AGE_SECONDS = 20

# Account name shown on the customer's prompt/SMS. Daraja caps it at 12
# characters, so "TAI BOOKSTORE" (13) would be cut to "TAI BOOKSTOR".
POS_ACCOUNT_REFERENCE = "TAIBOOKSTORE"

# Prompts expire on the phone after about a minute. Past this age, a prompt
# whose status M-Pesa won't confirm (rate limiting) may be replaced.
UNCONFIRMED_RESEND_AFTER_SECONDS = 180


class PromptStillOpen(Exception):
    """The previous prompt hasn't been answered yet — don't send another."""


def send_prompt(phone: str, amount: Decimal, *, user=None, previous: PosMpesaPayment | None = None) -> PosMpesaPayment:
    """
    Send an STK prompt for `amount` to `phone`.

    If `previous` (an earlier prompt from the same POS screen) is still
    pending, Daraja is asked about it first: if it was paid, that payment is
    returned instead of sending a new prompt; if it's still open,
    PromptStillOpen is raised so the customer isn't asked to pay twice.

    Raises:
        MpesaError: invalid phone or Daraja failure.
        PromptStillOpen
    """
    if previous is not None and previous.status == PosMpesaPayment.STATUS_PENDING:
        state = refresh_status(previous, force=True)
        previous.refresh_from_db()
        if previous.status == PosMpesaPayment.STATUS_PAID:
            return previous
        if state == QUERY_PROCESSING:
            raise PromptStillOpen(
                "The previous M-Pesa prompt is still open on the customer's phone. "
                "Ask them to enter their PIN or cancel it, then try again."
            )
        if state == "unknown":
            age = (timezone.now() - previous.created_at).total_seconds()
            if age < UNCONFIRMED_RESEND_AFTER_SECONDS:
                # Can't tell if the customer paid — a new prompt could charge twice.
                raise PromptStillOpen(
                    "Couldn't confirm the previous prompt with M-Pesa right now (it limits how often we "
                    "can check). Wait about a minute and try again."
                )
            # Long expired on the phone; a late success still lands on it and
            # shows as "paid, not used" in POS M-Pesa Payments for refund.
            previous.result_desc = "Status unconfirmed (M-Pesa unreachable); superseded by a new prompt."
            previous.save(update_fields=["result_desc", "updated_at"])
            log_event(
                SystemLog.MODULE_PAYMENTS, "mpesa.pos.superseded_unconfirmed",
                f"POS prompt {previous.pk} replaced by a new prompt without M-Pesa confirming its outcome.",
                level=SystemLog.LEVEL_WARNING, user=user, **_refs(previous),
            )
    if previous is not None and previous.status == PosMpesaPayment.STATUS_PAID and previous.sale_id is None:
        return previous

    mpesa = MpesaService()
    normalized = mpesa.normalize_phone(phone)
    payment = PosMpesaPayment.objects.create(
        phone_number=normalized, amount=amount, created_by=user,
    )
    try:
        result = mpesa.stk_push(
            phone_number=normalized,
            amount=int(amount),
            order_reference=f"POS{payment.pk}",
            account_reference=POS_ACCOUNT_REFERENCE,
        )
    except MpesaError as exc:
        payment.status = PosMpesaPayment.STATUS_FAILED
        payment.result_desc = f"Prompt not sent: {exc}"
        payment.save(update_fields=["status", "result_desc", "updated_at"])
        raise

    payment.checkout_request_id = result.get("CheckoutRequestID", "")
    payment.merchant_request_id = result.get("MerchantRequestID", "")
    payment.save(update_fields=["checkout_request_id", "merchant_request_id", "updated_at"])
    logger.info("POS STK sent | payment=%s | amount=%s | checkout=%s", payment.pk, amount, payment.checkout_request_id)
    return payment


def apply_result(
    checkout_request_id: str,
    *,
    success: bool,
    result_code: int | None = None,
    result_desc: str = "",
    receipt: str = "",
    amount: Any = None,
    raw: dict | None = None,
) -> PosMpesaPayment | None:
    """Apply a callback/query outcome. Returns None if no POS payment matches."""
    with transaction.atomic():
        payment = (
            PosMpesaPayment.objects.select_for_update()
            .filter(checkout_request_id=checkout_request_id)
            .first()
        )
        if payment is None:
            return None

        if raw is not None:
            payment.raw_callback = raw

        if payment.status == PosMpesaPayment.STATUS_PAID:
            # Duplicate, or the callback arriving after a status query
            # confirmed it — only the receipt can be new.
            if receipt and not payment.mpesa_receipt_number:
                payment.mpesa_receipt_number = receipt
                payment.save(update_fields=["mpesa_receipt_number", "raw_callback", "updated_at"])
                if payment.sale_id:
                    Sale.objects.filter(pk=payment.sale_id, mpesa_code="").update(mpesa_code=receipt[:20])
            return payment

        previous_status = payment.status
        was_superseded = "superseded" in (payment.result_desc or "")
        payment.result_code = result_code
        payment.result_desc = result_desc

        if success:
            expected = MpesaService().charge_amount(payment.amount)
            if amount is not None and Decimal(str(amount)) < expected:
                payment.result_desc = f"Amount mismatch: paid {amount}, expected {expected}"
                payment.save(update_fields=["result_code", "result_desc", "raw_callback", "updated_at"])
                log_event(
                    SystemLog.MODULE_PAYMENTS, "mpesa.pos.amount_mismatch",
                    f"POS prompt {payment.pk}: customer paid KES {amount} but KES {expected} was due — "
                    "NOT marked paid.",
                    level=SystemLog.LEVEL_ERROR, alert=True, **_refs(payment, receipt),
                )
                return payment
            payment.status = PosMpesaPayment.STATUS_PAID
            payment.mpesa_receipt_number = receipt or ""
        elif payment.status == PosMpesaPayment.STATUS_PENDING:
            payment.status = PosMpesaPayment.STATUS_FAILED

        payment.save(update_fields=[
            "status", "mpesa_receipt_number", "result_code", "result_desc", "raw_callback", "updated_at",
        ])

    if success and (previous_status == PosMpesaPayment.STATUS_FAILED or was_superseded):
        log_event(
            SystemLog.MODULE_PAYMENTS, "mpesa.pos.late_success",
            f"POS prompt {payment.pk} was PAID after being marked failed or replaced — the customer may "
            "have paid twice. Check POS M-Pesa Payments for an unused paid prompt and refund if so.",
            level=SystemLog.LEVEL_ERROR, alert=True, **_refs(payment, receipt),
        )
    else:
        log_event(
            SystemLog.MODULE_PAYMENTS, f"mpesa.pos.{payment.status}",
            f"POS prompt {payment.pk}: {payment.get_status_display()} ({result_code} {result_desc})",
            **_refs(payment, receipt),
        )
    return payment


def _refs(payment: PosMpesaPayment, receipt: str = "") -> dict:
    return {
        "reference": f"POS-{payment.pk}",
        "checkout_request_id": payment.checkout_request_id,
        "phone_number": payment.phone_number,
        "mpesa_receipt": receipt or payment.mpesa_receipt_number,
        "related": payment,
    }


def refresh_status(payment: PosMpesaPayment, *, force: bool = False, timeout_as_failed: bool = False) -> str | None:
    """
    Ask Daraja about a pending prompt and apply the outcome. Skipped (returns
    None) for non-pending payments, or prompts younger than
    MIN_PROMPT_AGE_SECONDS unless `force`.

    Returns the query state, or "unknown" if Daraja couldn't be reached.
    """
    if payment.status != PosMpesaPayment.STATUS_PENDING or not payment.checkout_request_id:
        return None
    age = (timezone.now() - payment.created_at).total_seconds()
    if not force and age < MIN_PROMPT_AGE_SECONDS:
        return QUERY_PROCESSING

    try:
        result = MpesaService().stk_query(payment.checkout_request_id)
    except MpesaError as exc:
        logger.warning("POS STK query failed for payment %s: %s", payment.pk, exc)
        return "unknown"

    state = result["state"]
    if state in (QUERY_SUCCESS, QUERY_FAILED):
        apply_result(
            payment.checkout_request_id,
            success=state == QUERY_SUCCESS,
            result_code=result["result_code"],
            result_desc=result["result_desc"],
            raw=result["raw"],
        )
    elif timeout_as_failed:
        apply_result(
            payment.checkout_request_id,
            success=False,
            result_desc="No response from M-Pesa before the payment window expired.",
            raw=result["raw"],
        )
        state = QUERY_FAILED
    return state


def claim_for_sale(payment_id: int, sale: Sale) -> PosMpesaPayment:
    """
    Attach a paid prompt to a sale being recorded (call inside the sale's
    transaction). Raises ValueError with a cashier-facing message if the
    payment can't back this sale.
    """
    try:
        payment = PosMpesaPayment.objects.select_for_update().get(pk=payment_id)
    except PosMpesaPayment.DoesNotExist:
        raise ValueError("M-Pesa payment not found — send a new prompt.")

    if payment.status != PosMpesaPayment.STATUS_PAID:
        raise ValueError("The M-Pesa payment hasn't been confirmed yet. Wait for the customer to pay.")
    if payment.sale_id and payment.sale_id != sale.pk:
        raise ValueError("This M-Pesa payment is already attached to another sale.")
    if payment.amount < sale.total_net:
        raise ValueError(
            f"The customer paid KES {payment.amount:,.2f} but the sale total is KES {sale.total_net:,.2f}. "
            "The cart changed after payment — send a new prompt for the difference or adjust the cart."
        )

    payment.sale = sale
    payment.save(update_fields=["sale", "updated_at"])
    return payment
