import config
from exceptions.custom_exceptions import CustomExceptions
import logging
import requests
import json
from utils.hashing import hashids


def no_touch_callckyc(pan_number, dob, random_id, application_id):
        url = config.CF_ENDPOINT + '/api/ckyc/fetch'
        headers = {
            "X-Client-Id": config.CLIENT_ID,
            "X-Client-Secret": config.CLIENT_SECRET
        }
        try:
            payload = {"pan": pan_number, "dob": dob, "id": random_id, "appId": application_id}
            responses = requests.request("POST", url, headers=headers, data=payload)
            response = responses.json()
            logging.info(response)
            if response["status"] == "OK" and response["data"] and response["data"]["response"] and response["data"]["response"]["data"] and response["data"]["response"]["data"]["kycStatus"] == "SUCCESS":
                personal_details = response["data"]["response"]["data"]["kycResult"]["personalIdentifiableData"]["personalDetails"]
                extracted_response = {
                    "status": response["status"],
                    "message": "Data fetched",
                    "kycStatus": response["data"]["response"]["data"]["kycStatus"],
                    "data": {
                        "first_name":
                            personal_details.get("firstName", ''),
                        "middle_name":
                            personal_details.get("middleName", ''),
                        "last_name":
                            personal_details.get("lastName", ''),
                        "full_name": personal_details.get("firstName", '') + ' ' +
                            personal_details.get("middleName", '') + ' ' +
                            personal_details.get("lastName", ''),
                        "email":
                            personal_details.get("email"),
                        "perm_address_line_1":
                            personal_details.get("permLine1", '') + ' ' +
                            personal_details.get("permLine2", '') + ' ' +
                            personal_details.get("permLine3", ''),
                        "address_line_1":
                            personal_details.get("permLine1", ''),
                        "address_line_2":
                            personal_details.get("permLine2", ''),
                        "address_line_3":
                            personal_details.get("permLine3", ''),
                        "perm_address_city":
                            personal_details.get("permCity"),
                        "perm_address_state":
                            personal_details.get("permState", ''),
                        "pincode": personal_details.get("permPin"),
                        "current_address_line_1":
                            personal_details.get("corresLine1", '') + ' ' +
                            personal_details.get("corresLine2", '') + ' ' + personal_details.get("corresLine3", ''),
                        "current_address_city":
                            personal_details.get("corresCity"),
                        "current_address_state":
                            personal_details.get("corresState", ''),
                        "current_pincode": personal_details.get("corresPin"),
                        "pan_number":
                            personal_details.get("pan"),
                        "dob": dob,
                        "gender":
                            personal_details.get("gender"),
                    }
                }
            else:
                extracted_response = {
                    "status": "FAIL",
                    "message": "error",
                    "kycStatus": "FAIL"
                }
            return extracted_response
        except Exception as ex:
            logging.info("Call ckyc error")
            raise CustomExceptions(f"{ex}")


def callckyc(pan_number, dob, random_id, mobile):
    url = config.CF_ENDPOINT + '/api/ckyc/fetch'
    headers = {
        "X-Client-Id": config.CLIENT_ID,
        "X-Client-Secret": config.CLIENT_SECRET
    }
    try:
        payload = {"pan": pan_number, "dob": dob, "id": random_id}
        responses = requests.request("POST", url, headers=headers, data=payload)
        response = responses.json()
        logging.info(response)
        if response["status"] == "OK" and response["data"] and response["data"]["response"] and \
                response["data"]["response"]["data"] and response["data"]["response"]["data"]["kycStatus"] == "SUCCESS":
            personal_details = response["data"]["response"]["data"]["kycResult"]["personalIdentifiableData"][
                "personalDetails"]
            extracted_response = {
                "status": response["status"],
                "message": "Data fetched",
                "kycStatus": response["data"]["response"]["data"]["kycStatus"],
                "data": {
                    "first_name":
                        personal_details.get("firstName", ''),
                    "middle_name":
                        personal_details.get("middleName", ''),
                    "last_name":
                        personal_details.get("lastName", ''),
                    "full_name": personal_details.get("firstName", '') + ' ' +
                                 personal_details.get("middleName", '') + ' ' +
                                 personal_details.get("lastName", ''),
                    "mobile_number": mobile,
                    "email":
                        personal_details.get("email"),
                    "perm_address_line_1":
                        personal_details.get("permLine1", '') + ' ' +
                        personal_details.get("permLine2", '') + ' ' +
                        personal_details.get("permLine3", ''),
                    "address_line_1":
                        personal_details.get("permLine1", ''),
                    "address_line_2":
                        personal_details.get("permLine2", ''),
                    "address_line_3":
                        personal_details.get("permLine3", ''),
                    "perm_address_city":
                        personal_details.get("permCity"),
                    "perm_address_state":
                        personal_details.get("permState", ''),
                    "pincode": personal_details.get("permPin"),
                    "current_address_line_1":
                        personal_details.get("corresLine1", '') + ' ' +
                        personal_details.get("corresLine2", '') + ' ' + personal_details.get("corresLine3", ''),
                    "current_address_city":
                        personal_details.get("corresCity"),
                    "current_address_state":
                        personal_details.get("corresState", ''),
                    "current_pincode": personal_details.get("corresPin"),
                    "pan_number":
                        personal_details.get("pan"),
                    "dob": dob,
                    "gender":
                        personal_details.get("gender"),
                }
            }
        else:
            extracted_response = {
                "status": "FAIL",
                "message": "error",
                "kycStatus": "FAIL"
            }
        return extracted_response
    except Exception as ex:
        logging.info("Call ckyc error")
        raise CustomExceptions(f"{ex}")


