from rest_framework.decorators import api_view
from django.http import JsonResponse
import os,sys
import requests
import pandas as pd
from collections import defaultdict
import datetime
from requests.auth import HTTPBasicAuth
from django.http import JsonResponse
sys.path.append(os.path.join(os.path.dirname(__file__)))
import LogUtils
logger = LogUtils.getRootLogger()

base_url = 'https://scic.crm.dynamics.com'

# Azure AD Application Client ID and Secret
client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'

def get_token(client_id, client_secret, tenant_id):
    token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/token'
    
    payload = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
        'resource': base_url,
    }
    
    response = requests.post(token_url, data=payload)
    if response.status_code == 200:
        return response.json().get('access_token')
    else:
        raise Exception(f"Failed to retrieve token: {response.text}")


####################################################################

def ce_request_odata(event_registration_id):
    client_id = "6e5989aa-4fd1-4015-8648-8f75609d607b"
    client_secret = "mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS"
    tenant_id = "95f69e7d-1811-4ab9-9b5a-eba95d3eba9b"
    base_url = "https://dev.crm.dynamics.com"


    token = get_token(client_id, client_secret, tenant_id)
    
    headers = {
        "Authorization": "Bearer " + token,
        "Prefer": "odata.maxpagesize=5000",
        "OData-MaxVersion": "4.0",
        "OData-Version": "4.0",
    }
    
    ce_request_api_url = (
        base_url
        + "/api/data/v9.2/trit_cerequests"
    )
    
    

    new_record = {
        "trit_EventRegistrationId@odata.bind": f"/msevtmgt_eventregistrations({event_registration_id})"


    }
    
    Response={"status":"null"
        }
    try:
        
        # Send POST request to create a new record
        response = requests.post(ce_request_api_url, headers=headers, json=new_record)
        
        if response.status_code in [200, 201]:
            print("Record created successfully:", response.json())
            Response={"status":"Success"
                }
        elif response.status_code == 204:
            print("Record created successfully (No Content).")
            Response={"status":"failed"
                }
        else:
            print(f"Failed to create record: {response.status_code} - {response.text}")
            Response={"status":"failed"
                }
        
    except Exception as e:
        print(e)
        Response={"status":"failed"
            }

    return Response        

####################################################################

def pc(license_id,product_id,state_id):
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }

    state_approval_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_instructorapprovals?$filter=_trit_state_value eq {state_id}"

    # state_approval_api_url="https://scic.crm.dynamics.com/api/data/v9.1/trit_instructorapprovals?$top=1"

    state_approval_req=requests.get(state_approval_api_url,headers=headers)

    res=state_approval_req.json()

    data=res["value"]

    state_approval_table=pd.DataFrame(data)
    
    state_approval=state_approval_table[state_approval_table["_trit_product_value"]==product_id]
    
    PC_list = list(state_approval['trit_name'])
    
    PC_lists=[]
    for tn in PC_list:
        # print(tn)  # Print the current value for debugging
        if tn and (tn.endswith("PC") or tn.endswith("(PC)") or tn.endswith("(PC/ETH)") or tn.endswith("(PC/LAH/ETH)") or tn.endswith("(PC/LAW/REG/ETH)")  or tn.endswith("PC/LAH") or tn.endswith("(PC Webinar)") or tn.endswith("(PC/LAH/LAW/REG/ETH)") or tn.endswith("(PC/LAW/REG/ETH)") or tn.endswith("PC (Webinar)") or tn.endswith("(PC/LH)") or tn.endswith("(LH/PC)") or tn.endswith("PC/LH") or tn.endswith("LH/PC") or tn.endswith("(LH/PC/ETH)") or tn.endswith("(ETH/PC/LH)") or tn.endswith("LH/PC/ETH") or tn.endswith("ETH/PC/LH") or tn.endswith("P/C & L/H") or tn.endswith("(P/C & L/H)") or tn.endswith("(PC/LAH/ETH)") or tn.endswith("PC/LAH/ETH")): 
            PC_lists.append(tn)
        
    PH_first_value=PC_lists[0]
    return PH_first_value


def lh(license_id,product_id,state_id):
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }

    state_approval_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_instructorapprovals?$filter=_trit_state_value eq {state_id}"

    # state_approval_api_url="https://scic.crm.dynamics.com/api/data/v9.1/trit_instructorapprovals"

    state_approval_req=requests.get(state_approval_api_url,headers=headers)

    res=state_approval_req.json()

    data=res["value"]
    
    state_approval_table=pd.DataFrame(data)
    
    state_approval=state_approval_table[state_approval_table["_trit_product_value"]==product_id]
    
    LH_list = list(state_approval['trit_name'])
    
    LH_lists=[]
    for tn in LH_list:
        # print(tn)  # Print the current value for debugging
        if tn and (tn.endswith("LH") or tn.endswith("(LH)") or tn.endswith("(LH/ETH)") or tn.endswith("(PC/LH/ETH)") or tn.endswith("(PC/LH)") or tn.endswith("(LH/LAW/REG/ETH)") or tn.endswith("LH (Webinar)") or tn.endswith("(LH/PC)") or tn.endswith("PC/LH") or tn.endswith("LH/PC") or tn.endswith("(LH/PC/ETH)") or tn.endswith("(ETH/PC/LH)") or tn.endswith("LH/PC/ETH") or tn.endswith("ETH/PC/LH") or tn.endswith("P/C & L/H") or tn.endswith("(P/C & L/H)")):  
            LH_lists.append(tn)
    LH_first_value=LH_lists[0]
    return LH_first_value 

#################################################################### 


