import requests
from .models import Mtndatashare, Config, mailer
import random
from datetime import datetime
import uuid
import json
from base64 import b64encode
import logging

logger = logging.getLogger(__file__)



# MTN_______


def manual_sme1(network, plan, 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_id = request_id()

    try:

        table = Config.objects.get(pk=1)
        email = table.admin_mail
        
        mailer(email, f'{network} MANUAL',
               f'Dear Admin, sell {plan.volume} {network} on {phone}.')
        result = [f"Successful {plan.volume} {network} on {phone}. The activation of {plan.volume} {network} was successful.", "Successful", request_id]
        return result
    except:
        result = [f" Oops Transaction Unsuccessful", "Unsuccessful", request_id]
        return result

def plan_code(network, plan, phone):
    
    sell = globals()[plan.vending_medium](network, plan, phone)
    
    return sell


def sell_with_fallback(network, plan, phone, primary_provider, fallback_provider):
    """
    Execute MTN DataShare through the selected primary provider.
    Attempt the configured fallback only after a confirmed failure.
    Return [message, status, reference].
    """

    provider_plan_fields = {
        "autopilot_sme1": "autopilot_id",
        "ms_sme1": "ms_id",
        "atuns_sme1": "Atuns_web_id",
        "ms2_sme1": "ms_id_2",
        "topupaccess_sme1": "topupaccess_plan_id",
        "imansub_sme1": "imansub_plan_id",
        "gongoz_sme1": "gongoz_plan_id",
    }

    # Only these providers may be selected as global fallbacks.
    
    allowed_fallbacks = (
        "autopilot_sme1",
        "ms_sme1",
        "atuns_sme1",
        "ms2_sme1",
        "topupaccess_sme1",
        "imansub_sme1",
        "gongoz_sme1",
    )


    # Resolve the plan-specific provider when plan_code is selected globally.
    if primary_provider == "plan_code":
        primary_provider = plan.vending_medium

    primary_function = globals().get(primary_provider)

    # Treat local configuration problems as definite failures.
    # This allows a correctly configured fallback to be attempted.
    if not callable(primary_function):
        primary_result = [
            "MTN DataShare primary provider is not configured correctly",
            "Unsuccessful",
            "",
        ]

    else:
        primary_plan_field = provider_plan_fields.get(primary_provider)

        if primary_plan_field and not getattr(plan, primary_plan_field, None):
            primary_result = [
                "{} plan ID is not configured".format(primary_provider),
                "Unsuccessful",
                "",
            ]
        else:
            try:
                primary_result = primary_function(network, plan, phone)
            except Exception:
                logger.exception(
                    "MTN DataShare primary provider raised an exception"
                )
                return [
                    "Primary provider transaction status could not be confirmed",
                    "Pending",
                    "",
                ]

    # Validate the primary provider's response.
    if not isinstance(primary_result, (list, tuple)) or len(primary_result) < 3:
        logger.error("Invalid MTN DataShare primary provider result")
        return [
            "Primary provider returned an invalid response",
            "Pending",
            "",
        ]

    primary_message, primary_status, primary_reference = primary_result[:3]
    primary_status = str(primary_status).strip().lower()

    # Never attempt fallback after success or an uncertain result.
    if primary_status == "successful":
        return list(primary_result)

    if primary_status != "unsuccessful":
        return [
            str(primary_message or "Primary provider transaction is pending"),
            "Pending",
            str(primary_reference or ""),
        ]

    # No fallback configured, or fallback is the same provider.
    if not fallback_provider or fallback_provider == primary_provider:
        return list(primary_result)

    # Reject fallback providers outside the approved list.
    if fallback_provider not in allowed_fallbacks:
        logger.error(
            "Unsupported MTN DataShare fallback provider: %s",
            fallback_provider,
        )
        return list(primary_result)

    fallback_function = globals().get(fallback_provider)

    if not callable(fallback_function):
        logger.error(
            "MTN DataShare fallback function not found: %s",
            fallback_provider,
        )
        return list(primary_result)

    fallback_plan_field = provider_plan_fields.get(fallback_provider)

    if not fallback_plan_field or not getattr(plan, fallback_plan_field, None):
        logger.warning(
            "MTN DataShare fallback plan ID is missing for %s",
            fallback_provider,
        )
        return [
            "{} failed: {}. {} fallback plan ID is not configured.".format(
                primary_provider,
                primary_message,
                fallback_provider,
            ),
            "Unsuccessful",
            str(primary_reference or ""),
        ]

    logger.warning(
        "MTN DataShare primary provider %s returned a confirmed failure. "
        "Attempting fallback provider %s.",
        primary_provider,
        fallback_provider,
    )

    try:
        fallback_result = fallback_function(network, plan, phone)
    except Exception:
        logger.exception(
            "MTN DataShare fallback provider raised an exception"
        )
        return [
            "Primary provider failed; fallback transaction status could not be confirmed",
            "Pending",
            str(primary_reference or ""),
        ]

    if not isinstance(fallback_result, (list, tuple)) or len(fallback_result) < 3:
        logger.error("Invalid MTN DataShare fallback provider result")
        return [
            "Primary provider failed; fallback returned an invalid response",
            "Pending",
            str(primary_reference or ""),
        ]

    fallback_message, fallback_status, fallback_reference = fallback_result[:3]
    fallback_status = str(fallback_status).strip().lower()

    logger.warning(
        "MTN DataShare fallback completed. Primary=%s, fallback=%s, status=%s",
        primary_provider,
        fallback_provider,
        fallback_status,
    )

    if fallback_status == "successful":
        return list(fallback_result)

    if fallback_status == "unsuccessful":
        return list(fallback_result)

    # Unknown or processing statuses must remain Pending.
    return [
        str(fallback_message or "Fallback transaction status could not be confirmed"),
        "Pending",
        str(fallback_reference or primary_reference or ""),
    ]



def autopilot_sme1(network, plan, phone):
    request_id = (
        datetime.now().strftime("%Y%m%d%H%M")
        + uuid.uuid4().hex
    )[:25]

    try:
        table = Config.objects.get(pk=1)

        if not table.autopilot_key:
            return [
                "Autopilot API key is not configured",
                "Unsuccessful",
                request_id
            ]

        if not plan.autopilot_id:
            return [
                "Autopilot plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        url = "https://autopilotng.com/api/live/v1/data"

        payload = {
            "networkId": "1",
            "dataType": "DATA TRANSFER",
            "planId": plan.autopilot_id,
            "phone": phone,
            "reference": request_id
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": f"Bearer {table.autopilot_key}",
        }

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        # Do not trigger fallback when the provider's response
        # does not establish a definite transaction outcome.
        if response.status_code not in (200, 201):
            logger.warning(
                "Autopilot returned HTTP %s for reference %s",
                response.status_code,
                request_id
            )
            return [
                "Autopilot response did not confirm the transaction outcome",
                "Pending",
                request_id
            ]

        data = response.json()

        if not isinstance(data, dict):
            return [
                "Autopilot returned an unexpected response",
                "Pending",
                request_id
            ]

        provider_code = data.get("code")

        if provider_code in (200, 201, "200", "201"):
            transaction_data = data.get("data") or {}
            message = (
                transaction_data.get("message")
                if isinstance(transaction_data, dict)
                else None
            )

            return [
                str(message or "Autopilot transaction successful"),
                "Successful",
                request_id
            ]

        # No documented definitive failure codes have been
        # established yet. Treat all other responses as Pending.
        logger.warning(
            "Autopilot returned an unconfirmed result for reference %s: %s",
            request_id,
            data
        )

        message = data.get("message") or data.get("detail") or (
            "Autopilot transaction status could not be confirmed"
        )

        return [
            str(message),
            "Pending",
            request_id
        ]

    except Config.DoesNotExist:
        logger.exception("Autopilot configuration record does not exist")
        return [
            "Autopilot configuration record does not exist",
            "Unsuccessful",
            request_id
        ]

    except requests.exceptions.RequestException:
        logger.exception(
            "Autopilot connection error for reference %s",
            request_id
        )
        return [
            "Autopilot connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception(
            "Autopilot transaction error for reference %s",
            request_id
        )
        return [
            "Autopilot transaction status could not be confirmed",
            "Pending",
            request_id
        ]

def autopilot2_sme1(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()
    table = Config.objects.get(pk=1)
    url = "https://autopilotng.com/api/live/v1/data"
    payload = {
        "networkId": "1",
        "dataType": "DATA TRANSFER",
        "planId": plan.autopilot_id_2,
        "phone": phone,
        "reference": request_id
    }

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {table.autopilot_key_2}",

    }
    # if plan.volume == '5GB' or plan.volume == '3GB':
    #     return manual_sme1(network, plan, phone)
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        if 'code' in response:
            stat = response['code']
            if stat == 200:
                status = 'successful'
                api = response['data']['message']
            elif stat == 201:
                status = 'successful'
                api = response['data']['message']
            else:
                status = 'failed'
                api = response['data']['message']
        else:
            status = 'processing'
            api = 'processing'
    except:
        status = 'failed'
        api = "Transaction Failed"

    if status == "successful":
        result = [f"{api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"{api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f"{api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result







def ms_sme1(network, plan, phone):
    request_id = (
        datetime.now().strftime("%Y%m%d%H%M")
        + uuid.uuid4().hex
    )[:25]

    try:
        table = Config.objects.get(pk=1)

        if not table.ms_api_key or not table.ms_url:
            return [
                "MS Web API credentials or URL are not configured",
                "Unsuccessful",
                request_id
            ]

        if not plan.ms_id:
            return [
                "MS Web plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        url = f"{table.ms_url}/api/data/"

        payload = {
            "network": "1",
            "plan": plan.ms_id,
            "mobile_number": phone,
            "Ported_number": True
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Token {table.ms_api_key}"
        }

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        try:
            data = response.json()
        except ValueError:
            data = None

        if not isinstance(data, dict):
            return [
                "MS Web returned an invalid or unrecognised response",
                "Pending",
                request_id
            ]

        provider_status = str(data.get("Status", "")).strip().lower()
        api_message = (
            data.get("api_response")
            or data.get("error")
            or "MS Web transaction status could not be confirmed"
        )

        if isinstance(api_message, list):
            api_message = api_message[0] if api_message else (
                "MS Web transaction status could not be confirmed"
            )

        if response.status_code in (200, 201):
            if provider_status in ("successful", "success"):
                return [str(api_message), "Successful", request_id]

            if provider_status in ("failed", "failure", "unsuccessful", "rejected"):
                return [str(api_message), "Unsuccessful", request_id]

            return [str(api_message), "Pending", request_id]

        # An HTTP error alone does not prove that the transaction failed.
        if provider_status in ("failed", "failure", "unsuccessful", "rejected"):
            return [str(api_message), "Unsuccessful", request_id]

        logger.warning(
            "MS Web returned HTTP %s with unconfirmed status: %s",
            response.status_code,
            data
        )

        return [
            str(api_message),
            "Pending",
            request_id
        ]

    except Config.DoesNotExist:
        logger.exception("MS Web configuration record does not exist")
        return [
            "MS Web configuration record does not exist",
            "Unsuccessful",
            request_id
        ]

    except requests.exceptions.RequestException:
        logger.exception("MS Web connection error")
        return [
            "MS Web connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception("MS Web transaction error")
        return [
            "MS Web transaction status could not be confirmed",
            "Pending",
            request_id
        ]

                

def gongoz_sme1(network, plan, phone):
    request_id = datetime.now().strftime("%Y%m%d%H%M") + uuid.uuid4().hex[:13]

    try:
        table = Config.objects.get(pk=1)

        if not table.gongoz_api_key or not plan.gongoz_plan_id:
            return [
                "Gongoz API key or plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        url = "https://www.gongozconcept.com/api/data/"

        payload = {
            "network": 1,
            "plan": plan.gongoz_plan_id,
            "mobile_number": phone,
            "Ported_number": True
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": "Token {}".format(table.gongoz_api_key)
        }

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        try:
            data = response.json()
        except ValueError:
            data = {}

        provider_status = str(
            data.get("Status", data.get("status", ""))
        ).strip().lower()

        api = (
            data.get("api_response")
            or data.get("apiresponse")
            or data.get("message")
            or ""
        )

        # Confirmed successful purchase
        provider_reference = str(
            data.get("ident") or data.get("id") or request_id
        )

        if response.status_code in (200, 201) and provider_status in ("successful", "success"):
            return [
                str(api or "Gongoz data purchase successful"),
                "Successful",
                provider_reference
            ]

        if provider_status in ("processing", "pending"):
            return [
                str(api or "Gongoz transaction is processing"),
                "Pending",
                provider_reference
            ]

        if response.status_code in (200, 201) and provider_status == "failed":
            return [
                str(api or "Gongoz transaction failed"),
                "Unsuccessful",
                provider_reference
            ]

        # Confirmed rejection from the actual response tested in Postman
        errors = data.get("error", [])
        if isinstance(errors, list):
            error_text = " ".join(str(item) for item in errors).lower()
        else:
            error_text = str(errors).lower()

        if response.status_code == 400 and "insufficient balance" in error_text:
            return [
                "Gongoz: insufficient balance for this plan",
                "Unsuccessful",
                request_id
            ]

        # Do not treat unknown responses or server errors as confirmed failures
        logger.warning(
            "Gongoz MTN DataShare uncertain response. HTTP %s; response: %s",
            response.status_code,
            response.text[:1000]
        )

        return [
            str(api or "Gongoz transaction status could not be confirmed"),
            "Pending",
            request_id
        ]

    except requests.exceptions.RequestException:
        logger.exception("Gongoz MTN DataShare connection error")
        return [
            "Gongoz connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception("Unexpected Gongoz MTN DataShare error")
        return [
            "Gongoz transaction status could not be confirmed",
            "Pending",
            request_id
        ]

def apisub_sme1(network, plan, 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_id = request_id()

    url = "https://apisubportal.com/api/buydata.php"
    parameters = {
        "api_key": apisubportal_key,
        "network": 'MTN_DIRECT_GIFTING',
        "return_url": "yarabpro.com",
        "plans": plan.apisubportal_plan_id,
        "phonenumber": phone,
    }

    try:
        responses = requests.get(url, params=parameters)
        response = json.loads(responses.text)
    except:
        result = [(
            f"Pending, dear customer, your transaction is pending, you can confirm if "
            f"the service has being delivered or contact admin"), "Pending", request_id]
        return result

    res = response["status"]

    if res == "success":
        description = response["msg"]
        result = [f"Successful {network}  {description}", "Successful", request_id]
        return result

    elif res == "unsuccessful":
        description = response["msg"]
        result = [f" Oops  {network} {description}", "Unsuccessful", request_id]
        return result

    else:
        result = [(
            f"Pending, dear customer, your transaction is pending, you can confirm if "
            f"the service has being delivered or contact admin"), "Pending", request_id]
        return result


def atuns_sme1(network, plan, phone):
    request_id = datetime.now().strftime("%Y%m%d%H%M") + uuid.uuid4().hex[:13]

    try:
        table = Config.objects.get(pk=1)

        if not table.Atuns_web_api_key or not table.Atuns_web_url:
            return [
                "ATUNS API configuration is incomplete",
                "Unsuccessful",
                request_id
            ]

        if not plan.Atuns_web_id:
            return [
                "ATUNS plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        url = "{}/api/data/".format(table.Atuns_web_url.rstrip("/"))

        payload = {
            "network": "1",
            "plan": plan.Atuns_web_id,
            "mobile_number": phone,
            "Ported_number": True
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": "Token {}".format(table.Atuns_web_api_key)
        }

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        try:
            data = response.json()
        except ValueError:
            data = {}

        provider_status = str(
            data.get("Status", data.get("status", ""))
        ).strip().lower()

        api = (
            data.get("api_response")
            or data.get("message")
            or ""
        )

        if response.status_code in (200, 201):
            if provider_status in ("successful", "success"):
                return [
                    str(api or "Transaction successful"),
                    "Successful",
                    request_id
                ]

            if provider_status in ("processing", "pending"):
                return [
                    str(api or "Transaction processing"),
                    "Pending",
                    request_id
                ]

            if provider_status in ("failed", "failure", "unsuccessful"):
                return [
                    str(api or "ATUNS confirmed transaction failure"),
                    "Unsuccessful",
                    request_id
                ]

        # Unknown statuses and HTTP errors are not safe grounds for failover
        logger.warning(
            "ATUNS MTN DataShare uncertain response. HTTP %s; response: %s",
            response.status_code,
            response.text[:1000]
        )

        return [
            str(api or "ATUNS transaction status could not be confirmed"),
            "Pending",
            request_id
        ]

    except Config.DoesNotExist:
        logger.exception("ATUNS configuration record does not exist")
        return [
            "ATUNS configuration record does not exist",
            "Unsuccessful",
            request_id
        ]

    except requests.exceptions.RequestException:
        logger.exception("ATUNS MTN DataShare connection error")
        return [
            "ATUNS connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception("Unexpected ATUNS MTN DataShare error")
        return [
            "ATUNS transaction status could not be confirmed",
            "Pending",
            request_id
        ]




def simserverslot_sme1(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()
    table = Config.objects.get(pk=1)
    url = f"{table.simserver_web_url}/api/v2/datashare/"
    payload = {
        "api_key": table.simserver_web_key,
        "product_code": plan.simserver_web_id,
        "phone": phone,
        "callback":"cheapdatasales.com/callback.php"
    }
    
   
    try:
        responses = requests.post(url, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "text_status" in response and response["text_status"]  == "COMPLETED" :
                status = 'successful'
                if "data" in response and "true_response" in response["data"]:
                    api = response["data"]["true_response"]
                else:
                    api = "Transaction successful"
            elif "text_status" in response and response["text_status"]  == "FAILED":
                status = 'failed'
                api = "Transaction Failed"
            else:
                status = 'processing'
                api = 'Transaction processing'
                
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result




def simserverslot2_sme1(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()
    table = Config.objects.get(pk=1)
    url = f"{table.simserver_web_url_2}/api/v2/datashare/"
    payload = {
        "api_key": table.simserver_web_key_2,
        "product_code": plan.simserver_web_id_2,
        "phone": phone,
        "callback":"justpayng.com/callback.php"
    }
    
   
    try:
        responses = requests.post(url, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "text_status" in response and response["text_status"]  == "COMPLETED" :
                status = 'successful'
                if "data" in response and "true_response" in response["data"]:
                    api = response["data"]["true_response"]
                else:
                    api = "Transaction successful"
            elif "text_status" in response and response["text_status"]  == "FAILED":
                status = 'failed'
                api = "Transaction Failed"
            else:
                status = 'processing'
                api = 'Transaction processing'
                
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result


def simserverslot3_sme1(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()
    table = Config.objects.get(pk=1)
    url = f"{table.simserver_web_url_3}/api/v2/datashare/"
    payload = {
        "api_key": table.simserver_web_key_3,
        "product_code": plan.simserver_web_id_3,
        "phone": phone,
        "callback":"cheapdatasales.com/callback.php"
    }
    
    try:
        responses = requests.post(url, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "text_status" in response and response["text_status"]  == "COMPLETED" :
                status = 'successful'
                if "data" in response and "true_response" in response["data"]:
                    api = response["data"]["true_response"]
                else:
                    api = "Transaction successful"
            elif "text_status" in response and response["text_status"]  == "FAILED":
                status = 'failed'
                api = "Transaction Failed"
            else:
                status = 'processing'
                api = 'Transaction processing'
                
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"{api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"{api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f"{api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result




def ms2_sme1(network, plan, phone):
    request_id = (
        datetime.now().strftime("%Y%m%d%H%M")
        + uuid.uuid4().hex
    )[:25]

    try:
        table = Config.objects.get(pk=1)

        if not table.ms_api_key_2 or not table.ms_url_2:
            return [
                "MS Web2 API credentials or URL are not configured",
                "Unsuccessful",
                request_id
            ]

        if not plan.ms_id_2:
            return [
                "MS Web2 plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        url = f"{table.ms_url_2}/api/data/"

        payload = {
            "network": "1",
            "plan": plan.ms_id_2,
            "mobile_number": phone,
            "Ported_number": True
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Token {table.ms_api_key_2}"
        }

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        try:
            data = response.json()
        except ValueError:
            data = None

        if not isinstance(data, dict):
            return [
                "MS Web2 returned an invalid or unrecognised response",
                "Pending",
                request_id
            ]

        provider_status = str(data.get("Status", "")).strip().lower()
        api_message = (
            data.get("api_response")
            or data.get("error")
            or "MS Web2 transaction status could not be confirmed"
        )

        if isinstance(api_message, list):
            api_message = api_message[0] if api_message else (
                "MS Web2 transaction status could not be confirmed"
            )

        if response.status_code in (200, 201):
            if provider_status in ("successful", "success"):
                return [str(api_message), "Successful", request_id]

            if provider_status in ("failed", "failure", "unsuccessful", "rejected"):
                return [str(api_message), "Unsuccessful", request_id]

            return [str(api_message), "Pending", request_id]

        if provider_status in ("failed", "failure", "unsuccessful", "rejected"):
            return [str(api_message), "Unsuccessful", request_id]

        logger.warning(
            "MS Web2 returned HTTP %s with unconfirmed status: %s",
            response.status_code,
            data
        )

        return [
            str(api_message),
            "Pending",
            request_id
        ]

    except Config.DoesNotExist:
        logger.exception("MS Web2 configuration record does not exist")
        return [
            "MS Web2 configuration record does not exist",
            "Unsuccessful",
            request_id
        ]

    except requests.exceptions.RequestException:
        logger.exception("MS Web2 connection error")
        return [
            "MS Web2 connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception("MS Web2 transaction error")
        return [
            "MS Web2 transaction status could not be confirmed",
            "Pending",
            request_id
        ]

  


def smeplug_sme1(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()
    table = Config.objects.get(pk=1)
    key = table.smeplug_api_key
    
    url = "https://smeplug.ng/api/v1/data/purchase"
    headers = {
            'Content-Type': 'application/json', 'User-Agent': 'Custom', 
            'Authorization': f'Bearer {key}'
                }
    payload = {
        "network_id": "1",
        "plan_id": plan.smeplug_id,
        "phone": phone,
    }

    
    try:
        responses = requests.post(url, headers=headers, json=payload)
        resp = responses.json()
        
        if 'data' in resp and 'current_status' in resp['data'] and 'msg' in resp['data']:
            if resp['data']['current_status'] == "success" or  resp['data']['current_status'] == "processing":
                status = "successful"
                api = resp['data']['msg']
                
            else:
                status = "failed"
                api = resp['data']['msg']
        else:
            if 'msg' in resp:
                status = "failed"
                api = resp['msg']
            else:
                status = "failed"
                api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"{api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"{api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f"{api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def topupaccess_sme1(network, plan, phone):
    def request_id_gen():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        token = uuid.uuid4().hex
        return (the_date + token)[:25]

    request_id = request_id_gen()

    try:
        table = Config.objects.get(pk=1)

        if not table.topupaccess_api_key or not table.topupaccess_pin:
            return [
                "Topupaccess API key or PIN is not configured",
                "Unsuccessful",
                request_id
            ]

        url = "https://server.topupaccess.com/api/data/topup"

        headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format(
                table.topupaccess_api_key
            ),
        }

        payload = {
            "id": plan.topupaccess_plan_id,
            "pin": table.topupaccess_pin,
            "number": phone,
        }

        if not plan.topupaccess_plan_id:
            return [
                "Topupaccess plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        if response.status_code in (200, 201):
            try:
                data = response.json()
            except ValueError:
                return [
                    "Topupaccess returned an unreadable response",
                    "Pending",
                    request_id
                ]

            provider_status = str(
                data.get("status", "")
            ).strip().lower()

            api = data.get("remark") or "Topupaccess response received"

            if provider_status == "success":
                return [str(api), "Successful", request_id]

            elif provider_status in ("reversed", "failed"):
                return [str(api), "Unsuccessful", request_id]

            else:
                return [str(api), "Pending", request_id]

        elif response.status_code >= 500:
            return [
                "Topupaccess server error; transaction status is uncertain",
                "Pending",
                request_id
            ]

        else:
            try:
                error_data = response.json()
            except ValueError:
                error_data = {}

            error_status = str(
                error_data.get("status", "")
            ).strip().lower()

            error_message = (
                error_data.get("remark")
                or error_data.get("error")
                or "Topupaccess returned HTTP {}".format(
                    response.status_code
                )
            )

            if error_status in (
                "failed", "reversed", "failure",
                "unsuccessful", "rejected"
            ):
                return [str(error_message), "Unsuccessful", request_id]

            return [str(error_message), "Pending", request_id]

    except requests.exceptions.RequestException:
        logger.exception("Topupaccess connection error")
        return [
            "Topupaccess connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception("Topupaccess transaction error")
        return [
            "Topupaccess transaction status could not be confirmed",
            "Pending",
            request_id
        ]



def imansub_sme1(network, plan, phone):
    request_id = (
        datetime.now().strftime("%Y%m%d%H%M")
        + uuid.uuid4().hex
    )[:25]

    try:
        table = Config.objects.get(pk=1)

        if not table.imansub_api_key:
            return [
                "IMANSUB API key is not configured",
                "Unsuccessful",
                request_id
            ]

        if not plan.imansub_plan_id:
            return [
                "IMANSUB plan ID is not configured",
                "Unsuccessful",
                request_id
            ]

        url = "https://imansub.com.ng/api/data/"

        payload = {
            "network": "1",
            "plan": plan.imansub_plan_id,
            "mobile_number": phone,
            "Ported_number": True
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Token {table.imansub_api_key}"
        }

        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=30
        )

        try:
            data = response.json()
        except ValueError:
            data = None

        if not isinstance(data, dict):
            return [
                "IMANSUB returned an invalid or unrecognised response",
                "Pending",
                request_id
            ]

        provider_status = str(data.get("Status", "")).strip().lower()
        api_message = (
            data.get("api_response")
            or data.get("error")
            or "IMANSUB transaction status could not be confirmed"
        )

        if isinstance(api_message, list):
            api_message = api_message[0] if api_message else (
                "IMANSUB transaction status could not be confirmed"
            )

        if response.status_code in (200, 201):
            if provider_status in ("successful", "success"):
                return [str(api_message), "Successful", request_id]

            if provider_status in ("failed", "failure", "unsuccessful", "rejected"):
                return [str(api_message), "Unsuccessful", request_id]

            return [str(api_message), "Pending", request_id]

        if provider_status in ("failed", "failure", "unsuccessful", "rejected"):
            return [str(api_message), "Unsuccessful", request_id]

        logger.warning(
            "IMANSUB returned HTTP %s with unconfirmed status: %s",
            response.status_code,
            data
        )

        return [
            str(api_message),
            "Pending",
            request_id
        ]

    except Config.DoesNotExist:
        logger.exception("IMANSUB configuration record does not exist")
        return [
            "IMANSUB configuration record does not exist",
            "Unsuccessful",
            request_id
        ]

    except requests.exceptions.RequestException:
        logger.exception("IMANSUB connection error")
        return [
            "IMANSUB connection error; transaction status is uncertain",
            "Pending",
            request_id
        ]

    except Exception:
        logger.exception("IMANSUB transaction error")
        return [
            "IMANSUB transaction status could not be confirmed",
            "Pending",
            request_id
        ]

  

