from patch.include import *
from tqdm import tqdm

@app_context(commit=True)
def patch():
    from ast import literal_eval
    import re
    import bs4
    processed = {}
    logs = []
    with open('/var/log/crm-uwsgi.log', 'r') as f:
        for row in f:
            if 'update_text_inline_comments' in row:
                # print(row)
                logs.append(row)
    logs.reverse()
    for comment in tqdm(models.CmfComment.list(filter=[['inline', '==', True], ['parent', '!=', None]], fields=['parent.text, parent.text_draft'])):
        tag = None
        if comment.parent.is_null or processed.get(comment.parent.code.value):
            continue
        processed[comment.parent.code.value] = None
        if comment.id.value not in comment.parent.text.value and comment.id.value not in comment.parent.text_draft.value:
            print(comment.parent)
            print(comment.id)
            # history = models.CmfDocumentHistory.get(filter=[['parent', '!=', comment.parent.value], ['text', 'LIKE', f'%{comment.id.value}%']],
            #                                 order_by=['-cmf_created_at'], fields=['text', 'parent'])
            # if history:
            #     processed[comment.parent.code.value] = history
            #     # print(f"history={history}")
            # else:
            #     _filter=['OR', ['text', 'LIKE',f'%{comment.id.value}%'], ['text_draft', 'LIKE',f'%{comment.id.value}%']]
            #     processed[comment.parent.code.value] = models.CmfDocument.get(filter=_filter)
            for row in logs:
                if comment.id.value in row:
                    res = re.search(r"{.*}", row)
                    res_dict = literal_eval(res[0])
                    soup = bs4.BeautifulSoup(res_dict['kwargs']['in_text'])
                    tag = soup.find(attrs={'id': comment.id.value})
                    print(tag)
                    comment.parent.text_draft.value = res_dict['kwargs']['in_text']
                    comment.parent.save()
                    break
                
            
    print(processed)
    


if __name__ == "__main__":
    patch()