def check_poll_requirements(data):
    # Ensure there's valid data
    if data.empty or not any(data["trit_answered"]):
        print("No valid trit_name found with trit_answered as True.")
        return "no"
    
    # Structure to hold the polls by product and hour
    polls_by_product_hour = defaultdict(lambda: defaultdict(set))

    # Process the input data
    for _, row in data.iterrows():
        trit_name = row["trit_name"]
        
        # Check if trit_name contains a ':' to split
        if ':' not in trit_name:
            print(f"Invalid format, missing colon: {trit_name}")
            continue

        try:
            # Split the trit_name to extract the product and poll number
            product_hour_part = trit_name.split(':', 1)[0]  # Take the part before the ':'
            parts = product_hour_part.rsplit('-', 2)  # Split from the right to get the last two parts

            if len(parts) != 3:
                print(f"Skipping invalid format: {trit_name}")
                continue

            product_hour, poll_num = parts[:-1], parts[-1]  # Get all but the last part for product
            product = '-'.join(product_hour)  # Join to get the product base
            
            # Calculate the hour based on the poll number
            hour = (int(poll_num) - 1) // 3 + 1  # Calculate the hour based on the poll number
            
            # Add the poll to the set to avoid duplicates
            polls_by_product_hour[product][hour].add(trit_name)

        except Exception as e:
            print(f"Error processing {trit_name}: {e}")

    # Required polls per hour
    required_polls_per_hour = 2  # Change this to your requirement
    product_poll_summary = defaultdict(lambda: defaultdict(int))
    
    # Count total polls for each product and hour
    for product, hours in polls_by_product_hour.items():
        for hour in range(1, 5):  # Assuming there are 4 hours to check
            total_poll_count = len(hours[hour])
            product_poll_summary[product][hour] = total_poll_count

    # Create the summary DataFrame
    summary_records = []
    for product, hour_data in product_poll_summary.items():
        for hour in range(1, 5):  # Check for each hour
            total_polls = hour_data[hour]
            summary_records.append({
                "Product": product,
                "Hour": hour,
                "Required Polls": required_polls_per_hour,
                "Total Polls": total_polls,
                "Status": "Sufficient" if total_polls >= required_polls_per_hour else "Insufficient"
            })

    summary_df = pd.DataFrame(summary_records)

    # Check for insufficient polls
    if 'Status' in summary_df.columns:
        insufficient_polls = summary_df[summary_df["Status"] == "Insufficient"]
        if not insufficient_polls.empty:
            print("\nProducts with insufficient polls:")
            print("#####Insufficient data starts#####")  # Change this to logs
            print(insufficient_polls)  # Change this to logs
            print("#####Insufficient data ends#####")  # Change this to logs
            return "no"

    print("This product have sufficient polls for every hour.")
    return "yes"

####################################################################


def ao_am_states(trit_product,trit_license_trit_stateid_value):
    ao=pd.read_excel("/home/karthikraj/Downloads/PPP Automation/AO and AM state and statecode.xlsx",sheet_name="AO")
    am=pd.read_excel("/home/karthikraj/Downloads/PPP Automation/AO and AM state and statecode.xlsx",sheet_name="AM")   
    
    
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }

    product_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/products?$filter=productid eq {trit_product}&$select=name"
    
    response=requests.get(product_api_url,headers=headers)
    
    res=response.json()
    
    data=res['value']
    
    product=pd.DataFrame(data)
    
    try:
        if product["name"][0]=="AO":
            print("This event number is in AO states")
            for index,row in ao.iterrows():
                if row["trit_stateid"]== trit_license_trit_stateid_value:
                    trit_name=row["trit_name"]
                    print(f"AO state name is {trit_name}")
                    no_of_cerequest=row["CE request"]
                
        elif product["name"][0]=="AM":
            print("This event is in AM states")
            for index,row in am.iterrows():
                if row["trit_stateid"]== trit_license_trit_stateid_value:
                    trit_name=row["trit_name"]
                    print(f"AM state name is {trit_name}")
                    no_of_cerequest=row["CE request"]
                
                   
        else:
            print("It doesn't comes under AO or AM product")
            no_of_cerequest=1
        
        return no_of_cerequest
    
    except Exception as e:
        print(e)
        print("fails at ao_am_states function")

####################################################################

def process_pquestions(pquestions):
    data = pd.DataFrame(pquestions)
    grouped_data = data.groupby('_trit_courseassignment_value')
    
    results = {}
    for course_value, group in grouped_data:
        print(f"\nProcessing for {course_value}:")
        valid_group = group[group["trit_answered"] == True]
        result = check_poll_requirements(valid_group)
        results[course_value] = result

    for result_yn in results.values():
        if result_yn == "yes":
            print("#We can create CE request")
        elif result_yn == "no":
            print("# We can't create CERequest")
        else:
            print("Null in results")



####################################################################


