import requests
from .models import ResultPin, Config, exam_pin
from base64 import b64encode
import random
from datetime import datetime
import json
from django.db import transaction
import uuid
import logging

logger = logging.getLogger(__name__)


# RESULT CHECKER PIN

def result_vtpass(exam_type, quantity, phone):

    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        return the_date + random_num

    request_id = request_id()

    try:
        quantity = int(quantity)
    except (TypeError, ValueError):
        return [
            "Invalid quantity.",
            "Unsuccessful",
            request_id
        ]

    if quantity < 1:
        return [
            "Quantity must be at least 1.",
            "Unsuccessful",
            request_id
        ]

    try:

        # -----------------------------------------------------
        # GET VTPASS SERVICE VARIATION
        # -----------------------------------------------------

        get_var = requests.get(
            f"https://api-service.vtpass.com/api/service-variations"
            f"?serviceID={exam_type}",
            timeout=30
        )

        var = get_var.json()

        variations = (
            var.get("content", {})
               .get("variations", [])
        )

        if not variations:

            return [
                (
                    "Your transaction is currently pending. "
                    "The provider did not return a valid service "
                    "variation. Please confirm the transaction "
                    "status later or contact support."
                ),
                "Pending",
                request_id
            ]

        d_var = variations[0].get("variation_code")

        if not d_var:

            return [
                (
                    "Your transaction is currently pending. "
                    "The provider returned an incomplete response."
                ),
                "Pending",
                request_id
            ]

        # -----------------------------------------------------
        # VTPASS PAYMENT
        # -----------------------------------------------------

        url = "https://api-service.vtpass.com/api/pay"

        parameters = {
            "request_id": request_id,
            "serviceID": exam_type,
            "variation_code": d_var,
            "quantity": quantity,
            "phone": phone,
        }

        headers = {
            "Content-Type": "application/json",
            "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
            "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
        }

        responses = requests.post(
            url,
            headers=headers,
            json=parameters,
            timeout=30
        )

        response = responses.json()

        

        if not isinstance(response, dict):

            return [
                (
                    "Your transaction is currently pending. "
                    "Please confirm the transaction status later "
                    "or contact support."
                ),
                "Pending",
                request_id
            ]

        description = str(
            response.get(
                "response_description",
                ""
            )
        ).strip()

        # -----------------------------------------------------
        # SUCCESSFUL
        # -----------------------------------------------------

        if description == "TRANSACTION SUCCESSFUL":

            pin = response.get(
                "purchased_code",
                ""
            )

            if not pin:

                return [
                    (
                        "Your transaction is currently pending. "
                        "The provider confirmed the transaction "
                        "but did not return the PIN. Please contact "
                        "support."
                    ),
                    "Pending",
                    request_id
                ]

            return [
                f"Successful {description}: {pin}",
                "Successful",
                request_id,
                pin
            ]

        # -----------------------------------------------------
        # DEFINITIVE FAILURE
        # -----------------------------------------------------

        elif description in [
            "TRANSACTION FAILED",
            "LOW WALLET BALANCE"
        ]:

            return [
                f"Oops {description}",
                "Unsuccessful",
                request_id
            ]

        # -----------------------------------------------------
        # ANY OTHER PROVIDER RESPONSE
        # -----------------------------------------------------

        elif description:

            return [
                (
                    f"Pending ({description}), dear customer, "
                    "your transaction is pending. Please confirm "
                    "the transaction status later or contact support."
                ),
                "Pending",
                request_id
            ]

        # -----------------------------------------------------
        # EMPTY/UNKNOWN RESPONSE
        # -----------------------------------------------------

        else:

            return [
                (
                    "Your transaction is currently pending. "
                    "The provider returned an incomplete response. "
                    "Please confirm the transaction status later "
                    "or contact support."
                ),
                "Pending",
                request_id
            ]

    except Exception:

        # IMPORTANT:
        # We cannot know whether VTPASS received or processed
        # the request when the network/API interaction fails.
        # Therefore do NOT mark it Unsuccessful.
        return [
            (
                "Your transaction is currently pending. "
                "Please confirm the transaction status later "
                "or contact support."
            ),
            "Pending",
            request_id
        ]



