import numpy as np
from ling_features import non_answers, get_regexes_df
from nltk import sent_tokenize

statusFile = rf'../logs/process_text.txt'

# Sample text:
text = 'We finished this quarter above expectations and plan to meet EPS goals for next quarter. We do not provide specifics regarding revenue.'
#text=""
#text=None

# Function setup for GLZ classification
regexes = get_regexes_df()
        
def non_answer_calc(text):
    def get_regex_ids(data):
        if data:
            regex_ids = [ eval(item)['regex_id'] for item in data]
            return [regexes['category'][i] for i in regex_ids]
        else:
            return None
    
    def is_non_answer(data, types = ['REFUSE', 'UNABLE', 'AFTERCALL']):
        if data:
            return len(set(types).intersection(data)) > 0
        else:
            return False
            
    if text != '': 
        sents = sent_tokenize(text)
        no_ans = non_answers(sents)
        non_ans_types = get_regex_ids(no_ans)
        refuse =  is_non_answer(non_ans_types, types = ['REFUSE'])
        unable =  is_non_answer(non_ans_types, types = ['UNABLE'])
        aftercall =  is_non_answer(non_ans_types, types = ['AFTERCALL'])
        nonanswer = any([refuse,unable,aftercall])
        return dict({'nonanswer':nonanswer,'refuse':refuse,'unable':unable,'aftercall':aftercall})
    else:
        return dict({'nonanswer':'','refuse':"",'unable':"",'aftercall':""})

def process_answers(text):
    try:
        if text != '' and text != None:
            d = dict(non_answer_calc(text))
            d = {k:v*1 for (k,v) in d.items()}
        else:
            d = dict({'nonanswer':np.nan,'refuse':np.nan,'unable':np.nan,'aftercall':np.nan})
        return d
    except Exception as e:
        with open(statusFile,'a') as f_out:
            f_out.write('Error type: {}.\nError: {}.\nText is of type {}.\n----------\n'.format(type(e),e,type(text)))
        print('Error type: {}.\nError: {}.\nText is of type {}.\n-------\n'.format(type(e),e,type(text)))
        d = dict({'nonanswer':np.nan,'refuse':np.nan,'unable':np.nan,'aftercall':np.nan})
        return d

if __name__ == '__main__':
    a=process_answers(text)
    print(a,'\n')