# msevtmgt_eventregistration
def evenregistration(eventregistration_id):
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }

    
    msevtmgt_eventregistration_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/msevtmgt_eventregistrations?$filter=msevtmgt_eventregistrationid eq {eventregistration_id}"

    response=requests.get(msevtmgt_eventregistration_api_url,headers=headers)

    res=response.json()

    data=res['value']

    msevtmgt_eventregistration=pd.DataFrame(data)

    # msevtmgt_eventregistration columns
    msevtmgt_eventid=msevtmgt_eventregistration['_msevtmgt_eventid_value'][0]
    trit_cedeclinationreason=msevtmgt_eventregistration['trit_cedeclinationreason'][0]
    msevtmgt_contactid_value=msevtmgt_eventregistration['_msevtmgt_contactid_value'][0]
    trit_lgsstate=msevtmgt_eventregistration['trit_lgsstate'][0]
    trit_lgsrequest=msevtmgt_eventregistration['trit_lgsrequest'][0]
    msevtmgt_eventregistrationid=msevtmgt_eventregistration['msevtmgt_eventregistrationid'][0]
    
    return {'msevtmgt_eventid' : msevtmgt_eventid ,'trit_cedeclinationreason':trit_cedeclinationreason
            ,'msevtmgt_contactid_value':msevtmgt_contactid_value,'trit_lgsstate':trit_lgsstate,'trit_lgsrequest':trit_lgsrequest,'msevtmgt_eventregistrationid':msevtmgt_eventregistrationid}
    

#############################################################


def msevtmgt_event(msevtmgt_eventid):
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }


    msevtmgt_event_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/msevtmgt_events?$filter=msevtmgt_eventid eq {msevtmgt_eventid}"
    
    response=requests.get(msevtmgt_event_api_url,headers=headers)
    
    res=response.json()
    
    data=res['value']
    
    msevtmgt_event=pd.DataFrame(data)
    
    
    # msevtmgt_event columns
    
    trit_type = msevtmgt_event["trit_type"][0]
    trit_product = msevtmgt_event["_trit_product_value"][0]
    trit_deliverymechanisms= msevtmgt_event["trit_deliverymechanisms"][0]
    
    
    return {'trit_type':trit_type,'trit_product':trit_product,"trit_deliverymechanisms":trit_deliverymechanisms}



##############################


def contacts(msevtmgt_contactid_value):
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }

    contacts_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/contacts?$filter=contactid eq {msevtmgt_contactid_value}"
    
    response=requests.get(contacts_api_url,headers=headers)
    
    res=response.json()
    
    data=res['value']
    
    contacts=pd.DataFrame(data)
    
    #contacts columns
    contacts_contactid=contacts["contactid"][0]
    contacts_firstname=contacts["firstname"][0]
    contacts_lastname=contacts["lastname"][0]

    return {"contacts_contactid":contacts_contactid, "contacts_firstname":contacts_firstname, 'contacts_lastname':contacts_lastname}




##########################################


def licenses_check(contacts_contactid):
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }

    try:

        trit_license_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_licenses?$filter=_trit_contact_value eq {contacts_contactid}"

        response=requests.get(trit_license_api_url,headers=headers)

        res=response.json()

        data=res['value']

        trit_license=pd.DataFrame(data)
        print(f"licenses - {trit_license}")


        trit_license=trit_license[trit_license['statecode']==0]
        trit_license=trit_license[trit_license['trit_rlicense']==1]
        print(f"license - {trit_license}")



        if len(trit_license)==1:
            print("only one license")
            licen=1
            return licen

        elif len(trit_license)==0:
            print("No license")
            licen=0
            return licen
        elif len(trit_license)>1:
            print("leave the process there are more than one license")
            licen=2
            return licen
        #trit_license columns

    except Exception as e:
        print(e)


def licenses(contacts_contactid):
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }
    
    try:
    
        trit_license_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_licenses?$filter=_trit_contact_value eq {contacts_contactid}"
        
        response=requests.get(trit_license_api_url,headers=headers)
        
        res=response.json()
        
        data=res['value']
        
        trit_license=pd.DataFrame(data)
        trit_license_trit_contact_value=trit_license["_trit_contact_value"][0]
        trit_license_statecode=trit_license["statecode"][0]
        trit_license_trit_stateid_value=trit_license['_trit_stateid_value'][0]
        trit_license_statuscode=trit_license["statuscode"][0]
        trit_rlicense=trit_license['trit_rlicense'][0]
        trit_license_trit_lineofauthority=trit_license['trit_lineofauthority'][0]
        license_id=trit_license['trit_licenseid'][0]



        return {"trit_license_trit_contact_value":trit_license_trit_contact_value,
                "trit_license_statecode":trit_license_statecode,
                "trit_license_trit_stateid_value":trit_license_trit_stateid_value,
                "trit_license_statuscode":trit_license_statuscode,"trit_rlicense":trit_rlicense,
                "trit_license_trit_lineofauthority":trit_license_trit_lineofauthority,
                "license_id":license_id}
        
        # return trit_license
    except Exception as e:
        print(e)





#########################################################


def course_assignment(course_assignment_id,event_id):
    try:
        client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
        client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
        tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
        token = get_token(client_id, client_secret, tenant_id)
    
    
        headers = {
            'Authorization': 'Bearer ' + token,
            'Prefer': 'odata.maxpagesize=5000',
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0'
        }
    
        trit_courseassignment_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=trit_courseassignmentid eq {course_assignment_id}"
        
        
        response=requests.get(trit_courseassignment_api_url,headers=headers)
        
        res=response.json()
        
        data=res['value']
        
        trit_courseassignment=pd.DataFrame(data)
        
        # trit_courseassignment columns
        trit_courseassignment_trit_eventregistrationid_value=event_id
        trit_courseassignment_trit_percentattended=trit_courseassignment["trit_percentattended"][0]
        trit_courseassignment_trit_product_value=trit_courseassignment["_trit_product_value"][0]
        trit_courseassignment_trit_instructionhours=trit_courseassignment["trit_instructionhours"][0]

    
    
    
    
        return {"trit_courseassignment_trit_eventregistrationid_value":trit_courseassignment_trit_eventregistrationid_value,
            "trit_courseassignment_trit_percentattended":trit_courseassignment_trit_percentattended,"trit_courseassignment_trit_product_value": trit_courseassignment_trit_product_value,
            "trit_courseassignment_trit_instructionhours":trit_courseassignment_trit_instructionhours}
    except Exception as e:
        print(e)
        print("failed at course_assignment function")

