from appservices.common.util import *
import hashlib

def generate_aes_key(access_token):
	"""Generate a 32-byte AES key from MD5 hexdigest()."""
	md5_hex = hashlib.md5(access_token.encode()).hexdigest()  # 32-character HEX string

	#### recieved a 32 bytes key now use this key as secret key to encrypt and decrypt so 
	###### use .decode() to convert this key to bytes to perform encryption
	return md5_hex.encode()  #  Returns a valid 32-byte AES key

def generate_iv():
	"""Generate a 16-byte random IV."""
	return os.urandom(16)

def encrypt_aes_cbc(plain_text, accessToken):
	"""Encrypt plain text using AES-256-CBC with PKCS7 padding."""
	
	key = generate_aes_key(accessToken)
	# print("key",key)
	iv = generate_iv()  # Generate a new IV for 1each encryption
	cipher = AES.new(key, AES.MODE_CBC, iv=iv)

	padded_data = pad(plain_text.encode(), AES.block_size)  # Apply PKCS7 padding
	encrypted_bytes = cipher.encrypt(padded_data)

	# Combine IV + Encrypted Data and encode in Base64
	encrypted_data = base64.b64encode(iv + encrypted_bytes).decode()
	return encrypted_data

def safegold_decrypt(encrypted, key):
	decrypted_text = ""
	try:
		key = generate_aes_key(key)
		
		# secret_key_hex_bytes = unhexlify(key)
		# print("secret_key_hex_bytes",key)
		encrypted_combined_bytes = base64.b64decode(encrypted)
		iv = encrypted_combined_bytes[:16]
		# print("iv",iv)
		encrypted_payload = encrypted_combined_bytes[16:]
		cipher = AES.new(key, AES.MODE_CBC, iv=iv)
		decrypted_bytes = unpad(cipher.decrypt(encrypted_payload), AES.block_size)
		# print("decrypted_bytes",decrypted_bytes)
		decrypted_text = decrypted_bytes.decode()
		# print("decrypted_text",decrypted_text)
		return decrypted_text
	except Exception as e:
		app.logger.error(traceback.format_exc())
		return decrypted_text


