
import logging
import requests

from django.db import transaction

from ..models import AppUser, KycVerificationAttempt
from ..payment import auth


logger = logging.getLogger(__name__)

MONNIFY_BVN_ENDPOINT = (
    "https://api.monnify.com/api/v1/vas/bvn-details-match"
)



def check_bvn_verification(response_data):
    """
    Accept only a successful Monnify response with a full match.
    Supports both current and legacy response formats.
    Rejects partial and unsuccessful matches.
    """

    if not isinstance(response_data, dict):
        return False, "Invalid verification response."

    if response_data.get("requestSuccessful") is not True:
        return False, "Verification could not be completed."

    response_body = response_data.get("responseBody")

    if not isinstance(response_body, dict):
        return False, "Invalid verification response."

    # Current Monnify response format.
    if "bvnInformationMatch" in response_body:
        if response_body.get("bvnInformationMatch") is True:
            return True, "BVN details matched successfully."

        return False, (
            "Your BVN details do not match the information provided."
        )

    # Legacy Monnify response format.
    name = response_body.get("name")
    dob = response_body.get("dateOfBirth")
    mobile = response_body.get("mobileNo")

    if not isinstance(name, dict):
        return False, "Invalid verification response."

    name_status = name.get("matchStatus")

    if (
        isinstance(name_status, str)
        and name_status.strip().upper() == "FULL_MATCH"
        and isinstance(dob, str)
        and dob.strip().upper() == "FULL_MATCH"
        and isinstance(mobile, str)
        and mobile.strip().upper() == "FULL_MATCH"
    ):
        return True, "BVN details matched successfully."

    return False, (
        "Your BVN details do not fully match the information provided."
    )



def reserve_kyc_attempt(user):
    """
    Enforce a five-minute cooldown and a maximum of five attempts
    within a rolling 24-hour period.
    """

    from django.utils import timezone
    from datetime import timedelta

    now = timezone.now()
    cooldown_start = now - timedelta(minutes=5)
    daily_start = now - timedelta(hours=24)

    try:
        with transaction.atomic():

            locked_user = (
                AppUser._default_manager
                .select_for_update()
                .get(pk=user.pk)
            )

            if locked_user.verify:
                return False, "Your account has already been verified."

            attempts = KycVerificationAttempt.objects.filter(
                user_id=locked_user.pk,
                created_at__gte=daily_start
            )

            if attempts.count() >= 5:
                return False, (
                    "You have reached the maximum number of verification "
                    "attempts. Please try again after 24 hours."
                )

            if attempts.filter(
                created_at__gte=cooldown_start
            ).exists():
                return False, (
                    "Please wait at least 5 minutes before trying again."
                )

            KycVerificationAttempt.objects.create(
                user_id=locked_user.pk
            )

        return True, None

    except Exception:
        logger.exception(
            "Failed to reserve KYC attempt for user ID %s.",
            user.pk
        )

        return False, (
            "Unable to process your verification request. "
            "Please try again later."
        )


def process_kyc_verification(user, cleaned_data):
    """
    Shared ExactSub KYC verification service.

    Used by the website and existing mobile application.

    Does not debit the user's wallet.
    Does not require a positive wallet balance.
    Does not perform BVN-to-bank-account matching.

    Returns:
        tuple: (status, message)
    """

    # 1. Check whether the user is already verified.
    try:
        user.refresh_from_db()

        if user.verify:
            return True, "Your account has already been verified."

    except Exception:
        logger.exception(
            "Could not refresh user record for KYC. User ID: %s",
            user.pk
        )

        return False, "Unable to process your request. Please try again."

    # 2. Obtain Monnify authentication token.
    try:
        token = auth()

    except Exception:
        logger.exception(
            "Monnify authentication failed for user ID %s.",
            user.pk
        )

        return False, (
            "Unable to connect to the verification service. "
            "Please try again later."
        )

    if not token:
        return False, (
            "The verification service is temporarily unavailable. "
            "Please try again later."
        )

    # 3. Prepare the customer's full name.
    full_name = " ".join(
        part.strip()
        for part in [
            cleaned_data["firstName"],
            cleaned_data.get("middleName", ""),
            cleaned_data["lastName"]
        ]
        if isinstance(part, str) and part.strip()
    )

    if not full_name:
        return False, "Please provide your full name."

    # 4. Prepare Monnify request.
    payload = {
        "bvn": cleaned_data["bvn"],
        "name": full_name,
        "dateOfBirth": cleaned_data["dob"].strftime("%d-%b-%Y"),
        "mobileNo": cleaned_data["phone"]
    }

    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(token)
    }

    # 5. Enforce per-user verification limits.
    allowed, throttle_message = reserve_kyc_attempt(user)

    if not allowed:
        return False, throttle_message

    # 6. Submit verification request.
    try:
        response = requests.post(
            MONNIFY_BVN_ENDPOINT,
            headers=headers,
            json=payload,
            timeout=(10, 45)
        )

        try:
            result = response.json()

            if not isinstance(result, dict):
                logger.error(
                    "Monnify returned unexpected BVN response format. "
                    "HTTP status: %s",
                    response.status_code
                )

                return False, (
                    "The verification service returned an unexpected "
                    "response. Please try again later."
                )

        except ValueError:
            logger.error(
                "Monnify returned a non-JSON BVN response. "
                "HTTP status: %s",
                response.status_code
            )

            return False, (
                "The verification service returned an invalid response. "
                "Please try again later."
            )

        if not response.ok:
            logger.warning(
                "Monnify BVN request failed for user ID %s. HTTP status: %s.",
                user.pk,
                response.status_code
            )

            return False, (
                "The verification service could not process your request. "
                "Please check your details or contact support."
            )

    except requests.Timeout:
        logger.warning(
            "Monnify BVN request timed out for user ID %s.",
            user.pk
        )

        return False, (
            "The verification request timed out. Please contact support "
            "to confirm its status before submitting another request."
        )

    except requests.RequestException:
        logger.exception(
            "Monnify BVN communication failed for user ID %s.",
            user.pk
        )

        return False, (
            "Unable to reach the verification service. "
            "Please try again later."
        )

    # 7. Validate Monnify response.
    verified, message = check_bvn_verification(result)

    if not verified:
        return False, message

    # 8. Save verified information.
    try:
        with transaction.atomic():

            locked_user = (
                AppUser._default_manager
                .select_for_update()
                .get(pk=user.pk)
            )

            if locked_user.verify:
                return True, "Your account has already been verified."

            locked_user.firstName = cleaned_data["firstName"]
            locked_user.lastName = cleaned_data["lastName"]
            locked_user.bvn = cleaned_data["bvn"]
            locked_user.dob = cleaned_data["dob"]
            locked_user.verify = True

            locked_user.save(
                update_fields=[
                    "firstName",
                    "lastName",
                    "bvn",
                    "dob",
                    "verify"
                ]
            )

    except Exception:
        logger.exception(
            "Failed to save KYC details for user ID %s.",
            user.pk
        )

        return False, (
            "Your details were verified, but we could not update "
            "your account. Please contact support."
        )

    return True, (
        "Your identity has been successfully verified. "
        "Your ExactSub account is now verified."
    )