############################################



def pquestions(course_assignment_id):
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }
    
    try:
        trit_pollquestions_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_pollquestions?$filter=_trit_courseassignment_value eq {course_assignment_id}"
        # trit_pollquestions_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_pollquestions?$filter=_trit_courseassignment_value eq {ids}"
        
        response=requests.get(trit_pollquestions_api_url,headers=headers)
        
        res=response.json()
        
        data=res['value']
        
        trit_pollquestions=pd.DataFrame(data)
    
    
        return {"trit_name":trit_pollquestions['trit_name'], "trit_answered":trit_pollquestions['trit_answered'],"_trit_courseassignment_value": trit_pollquestions["_trit_courseassignment_value"]}
    
    except:
        print(f"This Evenregistration {course_assignment_id} doesn't contains poll questions")
        

############################################

     

###########################################


def validate_lgs(state_id, contact_data):
    """
    Validates the designation logic based on state, designation, and contact data.

    :param state_id: The state code as a string.
    :param contact_data: The contact identifier to filter designation awards.
    :param client_id: Client ID for authentication.
    :param client_secret: Client secret for authentication.
    :param tenant_id: Tenant ID for authentication.
    :return: True if the validation conditions are met, False otherwise.
    """
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    
    try:
        # Retrieve token (ensure get_token is implemented and reliable)
        tokens = get_token(client_id, client_secret, tenant_id)
        headers = {
            'Authorization': f'Bearer {tokens}',
            'Prefer': 'odata.maxpagesize=5000',
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0'
        }

        # Fetch state data
        state_api_url = f"https://scic.crm.dynamics.com/api/data/v9.1/trit_states?$filter=trit_stateid eq '{state_id}'"
        state_response = requests.get(state_api_url, headers=headers)
        state_response.raise_for_status()
        state_data = state_response.json().get('value', [])
        if not state_data:
            return False
        state_name = state_data[0].get("trit_name")

        # Fetch designation awards
        designation_award_api_url = f"https://scic.crm.dynamics.com/api/data/v9.1/trit_designationawards?$filter=_trit_contact_value eq '{contact_data}'"
        response = requests.get(designation_award_api_url, headers=headers)
        response.raise_for_status()
        designation_data = response.json().get('value', [])

        # Validation logic
        for award in designation_data:
            award_date_str = award.get("trit_awarddate")
            designation = award.get("trit_name")
            if not (award_date_str and designation):
                continue

            award_date = datetime.datetime.strptime(award_date_str, "%Y-%m-%d")
            if (
                (state_name == "AL" and "CIC" in designation and award_date.year < 2013) or
                (state_name == "NJ" and "CIC" in designation) or
                (state_name == "NJ" and "CISR" in designation) or
                (state_name == "PR" and "CRM" in designation) or
                (state_name == "PR" and "CIC" in designation) or
                (state_name == "NV" and "CIC" in designation) or
                (state_name == "UT" and "CIC" in designation) or
                (state_name == "UT" and "CRM" in designation)
            ):
                return True

        return False

    except requests.RequestException as e:
        print(f"API request failed: {e}")
        return False
    except Exception as e:
        print(f"Unexpected error: {e}")
        return False

############################################

def fetch_poll_questions(trit_courseassignment):
    """
    Fetch poll questions for each course assignment and return a dictionary of DataFrames.

    Parameters:
        trit_courseassignment (DataFrame): DataFrame containing course assignments.
        client_id (str): Client ID for authentication.
        client_secret (str): Client Secret for authentication.
        tenant_id (str): Tenant ID for authentication.

    Returns:
        dict: A dictionary where keys are `ca_id` and values are DataFrames containing poll questions.
    """
    dataframes = {}  # Dictionary to store dataframes for each ca_id
    
    # Helper function to get the token
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    token = get_token(client_id, client_secret, tenant_id)

    for index, row in trit_courseassignment.iterrows():
        ca_id = row["trit_courseassignmentid"]
        trit_pollquestions_api_url = f"https://scic.crm.dynamics.com/api/data/v9.1/trit_pollquestions?$filter=_trit_courseassignment_value eq {ca_id}"
        
        headers = {
            'Authorization': 'Bearer ' + token,
            'Prefer': 'odata.maxpagesize=5000',
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0'
        }
        
        response = requests.get(trit_pollquestions_api_url, headers=headers)
        
        if response.status_code == 200:  # Ensure the request was successful
            res = response.json()
            data = res.get('value', [])  # Get the data, defaulting to an empty list
            
          
           # Create a new DataFrame for the current ca_id
            df = pd.DataFrame(data)
            dataframes[ca_id] = df  # Store it in the dictionary with ca_id as the key
        else:
            print(f"Failed to fetch data for ca_id: {ca_id}. Status Code: {response.status_code}")

    return dataframes


#############################################

def course_assignment_df(event_reg_id):
    '''
    This is used to retrieve all course assignments records based on event registration ID
    
    '''
    trit_courseassignment_api_url=f"https://scic.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=_trit_eventregistrationid_value eq {event_reg_id}"
    
    client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
    client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
    tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
    
    token = get_token(client_id, client_secret, tenant_id)


    headers = {
        'Authorization': 'Bearer ' + token,
        'Prefer': 'odata.maxpagesize=5000',
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0'
    }
    
    response=requests.get(trit_courseassignment_api_url,headers=headers)
    
    res=response.json()
    
    data=res['value']
    
    trit_courseassignment=pd.DataFrame(data)
    # trit_courseassignment_cols=trit_courseassignment.columns
    
    return trit_courseassignment