################################################ General Apis ################################################### 
def safegold_registration(get_base_url, access_token, name, mobile_no, email, pin_code):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		registration_request_body = {
			"name": name,
			"mobile_no": mobile_no,
			"email": email,
			"pin_code": pin_code,
		}

		### uncommment step 2 3 4 if needed to send encrypted data

		# Step 2: Convert the dictionary to a JSON string before encryption
		# request_body_json = json.dumps(registration_request_body)

		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/users"


		# encryptedBody = encrypt_aes_cbc(request_body_json, access_token)

		# payload = {"data": encryptedBody}

		# test_reqdecrypte = safegold_decrypt(encryptedBody, access_token)


		safeGoldResponse = requests.post(url, json=registration_request_body, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		
		safeGoldResponseJson = json.loads(safeGoldResponseJson)

		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		user_id = ""
		gold_balance = 0
		kyc_requirement = ""
		identity_required = ""
		pan_required = ""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			user_id = decrypted_response.get("id")
			gold_balance = decrypted_response.get("gold_balance")
			kyc_requirement = decrypted_response.get("kyc_requirement")
			identity_required = kyc_requirement.get("identity_required")
			pan_required = kyc_requirement.get("pan_required")
			message="User Registration Successful"
		elif safeGoldResponse.status_code == 400:
			message=decrypted_response.get("message")
		else:
			message="Unable to Create User"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"user_id": user_id,
			"gold_balance": gold_balance,
			"kyc_requirement": kyc_requirement,
			"identity_required": identity_required,
			"pan_required": pan_required,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_kyc_update(get_base_url, access_token, safeGoldUserId, pan_number,identity_no ):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		kyc_update_request_body =  { 
										"kyc_requirement": {
												"pan_no": pan_number,
												"identity_no": identity_no
											} 
									}
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/users/{safeGoldUserId}/kyc-update"

		print(kyc_update_request_body, "((((SAFEGOLD kyc update REQUEST BODY - JSON))))")

		safeGoldResponse = requests.post(url, json=kyc_update_request_body, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		
		safeGoldResponseJson = json.loads(safeGoldResponseJson)

		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD Kyc Update DECRYPTED RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		user_id = ""
		name = ""
		mobile_no = ""
		pincode = ""
		gold_balance = 0
		kyc_requirement = ""
		identity_required = ""
		pan_required = ""
		identity_no = ""
		pan_no = ""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			user_id = decrypted_response.get("id")
			name = decrypted_response.get("name")
			mobile_no = decrypted_response.get("mobile_no")
			pincode = decrypted_response.get("pincode")
			gold_balance = decrypted_response.get("gold_balance")
			kyc_requirement = decrypted_response.get("kyc_requirement")
			identity_required = kyc_requirement.get("identity_required")
			pan_required = kyc_requirement.get("pan_required")
			identity_no = kyc_requirement.get("identity_no")
			pan_no = kyc_requirement.get("pan_no")
			message="User Registration Successful"

		else:
			responseStatus= 0
			message="Unable to Update Kyc "
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"user_id": user_id,
			"name": name,
			"mobile_no": mobile_no,
			"pincode": pincode,
			"gold_balance": gold_balance,
			"kyc_requirement": kyc_requirement,
			"identity_required": identity_required,
			"pan_required": pan_required,
			'identity_no': identity_no,
			'pan_no': pan_no,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict
	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_mobile_number_update(get_base_url, access_token, safeGoldUserId, new_phone_no ):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		kyc_update_request_body =  { 
			"new_phone_no": new_phone_no
									}
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/users/{safeGoldUserId}/direct-update-phone-no"

		print(kyc_update_request_body, "((((SAFEGOLD mobile number update REQUEST BODY - JSON))))",url)

		safeGoldResponse = requests.post(url, json=kyc_update_request_body, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		
		safeGoldResponseJson = json.loads(safeGoldResponseJson)

		encryptedResponseData = safeGoldResponseJson.get("data", "")
		print(encryptedResponseData, "((((SAFEGOLD mobile number update RESPONSE DATA))))")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD mobile number update RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		message=""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			message="User Mobile Number Update Successful"
		elif safeGoldResponse.status_code == 400:
			message = decrypted_response.get("message")
		else:
			responseStatus= 0
			message="Unable to Update User Mobile Number"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict
	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_balance_check(get_base_url, access_token, safeGoldUserId):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}
	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"accept": "application/json",
		}
		url = f"{get_base_url}/v1/users/{safeGoldUserId}"

		safeGoldResponse = requests.get(url, headers=headers)
		print(safeGoldResponse, "((((SAFEGOLD balance Check RESPONSE))))")

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")


		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD balance Check DECRYPTED RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		user_id = ""
		gold_balance = 0
		sellable_balance=""
		kyc_requirement = ""
		identity_required = ""
		pan_required = ""
		message=""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			user_id = decrypted_response.get("id")
			gold_balance = decrypted_response.get("gold_balance")
			sellable_balance = decrypted_response.get("sellable_balance")
			kyc_requirement = decrypted_response.get("kyc_requirement")
			identity_required = kyc_requirement.get("identity_required")
			pan_required = kyc_requirement.get("pan_required")
			message="Successfullly Fetched Balance"
		elif safeGoldResponse.status_code == 404:
			message = decrypted_response.get("message")
		else:
			message="Unable To Fetch Balance"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"user_id": user_id,
			"gold_balance": gold_balance,
			"sellable_balance": sellable_balance,
			"kyc_requirement": kyc_requirement,
			"identity_required": identity_required,
			"pan_required": pan_required,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict
	
def safegold_get_transactions(get_base_url, access_token, safeGoldUserId):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}
	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"accept": "application/json",
		}
		url = f"{get_base_url}/v1/users/{safeGoldUserId}/transactions"

		
		safeGoldResponse = requests.get(url, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")


		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD balance Check DECRYPTED RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		user_id = ""
		transactionsList = []
		meta = {}
		message=""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			transactionsList = decrypted_response.get("transactions")
			meta = decrypted_response.get("meta")
			message="Successfullly Fetched Transactions"
		elif safeGoldResponse.status_code == 404:
			message = decrypted_response.get("message")
		else:
			message="Unable To Fetch Transactions"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"user_id": user_id,
			"transactionsList": transactionsList,
			"meta": meta,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict
#############################################################################################################


################################################ Buy Apis ###################################################
def safegold_get_buy_price(get_base_url, access_token):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}
	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/buy-price"

		safeGoldResponse = requests.get(url, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD buy price DECRYPTED RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		current_price = ""
		applicable_tax = ""
		rate_id = ""
		rate_validity = ""
		message=""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			current_price = decrypted_response.get("current_price")
			applicable_tax = decrypted_response.get("applicable_tax")
			rate_id = decrypted_response.get("rate_id")
			rate_validity = decrypted_response.get("rate_validity")
			message="Successfully Verified Buy Price"
		elif safeGoldResponse.status_code == 404:
			message = decrypted_response.get("message","")
		else:
			message="Unable to Get Buy Price"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"current_price": current_price,
			"applicable_tax": applicable_tax,
			"rate_id": rate_id,
			"rate_validity": rate_validity,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_buy_verify(get_base_url, access_token,safeGoldUserId, rate_id, gold_amount, buy_price):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		registration_request_body = {
			"rate_id": rate_id,
			"gold_amount": gold_amount,
			"buy_price": buy_price
		}

		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v4/users/{safeGoldUserId}/buy-gold-verify"

		print(registration_request_body, "((((SAFEGOLD Buy Verify Reqeust Body))))") 
		safeGoldResponse = requests.post(url, json=registration_request_body, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		
		requestData = [registration_request_body]
		responseData = [decrypted_response]
		responseStatus=0
		tx_id = ""
		rate_id = ""
		sg_rate = ""
		gold_amount = ""
		buy_price = ""
		pre_gst_buy_price = ""
		partner_rate = ""
		gst_amount = ""
		user_id = ""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			tx_id = decrypted_response.get("tx_id")
			rate_id = decrypted_response.get("rate_id")
			sg_rate = decrypted_response.get("sg_rate")
			gold_amount = decrypted_response.get("gold_amount")
			buy_price = decrypted_response.get("buy_price")
			pre_gst_buy_price = decrypted_response.get("pre_gst_buy_price")
			partner_rate = decrypted_response.get("partner_rate")
			gst_amount = decrypted_response.get("gst_amount")
			user_id = decrypted_response.get("user_id")
			message="Successfully Verified Buy Price"

		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Verify Buy Price"
		
		safeGoldResponseDict = {

			"responseStatus": responseStatus,
			"tx_id": tx_id,
			"rate_id": rate_id,
			"sg_rate": sg_rate,
			"gold_amount": gold_amount,
			"buy_price": buy_price,
			"partner_rate": partner_rate,
			"pre_gst_buy_price": pre_gst_buy_price,
			"gst_amount": gst_amount,
			"user_id": user_id,
			"message": message,
			"responseData": responseData,
			"requestData": requestData,

		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_buy_confirm(get_base_url, access_token,safeGoldUserId, tx_id, pincode, date):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		registration_request_body = {
			"tx_id": tx_id,
			"pincode": pincode,
			"date": date
		}

		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/users/{safeGoldUserId}/buy-gold-confirm"

		safeGoldResponse = requests.post(url, json=registration_request_body, headers=headers)
		# print(safeGoldResponse, "((((SAFEGOLD Buy confirm RESPONSE))))") 

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED Buy confirm RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		invoice_id=""

		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			
			responseStatus = 1
			invoice_id = decrypted_response.get("invoice_id")
			message="Buy Processed Successfully"

		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Raise Buy Request"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"user_id": safeGoldUserId,
			"invoice_id": invoice_id,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_buy_status_check(get_base_url, access_token, tx_id):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/buy-gold/{tx_id}/order-status"
		safeGoldResponse = requests.get(url,headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED Buy Status Check RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		invoice_id=""
		created_at =  ""
		status =  ""
		realization_status =  ""
		payment_status = ""

		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			
			responseStatus = 1
			created_at = decrypted_response.get("created_at")
			sgStatus = decrypted_response.get("status")
			invoice_id = decrypted_response.get("invoice_id")
			realization_status = decrypted_response.get("realization_status") ### safegold documenation says to ignore these2 keys
			payment_status = decrypted_response.get("payment_status") ### safegold documenation says to ignore these2 keys
			message="Status Check Successful"
		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Check Buy Status"
		
		transactionStatus = 2
		status=2
		
		if sgStatus == 1: ### in SG 1 is success
			transactionStatus = 1
			status=1
		elif sgStatus == 2: ### in SG 2 is failure
			transactionStatus = 0
			status=0
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"transactionStatus": transactionStatus,
			# "user_id": safeGoldUserId,
			"invoice_id": invoice_id,
			"created_at": created_at,
			"status": status,
			# "realization_status": realization_status,
			# "payment_status": payment_status,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict
	
def safegold_buy_invoice(get_base_url, access_token, tx_id):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/transactions/{tx_id}/fetch-invoice"

		safeGoldResponse = requests.get(url,headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")


		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED Buy invoice RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		invoiceLink=""

		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			responseStatus = 1
			invoiceLink = decrypted_response.get("link")
			message="Invoice Fetched Successfully"

		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Get Invoice Data"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"invoiceLink": invoiceLink,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict
##############################################################################################################


################################################ Sell Apis ###################################################
def safegold_get_sell_price(get_base_url, access_token):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}
	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/sell-price"

		safeGoldResponse = requests.get(url, headers=headers)
		# print(safeGoldResponse, "((((SAFEGOLD sell price RESPONSE))))")

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD sell price DECRYPTED RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		current_price = ""
		rate_id = ""
		rate_validity = ""
		message=""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			current_price = decrypted_response.get("current_price")
			rate_id = decrypted_response.get("rate_id")
			rate_validity = decrypted_response.get("rate_validity")
			message="Successfully Fetched Sell Price"
		elif safeGoldResponse.status_code == 404:
			message = decrypted_response.get("message","")
		else:
			message="Unable to Get Sell Price"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"current_price": current_price,
			"rate_id": rate_id,
			"rate_validity": rate_validity,
			"message": message,
			"responseData": responseData,
		}

		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_sell_verify(get_base_url, access_token,safeGoldUserId, rate_id, gold_amount, sell_price):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		registration_request_body = {
			"rate_id": rate_id,
			"gold_amount": gold_amount,
			"sell_price": sell_price
		}

		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v4/users/{safeGoldUserId}/sell-gold-verify"

		print(registration_request_body, "((((SAFEGOLD Sell Verify Reqeust Body))))") 
		safeGoldResponse = requests.post(url, json=registration_request_body, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED Sell Verify RESPONSE))))")

		requestData = [registration_request_body]
		responseData = [decrypted_response]
		responseStatus=0
		tx_id = ""
		rate_id = ""
		rate = ""
		gold_amount = ""
		sell_price = ""
		user_id = ""

		if safeGoldResponse.status_code == 200:
			responseStatus = 1
			tx_id = decrypted_response.get("tx_id")
			rate_id = decrypted_response.get("rate_id")
			rate = decrypted_response.get("rate")
			gold_amount = decrypted_response.get("gold_amount")
			sell_price = decrypted_response.get("sell_price")
			user_id = decrypted_response.get("user_id")
			message="Successfully Verified Sell Price"

		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Verify Sell Price"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"tx_id": tx_id,
			"rate_id": rate_id,
			"rate": rate,
			"gold_amount": gold_amount,
			"sell_price": sell_price,
			"user_id": user_id,
			"message": message,
			"responseData": responseData,
			"requestData": requestData,

		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict    

