import os
import requests
import base64
from datetime import datetime
from requests.auth import HTTPBasicAuth
from dotenv import load_dotenv

load_dotenv()


class MpesaGateWay:
    def __init__(self):
        self.consumer_key = "qnEAm8ISGa4vkN9AtEjC3QF3Glp7wHPEhYopLWdFaBZGoyYK"
        self.consumer_secret = "YJxdVErtEL7Ul8NQVxfEbZoXURHLRS35cOZ3TWOrxZaj58PBA9GwRLYVaYdgU7G7"
        self.passkey = "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919"
        self.shortcode = "174379"
        self.base_url = "https://sandbox.safaricom.co.ke"

        # # Switch URL based on environment
        # if os.getenv("MPESA_ENVIRONMENT") == "production":
        #     self.base_url = "https://api.safaricom.co.ke"
        # else:
        #     self.base_url = "https://sandbox.safaricom.co.ke"

    def get_access_token(self):
        auth_url = f"{self.base_url}/oauth/v1/generate?grant_type=client_credentials"
        response = requests.get(auth_url, auth=HTTPBasicAuth(self.consumer_key, self.consumer_secret),timeout=30)
        if response.status_code == 200:
            return response.json().get("access_token")
        else:
            raise Exception(f"Failed to get access token: {response.text}")

    def get_password_and_timestamp(self):
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        password_str = f"{self.shortcode}{self.passkey}{timestamp}"
        password = base64.b64encode(password_str.encode()).decode("utf-8")
        return password, timestamp

    def initiate_stk_push(self, phone_number, amount, account_reference="reagancodes", transaction_desc="Payment"):
        access_token = self.get_access_token()
        password, timestamp = self.get_password_and_timestamp()

        stk_push_url = f"{self.base_url}/mpesa/stkpush/v1/processrequest"
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json"
        }
        payload = {
            "BusinessShortCode": self.shortcode,
            "Password": password,
            "Timestamp": timestamp,
            "TransactionType": "CustomerPayBillOnline",
            "Amount": amount,
            "PartyA": phone_number,
            "PartyB": self.shortcode,
            "PhoneNumber": phone_number,
            "CallBackURL": "https://daraja.reagancodes.com/callback/",
            "AccountReference": account_reference,
            "TransactionDesc": transaction_desc,
        }

        response = requests.post(stk_push_url, json=payload, headers=headers,timeout=30)
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Failed to initiate STK Push: {response.text}")


# gateway = MpesaGateWay()
# response = gateway.get_access_token()
# print(response)
# passwords = gateway.get_password_and_timestamp()
# print(passwords)