############################################


def process_course_assignments(test_fpq):
    """
    Process course assignments and generate a structured dictionary.

    Args:
        test_fpq (dict): A dictionary where keys are `ca_id` and values are DataFrames.
        client_id (str): Client ID for API authentication.
        client_secret (str): Client Secret for API authentication.
        tenant_id (str): Tenant ID for API authentication.

    Returns:
        dict: Processed data for all course assignments.
    """
    try:

        result_data = {}
        
        for ca_id, df in test_fpq.items():  # Iterate over dictionary items
            print(f"Processing ca_id: {ca_id}")
            
            client_id = '6e5989aa-4fd1-4015-8648-8f75609d607b'
            client_secret = 'mUv8Q~1u3JtjdAdw.ov1sRfjzTm3yS.f~cC6wcQS'
            tenant_id = '95f69e7d-1811-4ab9-9b5a-eba95d3eba9b'
            
            token = get_token(client_id, client_secret, tenant_id)
    
            headers = {
                'Authorization': 'Bearer ' + token,
                'Prefer': 'odata.maxpagesize=5000',
                'OData-MaxVersion': '4.0',
                'OData-Version': '4.0'
            }
            
            trit_courseassignment_api_url = (
                f"https://scic.crm.dynamics.com/api/data/v9.1/trit_courseassignments?$filter=trit_courseassignmentid eq {ca_id}"
            )
    
            response = requests.get(trit_courseassignment_api_url, headers=headers)
            
            res = response.json()
    
            data = res.get('value', [])
            comments_retrieval_course_assignment = pd.DataFrame(data)
            trit_admincomment = comments_retrieval_course_assignment.get('trit_admincomment', pd.Series(dtype=object))
    
            pq = {
                "trit_name": [],
                "trit_answered": [],
                "_trit_courseassignment_value": []
            }
    
            if isinstance(df, pd.DataFrame):  # Ensure the value is a DataFrame
                for _, row in df.iterrows():  # Iterate over DataFrame rows
                    pq["trit_name"].append(row['trit_name'])
                    pq["trit_answered"].append(row['trit_answered'])
                    pq["_trit_courseassignment_value"].append(row["_trit_courseassignment_value"])
    
                    if not trit_admincomment.empty:  # Check if 'trit_admincomment' is not empty
                        for i in trit_admincomment:
                            if i:  # Ensure `i` is not None or empty
                                result = i.split("-")[:3]
                                joined_data = "-".join(result) + ": question"
                                
                                pq["trit_name"].append(joined_data)
                                pq['trit_answered'].append(True)
                                pq['_trit_courseassignment_value'].append(ca_id)
    
            result_data[ca_id] = pq
    
        return result_data
    
    except Exception as e:
        print(e)