def safegold_sell_confirm(get_base_url, access_token,safeGoldUserId, tx_id, pincode, date):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		registration_request_body = {
			"tx_id": tx_id,
			"pincode": pincode,
			"date": date
		}

		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/users/{safeGoldUserId}/sell-gold-confirm"

		print(registration_request_body, "((((SAFEGOLD Sell Confirm Reqeust Body))))")
		safeGoldResponse = requests.post(url, json=registration_request_body, headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED Sell confirm RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		invoice_id=""

		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			
			responseStatus = 1
			invoice_id = decrypted_response.get("invoice_id")
			message="Sell Request Processed Successfully"

		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Raise Sell Request"
		
		safeGoldResponseDict = {
			"responseStatus": responseStatus,
			"user_id": safeGoldUserId,
			"invoice_id": invoice_id,
			"message": message,
			"responseData": responseData,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

def safegold_sell_status_check(get_base_url, access_token, tx_id):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		url = f"{get_base_url}/v1/sell-gold/{tx_id}/order-status"

		safeGoldResponse = requests.get(url,headers=headers)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD REGISTRATION DECRYPTED Sell Status Check RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		bank_reference_number =  ""
		created_at =  ""
		invoice_id=""
		settlement_date = ""
		settled_status = ""
		status =  ""
		transactionStatus = 2

		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			
			responseStatus = 1
			
			bank_reference_number = decrypted_response.get("bank_reference_number") ### safegold documenation says to ignore these2 keys
			created_at = decrypted_response.get("created_at")
			invoice_id = decrypted_response.get("invoice_id")
			message="Status Check Successful"
			sgStatus = decrypted_response.get("status") #### here 1 is success and 2 is failure and 
			settled_status = decrypted_response.get("settled_status") ### safegold documenation says to ignore these2 keys
			settlement_date = decrypted_response.get("settlement_date") ### safegold documenation says to ignore these2 keys

		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message=decrypted_response.get("message","")
		else:
			message="Unable to Check Sell Status"
		
		status=2
		transactionStatus = 2
		if sgStatus == 1: ### in SG 1 is success
			transactionStatus = 1
			status=1
		elif sgStatus == 2: ### in SG 2 is failure
			transactionStatus = 0
			status=0
		safeGoldResponseDict = {
			"bank_reference_number": bank_reference_number,
			"created_at": created_at,
			"invoice_id": invoice_id,
			"transactionStatus": transactionStatus,
			"message": message,
			"responseData": responseData,
			"responseStatus": responseStatus,
			"settlement_date": settlement_date,
			"settled_status": settled_status,
			"status": status,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict
  
### 30 mnts interval
def safegold_historical_prices_interval(get_base_url, access_token, from_date, to_date):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		params= {
			"from_date": from_date,  	###### yy - mm - dd
			"to_date": to_date 			###### yy - mm - dd
		}	


		url = f"{get_base_url}/v1/gold/historical-data"

		safeGoldResponse = requests.get(url,headers=headers,params=params)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD Historical Prices decrypted RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		pricesList=[]
		params={}
		purity=""
		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			responseStatus = 1
			message="Successfully fetched Gold Prices"
			pricesList=decrypted_response.get("data","")
			params=decrypted_response.get("params",{})
			purity=params.get("purity","")
		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message="Unable to Get Historical Prices"
		else:
			message="Unable to Get Historical Prices"
		
		safeGoldResponseDict = {
			"message": message,
			"pricesList": pricesList,
			"responseData": responseData,
			"purity": purity,
			"responseStatus": responseStatus,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict

### 
def safegold_historical_prices(get_base_url, access_token, from_date, to_date, priceFetchType):
	safeGoldResponseDict = {"responseStatus": 0, "message": ""}

	try:
		headers = {
			"Authorization": f"Bearer {access_token}",
			"Content-Type": "application/json",
			"accept": "application/json",
		}

		params= {
			"from_date": from_date,  	###### yy - mm - dd
			"to_date": to_date,
			"type": priceFetchType					###### yy - mm - dd
		}	


		url = f"{get_base_url}/v1/gold/historical"

		safeGoldResponse = requests.get(url,headers=headers,params=params)

		safeGoldResponseJson =  safeGoldResponse.text
		safeGoldResponseJson = json.loads(safeGoldResponseJson)
		encryptedResponseData = safeGoldResponseJson.get("data", "")

		# Step 6: Decrypt the response data
		decrypted_response = safegold_decrypt(encryptedResponseData, access_token)
		decrypted_response = json.loads(decrypted_response)
		print(decrypted_response, "((((SAFEGOLD Historical Prices By Time range decrypted RESPONSE))))")

		responseData = [decrypted_response]
		responseStatus=0
		pricesList=[]
		params={}
		purity=""
		if safeGoldResponse.status_code == 200 and decrypted_response != []:
			responseStatus = 1
			message="Successfully fetched Gold Prices"
			pricesList=decrypted_response.get("data","")
			params=decrypted_response.get("params",{})
			purity=params.get("purity","")
		elif safeGoldResponse.status_code == 400:
			responseStatus= 0
			message="Unable to Get Historical Prices  By Time range"
		else:
			message="Unable to Get Historical Prices By Time range"
		
		safeGoldResponseDict = {
			"message": message,
			"pricesList": pricesList,
			"responseData": responseData,
			"purity": purity,
			"responseStatus": responseStatus,
		}
		return safeGoldResponseDict

	except Exception as e:
		app.logger.error(traceback.format_exc())
		safeGoldResponseDict["responseStatus"] = 0
		safeGoldResponseDict["message"] = "Our banking partner server is down. Please try again later."
		return safeGoldResponseDict