def fetch_bureau(application_id, applicant_type, first_name, last_name, pan, dob, mobile_number,
                 address_street, address_city, address_state, address_pincode, loan_amount):
    try:
        data = {
            "application_id": str(application_id),
            "applicant_type": applicant_type,
            "request_type": "customer",
            "first_name": first_name,
            "last_name": last_name,
            "pan_card": pan,
            "document_type": "PAN-Detailed",
            "consent": "Y",
            "mobile_number": mobile_number,
            "gender": "1",
            "dob": dob,
            "address": address_street,
            "state": address_state,
            "city": address_city,
            "postal_code": address_pincode,
            "loan_amount": loan_amount,
            "vendor": "partner link"
        }

        headers = {
                    "Content-Type": "application/json",
                    "X-Client-Id": config.CLIENT_ID,
                    "X-Client-Secret": config.CLIENT_SECRET
                }

        response = requests.post(url=config.BUREAU_ENDPOINT + '/api/get-bureau-response', data=json.dumps(data), headers=headers)
        return response
    except Exception as ex:
        return True


def electricity_bill(application_id, customer_id, provider, district, mobile_number):
    try:
        data = {
            "application_id": str(application_id),
            "customer_id": customer_id,
            "provider": provider,
            "district": district,
            "mobile_number": mobile_number
        }

        headers = {
            "Content-Type": "application/json",
            "X-Client-Id": config.CLIENT_ID,
            "X-Client-Secret": config.CLIENT_SECRET
        }

        response = requests.post(url=config.CF_ENDPOINT + '/api/electricity-bill-details', data=json.dumps(data),
                                 headers=headers)
        return json.loads(response.text)
    except Exception as ex:
        return {'message': 'Failed to validate utility bill'}
    

def run_auto_decision(application_id):
    try:
        url = config.CF_ENDPOINT + '/api/run-auto-decision'
        encoded_app_id = hashids.encode(application_id)  
  
        params = {
            'application_id': encoded_app_id,
        }
        headers = {
            "X-Client-Id": config.CLIENT_ID,
            "X-Client-Secret": config.CLIENT_SECRET
        }

        response = requests.get(url, params=params, headers=headers)
        logging.info(response)
        
        return json.loads(response.text)
        
    except Exception as ex:
        return {'message': 'Failed to run auto decision'}


def get_offers(application_id):
    try:
        url = config.EMI_CHECKOUT_BE_ENDPOINT + '/v1/loan_offer/applicable'
        encoded_app_id = hashids.encode(application_id)
        params = {
            'application_id': encoded_app_id,
        }
        headers = {
            "X-Client-Id": config.CLIENT_ID,
            "X-Client-Secret": config.CLIENT_SECRET
        }

        response = requests.get(url, params = params,
                                 headers=headers)
        logging.info(response)
        return json.loads(response.text)

    except Exception as ex:
        return {'message': 'Failed to run get offers'}


def epf_call_cf(company_name,consumer_name,mobile,email,application_id):
    try:
        data = {"employerName": company_name, "employeeName": consumer_name,
                "emp_mobile":mobile,"emp_email":email,"id":application_id, "type":1}

        headers = {
            "Content-Type": "application/json",
            "X-Client-Id": config.CLIENT_ID,
            "X-Client-Secret": config.CLIENT_SECRET
        }

        response = requests.post(url=config.CF_ENDPOINT + '/api/employment-verification', data=json.dumps(data),
                                 headers=headers)
        logging.info(response.text)
        return response
    except Exception as ex:
        return True


def account_aggregator(application_id, redirect_url):
    try:
        hashed_id = hashids.encode(application_id)
        data = {"application_id": hashed_id, "redirect_url": redirect_url}

        headers = {
            "Content-Type": "application/json",
            "X-Client-Id": config.CLIENT_ID,
            "X-Client-Secret": config.CLIENT_SECRET
        }

        response = requests.post(url=config.CF_ENDPOINT + '/api/get-account-aggregator-link', data=json.dumps(data),
                                 headers=headers)
        # logging.info(response.text)
        return (response.status_code,
                response.json())
    except Exception as ex:
        return True


def cf_sign_agreement(application_id, load_time, click_time):
    try:
        if application_id:
            hashed_id = hashids.encode(int(application_id))
            data = {"application_id": hashed_id, "load_time": load_time, "click_time": click_time}

            headers = {
                "Content-Type": "application/json",
                "X-Client-Id": config.CLIENT_ID,
                "X-Client-Secret": config.CLIENT_SECRET
            }

            response = requests.post(url=config.CF_ENDPOINT + '/api/sign-agreement', data=json.dumps(data),
                                     headers=headers)
            return (response.status_code,
                    response.json())
        return None, {}
    except Exception as ex:
        return True