#############################################

    
def cerequest_check(eventregistration_id):    
    try:
        ce_request_created = False
        info_after_percentage_check= "No info acquired due to condition fail"
        ca_df=course_assignment_df(eventregistration_id)
        
        fpq=fetch_poll_questions(ca_df)
        
        pca=process_course_assignments(fpq)
                
        for ca_id, df in pca.items():
            print(f"Processing DataFrame for ca_id: {ca_id}")
            
            er=evenregistration(eventregistration_id)
            msevtmgt_contactid_value = er["msevtmgt_contactid_value"]
            cont = contacts(msevtmgt_contactid_value)
            ca = course_assignment(ca_id,eventregistration_id)

        
            if ca['trit_courseassignment_trit_percentattended'] is not None:
                percentage_check=ca['trit_courseassignment_trit_percentattended']
                print(f"In courseassignment attendance percentage value present and it is {percentage_check} ")
                contacts_contactid = cont["contacts_contactid"]
                print(f"contactID - {contacts_contactid}")
                print(contacts_contactid)
                lic_check=licenses_check(contacts_contactid)
                try:
                    lic = licenses(contacts_contactid)   
                    trit_license_trit_licensetype=lic.get('trit_license_trit_licensetype')
                    print(f"License type - {trit_license_trit_licensetype}")
                    trit_rlicense=lic.get("trit_rlicense")
                    print(f"Resident License {trit_rlicense}")
                    trit_license_trit_lgs=lic.get("trit_license_trit_lgs")
                    print(f"LGS code - {trit_license_trit_lgs}")
                    trit_license_trit_stateid_value=lic.get('trit_license_trit_stateid_value')
                    print(f"State id - {trit_license_trit_stateid_value}")
                    trit_license_trit_lineofauthority=lic.get("trit_license_trit_lineofauthority")
                    license_id=lic.get("license_id")
                except:
                    print("no license or more than one license")
                if lic_check==1:
                    print("one License")
                    er=evenregistration(eventregistration_id)
                    msevtmgt_eventid=er['msevtmgt_eventid']
                    ev = msevtmgt_event(msevtmgt_eventid)
                    delivery_mechanism=ev["trit_deliverymechanisms"]
                    dm=er['trit_cedeclinationreason']
                    t_type=ev['trit_type']
                    print(f"Trit_type - {t_type}")
                    print(f"Event ID - {msevtmgt_eventid}")
                    print(f"Delivery method - {delivery_mechanism}")
                    print(f"Declination reason - {dm}")
                    print(f"Event Registration id - {eventregistration_id}")
                    if trit_rlicense==1:
                        print("it is a resident license")
                    
                        if ev['trit_type'] == 314310000 and er['trit_cedeclinationreason'] not in ["314310000","314310001","314310002"] and delivery_mechanism==314310001:
                            print(f"This {eventregistration_id} satisfied trit_type as SS & trit_cedeclinationreason is None and {delivery_mechanism}")
                            contacts_contactid = cont["contacts_contactid"]
                            try:
                                lic = licenses(contacts_contactid) 
                                trit_license_trit_licensetype=lic['trit_license_trit_licensetype']
                                trit_license_trit_lgs=lic["trit_license_trit_lgs"]
                                trit_license_trit_stateid_value=lic['trit_license_trit_stateid_value']
                            except:
                                print("no license or more than one license")
                            
                            if lic['trit_license_statecode'] == 0:
                                print(f"This {eventregistration_id} have only one license")
                                contacts_contactid = cont["contacts_contactid"]
                                try:
                                    lic = licenses(contacts_contactid)   
                                    trit_license_trit_licensetype=lic['trit_license_trit_licensetype']
                                    trit_license_trit_lgs=lic["trit_license_trit_lgs"]
                                    trit_license_trit_stateid_value=lic['trit_license_trit_stateid_value']
                                except:
                                    print("no license or more than one license")
                                
                                if lic['trit_license_trit_stateid_value'] is not None:
                                    print(f"This {eventregistration_id} have stateid value")
                                    
                                    contacts_contactid = cont["contacts_contactid"]
                                    try:
                                        lic = licenses(contacts_contactid)   
                                        trit_license_trit_stateid_value=lic['trit_license_trit_stateid_value']
                                        state_id = trit_license_trit_stateid_value
                                        contact_data= contacts_contactid
                                        val_LGS = validate_lgs(state_id, contact_data)
                                        print(f"LGS Validated - {val_LGS}")
                                    except:
                                        print("no license or more than one license")
                                    
                                    
        
                                    if val_LGS == False:
                                        print(f" This {eventregistration_id}'s State comes under Non-LGS states")
                                        
                                        specified_states = {'9544192b-a600-ea11-a827-000d3a1cac04', 
                                                            '881d0c2a-a600-ea11-a825-000d3a1cadb6', 
                                                            '861d0c2a-a600-ea11-a825-000d3a1cadb6', 
                                                            '33805427-a600-ea11-a826-000d3a1ca610'}
                                        
                                        State_Code=[                                        
                                            '8b44192b-a600-ea11-a827-000d3a1cac04',
                                            'd21d0c2a-a600-ea11-a825-000d3a1cadb6',
                                            'cb1d0c2a-a600-ea11-a825-000d3a1cadb6',
                                            'c91d0c2a-a600-ea11-a825-000d3a1cadb6',
                                            'ab1d0c2a-a600-ea11-a825-000d3a1cadb6',                                                                          
                                            '7c1d0c2a-a600-ea11-a825-000d3a1cadb6',
                                            '40805427-a600-ea11-a826-000d3a1ca610',
                                            '3c805427-a600-ea11-a826-000d3a1ca610',                                       
                                        ]
                                        
                                        ce_request_created = False
                                        
                                        ca = course_assignment(ca_id,eventregistration_id)
                                        # cer = cerequest(eventregistration_id) 
                                        # pquestions_list = pquestions(course_assignment_id)
                                        trit_product = ev['trit_product']
                    
                                        info_before_percentage_check={"Eventregistration_id":eventregistration_id,
                                              "Event_ID":msevtmgt_eventid,
                                              "License_type":trit_license_trit_licensetype,
                                              "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                              "Delivery_method":delivery_mechanism,
                                              "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                              "LGS":val_LGS,"Product_ID":trit_product}
                                        
                                        if state_id == '7c1d0c2a-a600-ea11-a825-000d3a1cadb6' and ca["trit_courseassignment_trit_percentattended"] >= 70:
                                                print(f"# Check for AO&AM products - based on percentage 1 {ca['trit_courseassignment_trit_percentattended']}")
                                                no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                print(f"no of ce requests {no_of_cerequest}")
                                                ce_request_created = True
                                                if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                    print("P/C")
                                                    license_id=lic.get("trit_licenseid")
                                                    
                                                    LOA = pc(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                    print("L/H")
                                                    LOA = lh(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                    print("P/C & L/H")
                                                    try:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    except:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                else:
                                                    print("Null")
                                                    LOA = "Null"
                                                info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                      "Event_ID":msevtmgt_eventid,
                                                      "License_type":trit_license_trit_licensetype,
                                                      "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                      "Delivery_method":delivery_mechanism,
                                                      "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                      "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                      "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                
                                                return (no_of_cerequest,ce_request_created,eventregistration_id)
                                        
                                        elif state_id in {"8b44192b-a600-ea11-a827-000d3a1cac04", "3c805427-a600-ea11-a826-000d3a1ca610"} and ca["trit_courseassignment_trit_percentattended"] >= 85:
                                                print(f"# Check for AO&AM products - based on percentage 2 {ca['trit_courseassignment_trit_percentattended']}")
                                                no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                print(f"no of ce requests {no_of_cerequest}")
                                                ce_request_created = True
                                                if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                    print("P/C")
                                                    license_id=lic.get("trit_licenseid")
                                                    
                                                    LOA = pc(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                    print("L/H")
                                                    LOA = lh(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                    print("P/C & L/H")
                                                    try:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    except:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                else:
                                                    print("Null")
                                                    LOA = "Null"
                                                info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                      "Event_ID":msevtmgt_eventid,
                                                      "License_type":trit_license_trit_licensetype,
                                                      "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                      "Delivery_method":delivery_mechanism,
                                                      "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                      "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                      "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                
                                                return (no_of_cerequest,ce_request_created,eventregistration_id)
                                            
                                        elif state_id in {"40805427-a600-ea11-a826-000d3a1ca610", "ab1d0c2a-a600-ea11-a825-000d3a1cadb6"} and ca["trit_courseassignment_trit_percentattended"] >= 90:
                                                print(f"# Check for AO&AM products - based on percentage 3 {ca['trit_courseassignment_trit_percentattended']}")
                                                no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                print(f"no of ce requests {no_of_cerequest}")
                                                ce_request_created = True
                                                if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                    print("P/C")
                                                    license_id=lic.get("trit_licenseid")
                                                    
                                                    LOA = pc(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                    print("L/H")
                                                    LOA = lh(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                    print("P/C & L/H")
                                                    try:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    except:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                else:
                                                    print("Null")
                                                    LOA = "Null"
                                                info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                      "Event_ID":msevtmgt_eventid,
                                                      "License_type":trit_license_trit_licensetype,
                                                      "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                      "Delivery_method":delivery_mechanism,
                                                      "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                      "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                      "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                return (no_of_cerequest,ce_request_created,eventregistration_id)
                                            
                                        elif state_id in {"d21d0c2a-a600-ea11-a825-000d3a1cadb6", "cb1d0c2a-a600-ea11-a825-000d3a1cadb6", "c91d0c2a-a600-ea11-a825-000d3a1cadb6"} and ca["trit_courseassignment_trit_percentattended"] == 100:
                                                print(f"# Check for AO&AM products - based on percentage 4 {ca['trit_courseassignment_trit_percentattended']}")
                                                no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                print(f"no of ce requests {no_of_cerequest}")
                                                ce_request_created = True
                                                if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                    print("P/C")
                                                    license_id=lic.get("trit_licenseid")
                                                    
                                                    LOA = pc(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                    print("L/H")
                                                    LOA = lh(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                    print("P/C & L/H")
                                                    try:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    except:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                else:
                                                    print("Null")
                                                    LOA = "Null"
                                                if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                    print("P/C")
                                                    license_id=lic.get("trit_licenseid")
                                                    
                                                    LOA = pc(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                    print("L/H")
                                                    LOA = lh(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                    print("P/C & L/H")
                                                    try:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    except:
                                                        LOA = pc(license_id,trit_product,state_id)
                                                else:
                                                    print("Null")
                                                    LOA = "Null"
                                                info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                      "Event_ID":msevtmgt_eventid,
                                                      "License_type":trit_license_trit_licensetype,
                                                      "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                      "Delivery_method":delivery_mechanism,
                                                      "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                      "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                      "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                return (no_of_cerequest,ce_request_created,eventregistration_id)
                                            
                                        elif state_id not in State_Code or specified_states and ca["trit_courseassignment_trit_percentattended"] >= 80:
                                                print(f"# Check for AO&AM products - based on percentage 5 {ca['trit_courseassignment_trit_percentattended']}")
                                                no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                print(f"no of ce requests {no_of_cerequest}")
                                                ce_request_created = True   
                                                if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                    print("P/C")
                                                    license_id=lic.get("trit_licenseid")
                                                    
                                                    LOA = pc(license_id,trit_product,state_id)
                                                elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                    print("L/H")
                                                    license_id=lic.get("trit_licenseid")
                                                    LOA = lh(license_id,trit_product,state_id)
                                                
                                                elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                    print("P/C & L/H")
                                                    try:
                                                        license_id=lic.get("trit_licenseid")
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    except:
                                                        license_id=lic.get("trit_licenseid")
                                                        LOA = pc(license_id,trit_product,state_id)
                                                else:
                                                    print("Null")
                                                    LOA = "Null"
                                                info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                      "Event_ID":msevtmgt_eventid,
                                                      "License_type":trit_license_trit_licensetype,
                                                      "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                      "Delivery_method":delivery_mechanism,
                                                      "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                      "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                      "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                return (no_of_cerequest,ce_request_created,eventregistration_id)
                                                
                                        elif state_id in specified_states:
                                                attendance_thresholds = {
                                                16: 98,  # 98% for 16 hours
                                                7:  95,  # 95% for 7 hours
                                                4:  92,  # 92% for 4 hours
                                                3:  89,  # 89% for 3 hours
                                                2:  83,  # 83% for 2 hours
                                                1:  67   # 67% for 1 hour
                                                }
                                            
                                                # Get the instruction hours and corresponding attendance threshold
                                                instruction_hours = ca["trit_courseassignment_trit_instructionhours"]
                                                required_percentage = attendance_thresholds.get(instruction_hours)
                                                
                                                if required_percentage:
                                                    if ca["trit_courseassignment_trit_percentattended"] >= required_percentage:
                                                        print(f"# Attendance meets the threshold of {required_percentage}% for {instruction_hours} hours.")
                                                        no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                        print(f"Number of CE requests: {no_of_cerequest}")
                                                        ce_request_created = True
                                                        if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                            print("P/C")
                                                            license_id=lic.get("trit_licenseid")
                                                            
                                                            LOA = pc(license_id,trit_product,state_id)
                                                        elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                            print("L/H")
                                                            license_id=lic.get("trit_licenseid")
                                                            LOA = lh(license_id,trit_product,state_id)
                                                        
                                                        elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                            print("P/C & L/H")
                                                            try:
                                                                license_id=lic.get("trit_licenseid")
                                                                LOA = pc(license_id,trit_product,state_id)
                                                            except:
                                                                license_id=lic.get("trit_licenseid")
                                                                LOA = pc(license_id,trit_product,state_id)
                                                        else:
                                                            print("Null")
                                                            LOA = "Null"
                                                        info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                              "Event_ID":msevtmgt_eventid,
                                                              "License_type":trit_license_trit_licensetype,
                                                              "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                              "Delivery_method":delivery_mechanism,
                                                              "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                              "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                              "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                        return (no_of_cerequest,ce_request_created,eventregistration_id)
                                                    else:
                                                        print(f"# Attendance does NOT meet the required {required_percentage}% for {instruction_hours} hours.")
                                                        # Optionally, handle the case where attendance doesn't meet the threshold.
                                                        print(ce_request_created)    
                                                elif not ce_request_created and df:
                                                    # Process polls only for these states if percentage criteria fails
                                                    process_pquestions(df)
                                                    print("# Created cerequest based on polls for specified state")
                                                    no_of_cerequest = ao_am_states(trit_product, lic['trit_license_trit_stateid_value'])
                                                    print(f"no of ce requests {no_of_cerequest}")
                                                    ce_request_created = True
                                                    if lic.get("trit_license_trit_lineofauthority") == 314310000:
                                                        print("P/C")
                                                        license_id=lic.get("trit_licenseid")
                                                        
                                                        LOA = pc(license_id,trit_product,state_id)
                                                    elif lic.get("trit_license_trit_lineofauthority")   == 314310001:
                                                        print("L/H")
                                                        license_id=lic.get("trit_licenseid")
                                                        LOA = lh(license_id,trit_product,state_id)
                                                    
                                                    elif lic.get("trit_license_trit_lineofauthority") == 314310002:
                                                        print("P/C & L/H")
                                                        try:
                                                            license_id=lic.get("trit_licenseid")
                                                            LOA = pc(license_id,trit_product,state_id)
                                                        except:
                                                            license_id=lic.get("trit_licenseid")
                                                            LOA = pc(license_id,trit_product,state_id)
                                                    else:
                                                        print("Null")
                                                        LOA = "Null"
                                                    info_after_percentage_check={"Eventregistration_id":eventregistration_id,
                                                          "Event_ID":msevtmgt_eventid,
                                                          "License_type":trit_license_trit_licensetype,
                                                          "Contact_ID":msevtmgt_contactid_value,"State_ID":trit_license_trit_stateid_value,
                                                          "Delivery_method":delivery_mechanism,
                                                          "SS_type_314310000":t_type,"Course_Assignment_ID":ca_id,
                                                          "LGS":val_LGS,"Product_ID":trit_product,"ce_request_created":ce_request_created,
                                                          "No of CE Request":no_of_cerequest,"Line_of_Authority":LOA}
                                                    return (no_of_cerequest,ce_request_created,eventregistration_id)
                                                    
                                                else:
                                                    print("Ce request declined with both attendance percentage and poll count conditions failing ")
                                                    print(ce_request_created)

                                                
                                        else:
                                            print("Ce request declined due to attendance percentage in Non-LGS")
                                            print(ce_request_created)
                                        
                                    elif val_LGS == True:
                                        print("it is LGS state")
                                           
                            
                                else:
                                    print("failed at trit_license_trit_residentstate is none")  
                                    print(ce_request_created)
                            else:
                                print("trit_license_statecode either have no license or multiple license")    
                                print(ce_request_created)
                                
                        else:    
        
                            print("It failed trit_type==314310000 or trit_cedeclinationreason is None or delivery method is not webinar")
                            print(ce_request_created)
                    else:
                        print("it is a non-resident license")        
                        print(ce_request_created)
                elif lic_check>1:
                    print("More than one license so CE requests can not be created")
                    
                    
                    print(ce_request_created)
                elif lic_check==0:
                    print("No License")
            else:
                print("Attendance percentage is none so no CE request can be created escaped in the first condition itself")
                print(ce_request_created)
                
        return (no_of_cerequest,ce_request_created,eventregistration_id)  
     
    except Exception as e:
        print(e)  


def ce_request_last_check(eventregistration_id):
    try:
        ce = cerequest_check(eventregistration_id)  # Call the cerequest_check function
        # Handle if ce is None
        if ce is None:
            print("Cannot create CE request: cerequest_check returned None")
            return {"CE_Request": None, "No_of_CE_Request": None, "Event_registration_id": None}
        # Check the ce tuple and handle accordingly
        if ce[1] == True:
            print("Create CE request")
            dicts = {"CE_Request": ce[1], "No_of_CE_Request": ce[0], "Event_registration_id": ce[2]}
            print(dicts)
            return {"response":"Success - CE Request created"}
        elif ce[1] == False:
            print("Cannot create CE request")
            dicts = {"CE_Request": ce[1], "No_of_CE_Request": ce[0], "Event_registration_id": ce[2]}
            print(dicts)
            return {"response":"No CE Request is created"}
        else:
            print("Cannot create CE request")
            dicts = {"CE_Request": None, "No_of_CE_Request": None, "Event_registration_id": ce[2] if len(ce) > 2 else None}
            print(dicts)
            return {"response":"No CE Request is created"}
    except Exception as e:
        return e

@api_view(['POST'])
def index(request):
    try:
        if request.method == "POST":
            eventregistration_id = request.data.get('eventreg_id')
            ce=ce_request_last_check(eventregistration_id)            
            return JsonResponse({"response": ce})
    except Exception as e:
        print(e)
        return JsonResponse({"error": str(e)}, status=500)