def result_apisub(exam_type, quantity, phone):

    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        request_idd = the_date + random_num
        return request_idd

    # ---------------------------------------------------------
    # Convert frontend exam name to provider exam name
    # ---------------------------------------------------------

    if exam_type == 'waec':
        exam = 'WAEC'

    elif exam_type == 'neco':
        exam = 'NECO'

    else:
        return [
            "Oops unsuccessful, invalid examination type",
            "Unsuccessful",
            request_id()
        ]

    # ---------------------------------------------------------
    # Validate quantity
    # ---------------------------------------------------------

    try:
        quantity = int(quantity)

    except (TypeError, ValueError):
        return [
            "Oops unsuccessful, invalid quantity",
            "Unsuccessful",
            request_id()
        ]

    if quantity < 1:
        return [
            "Oops unsuccessful, quantity must be at least 1",
            "Unsuccessful",
            request_id()
        ]

    request_idd = request_id()

    table = Config.objects.get(pk=1)
    apisubportal_key = table.apisubportal_key

    url = "https://apisubportal.com/api/buyepin.php"

    parameters = {
        "api_key": apisubportal_key,
        "examtype": exam,
    }
    # ---------------------------------------------------------
    # Provider request
    # ---------------------------------------------------------

    try:

        responses = requests.get(
            url,
            params=parameters,
            timeout=30
        )

        response = json.loads(responses.text)

    except Exception:

        # We cannot know whether the provider received or
        # processed the request.
        #
        # Therefore DO NOT return Unsuccessful here.
        # The outer transaction process will keep the
        # transaction pending and will NOT refund automatically.

        return [
            (
                "Pending, dear customer, your transaction is "
                "pending. Please confirm the transaction status "
                "later or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Validate provider response
    # ---------------------------------------------------------

    if not isinstance(response, dict):

        return [
            (
                "Your transaction is currently pending. "
                "The provider returned an invalid response. "
                "Please confirm the transaction status later "
                "or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Safely obtain provider status
    # ---------------------------------------------------------

    res = str(
        response.get("status", "")
    ).strip().lower()

    message = str(
        response.get(
            "msg",
            response.get(
                "message",
                "No response message was provided."
            )
        )
    ).strip()

    # ---------------------------------------------------------
    # SUCCESSFUL
    # ---------------------------------------------------------

    if res == "success":

        return [
            f"Successful {exam_type} {message}",
            "Successful",
            request_idd
        ]

    # ---------------------------------------------------------
    # DEFINITIVE FAILURE
    # ---------------------------------------------------------

    elif res == "unsuccessful":

        return [
            f"Oops unsuccessful {exam_type} Subscription",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # EXPLICIT PENDING / PROCESSING
    # ---------------------------------------------------------

    elif res in [
        "pending",
        "processing",
        "process",
        "in progress"
    ]:

        return [
            (
                f"Pending, {exam_type}. "
                f"{message}"
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # EMPTY / UNKNOWN STATUS
    # ---------------------------------------------------------

    else:

        return [
            (
                f"Pending, {exam_type}. "
                "The provider returned an incomplete or "
                "unrecognized response. Please confirm the "
                "transaction status later or contact support."
            ),
            "Pending",
            request_idd
        ]

def result_manual(exam_type, quantity, phone):

    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        return the_date + str(num)

    request_idd = request_id()

    # ---------------------------------------------------------
    # VALIDATE EXAMINATION TYPE
    # ---------------------------------------------------------

    exam_type = str(exam_type or "").strip().lower()

    if exam_type == "waec":
        exam = "WAEC"

    elif exam_type == "neco":
        exam = "NECO"

    else:
        return [
            "Unable to process your request because the selected "
            "examination type is invalid.",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # VALIDATE QUANTITY
    # ---------------------------------------------------------

    try:
        num = int(quantity)

    except (TypeError, ValueError):

        return [
            "The quantity entered is invalid. Please enter a valid "
            "quantity and try again.",
            "Unsuccessful",
            request_idd
        ]

    if num < 1:

        return [
            "The quantity must be at least 1.",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # RESERVE PIN INVENTORY ATOMICALLY
    # ---------------------------------------------------------

    try:

        with transaction.atomic():

            available_pins = list(
                exam_pin.objects
                .select_for_update()
                .filter(
                    exam=exam,
                    available=True
                )
                .order_by("id")[:num]
            )

            # -------------------------------------------------
            # INSUFFICIENT INVENTORY
            # -------------------------------------------------

            available_count = len(available_pins)

            if available_count < num:

                return [
                    (
                        f"Sorry, the requested number of {exam} "
                        f"result PINs is currently unavailable. "
                        f"Requested: {num}. "
                        f"Available: {available_count}."
                    ),
                    "Unsuccessful",
                    request_idd
                ]

            # -------------------------------------------------
            # PREPARE STRUCTURED DELIVERY DATA
            # -------------------------------------------------

            pins_data = []

            message_parts = []

            for item in available_pins:

                pin_value = str(
                    item.pin or ""
                ).strip()

                serial_value = str(
                    item.serial or ""
                ).strip()

                pins_data.append({
                    "exam": str(item.exam),
                    "pin": pin_value,
                    "serial": serial_value
                })

                message_parts.append(
                    f"{item.exam} PIN: {pin_value} "
                    f"SERIAL: {serial_value}"
                )

            # -------------------------------------------------
            # CUSTOMER-FACING SUCCESS MESSAGE
            # -------------------------------------------------

            message = (
                "Successful, " +
                " ".join(message_parts)
            )

            # -------------------------------------------------
            # MARK PIN INVENTORY AS USED
            # -------------------------------------------------

            exam_pin.objects.filter(
                id__in=[
                    item.id
                    for item in available_pins
                ]
            ).update(
                available=False
            )

            # -------------------------------------------------
            # RETURN EXISTING PROVIDER CONTRACT
            #
            # [0] = message
            # [1] = status
            # [2] = request ID
            # [3] = structured PIN data
            # -------------------------------------------------

            return [
                message,
                "Successful",
                request_idd,
                pins_data
            ]

    except Exception as exc:

        # -----------------------------------------------------
        # LOG TECHNICAL ERROR
        #
        # Never expose the actual exception to the customer.
        # -----------------------------------------------------

        logger.exception(
            "Manual Exam PIN transaction failed. "
            "Exam: %s | Quantity: %s | Request ID: %s | Error: %s",
            exam,
            num,
            request_idd,
            exc
        )

        # -----------------------------------------------------
        # CUSTOMER-FACING PENDING RESPONSE
        # -----------------------------------------------------

        return [
            (
                "We couldn't complete your request at this time. "
                "Your transaction is currently pending. Please "
                "check your transaction history shortly or contact "
                "support if the status does not update."
            ),
            "Pending",
            request_idd
        ]

def result_ringo(exam_type, quantity, phone):

    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        return the_date + random_num

    request_id = request_id()

    # Ringo currently supports WAEC in this implementation.
    if exam_type != 'waec':
        return [
            "Transaction unsuccessful",
            "Unsuccessful",
            request_id
        ]

    try:
        quantity = int(quantity)
    except (TypeError, ValueError):
        return [
            "Invalid quantity.",
            "Unsuccessful",
            request_id
        ]

    if quantity < 1:
        return [
            "Quantity must be at least 1.",
            "Unsuccessful",
            request_id
        ]

    try:

        table = Config.objects.get(pk=1)

        email = table.ringo_email
        password = table.ringo_password

        url = "https://www.api.ringo.ng/api/agent/p2"

        payload = {
            "serviceCode": "WAB",
            "type": "WAEC",
            "amount": "",
            "request_id": request_id,
            "pinNo": quantity
        }

        headers = {
            "Content-Type": "application/json",
            "email": email,
            "password": password,
        }

        responses = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        response = responses.json()

        print(response)

        # -----------------------------------------------------
        # PROVIDER RESPONSE
        # -----------------------------------------------------

        if not isinstance(response, dict):
            return [
                (
                    "Your transaction is currently pending. "
                    "Please confirm the transaction status later "
                    "or contact support."
                ),
                "Pending",
                request_id
            ]

        stat = str(response.get("status", "")).strip()
        api_message = str(
            response.get(
                "message",
                "No response message was provided."
            )
        )

        # Ringo status 200 = successful
        if stat == "200":

            return [
                f"Successful {exam_type} {api_message}",
                "Successful",
                request_id
            ]

        # Ringo status 201 = processing
        elif stat == "201":

            return [
                f"Pending, {exam_type} {api_message}",
                "Pending",
                request_id
            ]

        # Any explicit provider failure
        elif stat:

            return [
                f"Oops Unsuccessful {exam_type}, {api_message}",
                "Unsuccessful",
                request_id
            ]

        # No status means the provider response is uncertain.
        else:

            return [
                (
                    f"Pending, {exam_type}. "
                    "The provider returned an incomplete response. "
                    "Please confirm the transaction status later."
                ),
                "Pending",
                request_id
            ]

    except Exception:

        # IMPORTANT:
        # We cannot know whether Ringo received/processed
        # the request if the network/API interaction fails.
        # Therefore DO NOT return Unsuccessful here.
        return [
            (
                "Your transaction is currently pending. "
                "Please confirm the transaction status later "
                "or contact support."
            ),
            "Pending",
            request_id
        ]

def result_imansub(exam_type, quantity, phone):

    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        request_idd = the_date + random_num
        return request_idd

    request_idd = request_id()

    # ---------------------------------------------------------
    # Validate exam type
    # ---------------------------------------------------------

    if exam_type not in ['waec', 'neco']:

        return [
            "Oops unsuccessful, invalid examination type",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # Validate quantity
    # ---------------------------------------------------------

    try:
        quantity = int(quantity)

    except (TypeError, ValueError):

        return [
            "Oops unsuccessful, invalid quantity",
            "Unsuccessful",
            request_idd
        ]

    if quantity < 1:

        return [
            "Oops unsuccessful, quantity must be at least 1",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # Provider configuration
    # ---------------------------------------------------------

    try:
        table = Config.objects.get(pk=1)

    except Exception:

        return [
            (
                "Pending, dear customer, your transaction is "
                "pending. Please contact support."
            ),
            "Pending",
            request_idd
        ]

    url = "https://imansub.com.ng/api/exam/"

    parameters = {
        "exam_type": exam_type,
        "quantity": quantity,
        "mobile_number": phone,
    }

    headers = {
        "Authorization": f"Token {table.imansub_api_key}",
        "Content-Type": "application/json",
    }

    # ---------------------------------------------------------
    # Provider request
    # ---------------------------------------------------------

    try:

        responses = requests.post(
            url,
            headers=headers,
            json=parameters,
            timeout=30
        )

        response = responses.json()

    except Exception:

        # Network/API exception does NOT prove that the
        # provider rejected the transaction.
        #
        # Keep it Pending to prevent an incorrect refund.

        return [
            (
                "Pending, dear customer, your transaction is "
                "pending. Please confirm the transaction status "
                "later or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Validate provider response
    # ---------------------------------------------------------

    if not isinstance(response, dict):

        return [
            (
                "Your transaction is currently pending. "
                "The provider returned an invalid response. "
                "Please confirm the transaction status later "
                "or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Safely read provider status
    # ---------------------------------------------------------

    res = str(
        response.get("status", "")
    ).strip().lower()

    description = str(
        response.get(
            "message",
            response.get(
                "msg",
                "No response message was provided."
            )
        )
    ).strip()

    # ---------------------------------------------------------
    # SUCCESSFUL
    # ---------------------------------------------------------

    if res == "successful":

        return [
            description,
            "Successful",
            request_idd
        ]

    # ---------------------------------------------------------
    # PENDING
    # ---------------------------------------------------------

    elif res in [
        "pending",
        "processing",
        "process",
        "in progress"
    ]:

        return [
            description,
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # DEFINITIVE FAILURE
    # ---------------------------------------------------------

    elif res == "unsuccessful":

        return [
            description,
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # EMPTY / UNKNOWN STATUS
    # ---------------------------------------------------------

    else:

        return [
            (
                "Your transaction is currently pending. "
                "The provider returned an incomplete or "
                "unrecognized response. Please confirm the "
                "transaction status later or contact support."
            ),
            "Pending",
            request_idd
        ]



def result_supercheap(exam_type, quantity, phone):

    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        request_idd = the_date + random_num
        return request_idd

    request_idd = request_id()

    # ---------------------------------------------------------
    # Validate exam type
    # ---------------------------------------------------------

    if exam_type not in ['waec', 'neco']:

        return [
            "Oops unsuccessful, invalid examination type",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # Validate quantity
    # ---------------------------------------------------------

    try:
        quantity = int(quantity)

    except (TypeError, ValueError):

        return [
            "Oops unsuccessful, invalid quantity",
            "Unsuccessful",
            request_idd
        ]

    if quantity < 1:

        return [
            "Oops unsuccessful, quantity must be at least 1",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # Provider endpoint
    # ---------------------------------------------------------

    url = "https://supercheapdata.com/api/exam-pin"

    parameters = {
        "exam_type": exam_type,
        "transaction_id": request_idd,
    }

    headers = {
        "Authorization": "Bearer b45e8b445f8b0142a506b42e636f6d31373038303134353934",
        "Content-Type": "application/json",
    }

    # ---------------------------------------------------------
    # Provider request
    # ---------------------------------------------------------

    try:

        responses = requests.post(
            url,
            headers=headers,
            json=parameters,
            timeout=30
        )

    except Exception:

        # We cannot know whether the provider received the
        # request. Therefore keep the transaction Pending.

        return [
            (
                "Pending, dear customer, your transaction is "
                "pending. Please confirm the transaction status "
                "later or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Parse provider response
    # ---------------------------------------------------------

    try:

        response = responses.json()

    except Exception:

        return [
            (
                "Pending, dear customer, your transaction is "
                "pending. The provider returned an invalid "
                "response. Please confirm the transaction "
                "status later or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Validate provider response
    # ---------------------------------------------------------

    if not isinstance(response, dict):

        return [
            (
                "Your transaction is currently pending. "
                "The provider returned an invalid response. "
                "Please confirm the transaction status later "
                "or contact support."
            ),
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # Safely obtain provider status
    # ---------------------------------------------------------

    res = str(
        response.get("status", "")
    ).strip().lower()

    description = str(
        response.get(
            "message",
            response.get(
                "msg",
                "No response message was provided."
            )
        )
    ).strip()

    # ---------------------------------------------------------
    # SUCCESSFUL
    # ---------------------------------------------------------

    if res == "success":

        return [
            f"Successful {description}",
            "Successful",
            request_idd
        ]

    # ---------------------------------------------------------
    # PENDING / PROCESSING
    # ---------------------------------------------------------

    elif res in [
        "pending",
        "processing",
        "process",
        "in progress"
    ]:

        return [
            f"Pending, {description}",
            "Pending",
            request_idd
        ]

    # ---------------------------------------------------------
    # DEFINITIVE FAILURE
    # ---------------------------------------------------------

    elif res in [
        "failed",
        "unsuccessful"
    ]:

        return [
            f"Oops {description}",
            "Unsuccessful",
            request_idd
        ]

    # ---------------------------------------------------------
    # EMPTY / UNKNOWN STATUS
    # ---------------------------------------------------------

    else:

        return [
            (
                "Your transaction is currently pending. "
                "The provider returned an incomplete or "
                "unrecognized response. Please confirm the "
                "transaction status later or contact support."
            ),
            "Pending",
            request_idd
        ]





