# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import ChatMessage
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from datetime import timedelta,datetime,timezone
from time import time
from langchain.chat_models import ChatOpenAI
import os,sys
from langchain_community.vectorstores import FAISS

# import uuid
from langchain_core.messages import (
    BaseMessage,
    message_to_dict,
    messages_from_dict,
)
from glob import glob
from langchain.prompts import PromptTemplate
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import ElasticsearchStore
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain.memory import ConversationBufferWindowMemory
from langchain_core.messages.human import HumanMessage
from langchain_core.messages.ai import AIMessage
import requests
from requests.auth import HTTPBasicAuth
from elasticsearch import Elasticsearch
from collections import OrderedDict
from decouple import config
from openai import OpenAI

sys.path.append(os.path.join(os.path.dirname(__file__)))
from index_attached import start_indexing
from Image_attached import Image_indexing
from langchain.retrievers import EnsembleRetriever

import LogUtils
logger = LogUtils.getRootLogger()

def chatbot(request):
    return render(request, 'index.html')

# Define the search query
def get_messages_by_user_and_session(username):
    query = {
       "query": {
           "bool": {
               "must": [
                   {"match": {"username": username}},
               ]
           }
       },
       "size": 5000,
       "sort": [
           {"lastmodified_at": {"order": "asc"}}
       ]
    }

    # Execute the search query
    response = es.search(index=es_index_name, body=query)

    # Extract and return the messages
    messages = [hit['_source'] for hit in response['hits']['hits']]
    return messages


class Document:
    def __init__(self, page_content, metadata):
        self.page_content = page_content  # Expecting a plain string
        self.metadata = metadata

    def __repr__(self):
        # Display page_content as plain text
        return (f"Document(page_content={self.page_content}, "
                f"metadata={self.metadata})")
    
    
def get_faiss_index_doc(index_name,session_id):
# Example usage
    search_body = {
        "query": {
            "match": {
                "metadata.session_id": session_id
            }
        }
    }
    
    response = es.search(index=index_name, body=search_body)
    sourcedata=[]
    updocuments=[]
    page_con=[]
    # Create Document objects from search results
    for hit in response['hits']['hits']:
        source = hit['_source']
        text = source.get('text', '')  # Adjust 'text' to the actual field name
        content=json.loads(text)
        metadata = source.get('metadata', {})  # Adjust 'metadata' if needed
        updocuments.append("'"+content['text']+"'")
        sourcedata.append(metadata)
        page_con.append(Document(page_content="'"+content['text']+"'", metadata=metadata))

    return updocuments,sourcedata,page_con

os.environ["OPENAI_API_KEY"] = config('SECRET_KEY')
embeddings = OpenAIEmbeddings()
es_index_name ='allibot_v2_gpt'
chatname_index='get_chatid'
# logger.info(es_index_name)
es= Elasticsearch('https://elastic:8oKIqy312EBsAPzWT64NUzji@scic-elasticsearch.es.us-central1.gcp.cloud.es.io:443',request_timeout=300,retry_on_timeout=True)

def check_elastic_status():
    basic = HTTPBasicAuth('elastic', '8oKIqy312EBsAPzWT64NUzji')
    response=requests.get('https://scic-elasticsearch.es.us-central1.gcp.cloud.es.io', auth=basic)
    if response.status_code == 200:
        return True
    else:
        return False

try :
    db = ElasticsearchStore(
        es_connection=es,
        index_name=['docx_new_page','pdf_new_page','additional_commercial_forms','docx_pdf_page','botcoach_index','html_unstructured1','excel_json_ind','pdf_json_ind'],
        #index_name=['cml_study_guide', 'docx_pdf', 'new_pdf', 'pl_pilot_24_02_21_lg','botcoach_index','mcq','pdf_test','docx_test','excel_test','csv_test','xlsx','word_docx','pdf_docs','html_unstructured1'],
        embedding=embeddings,
        strategy=ElasticsearchStore.ExactRetrievalStrategy()
    )
except Exception as ex:        
    logger.exception('Exception occured due to %s' % ex)
    if check_elastic_status():
        db = ElasticsearchStore(
            es_connection=es,
            index_name=['cml_study_guide', 'docx_pdf', 'new_pdf', 'pl_pilot_24_02_21_lg','botcoach_index','mcq','pdf_test','docx_test','excel_test','csv_test','xlsx','word_docx','pdf_docs'],
            embedding=embeddings,
            strategy=ElasticsearchStore.ExactRetrievalStrategy()
        )
        
def get_chat_id_names_by_session_id(index_name, session_id):
    query = {
        "query": {
            "match": {
                "session_id": session_id
            }
        }
    }
    
    response = es.search(index=index_name, body=query)
    
    chat_id_names = []
    for hit in response['hits']['hits']:
        source = hit['_source']
        if 'chat_id_name' in source:
            chat_id_names.append(source['chat_id_name'])
    
    return chat_id_names

def get_upload_docuindex(index_name,session_id):
# Perform the search
    search_body = {
        "query": {
            "match": {
                "metadata.session_id": session_id
            }
        }
    }
    
    response = es.search(index=index_name, body=search_body)
    
    documents = []
    # Create Document objects from search results
    for hit in response['hits']['hits']:
        source = hit['_source']
        text = source.get('text')  # Adjust 'text' to the actual field name
        metadata = source.get('metadata', {})  # Adjust 'metadata' if needed
        documents.append(Document(page_content=text, metadata=metadata))
    return documents

def add_user_message_to_es( username, session_id, user_prompt):
    # Create a document with the required fields
    doc = {
        'username': username,
        'session_id': session_id,
        'user_prompt': user_prompt,
        "created_at": round(time() * 1000),
        "lastmodified_at": round(time() * 1000),
        "history": json.dumps(
            message_to_dict(HumanMessage(content=user_prompt)),
            ensure_ascii=True,
        ),
    }
    
    # Index the document in Elasticsearch
    res = es.index(index=es_index_name, body=doc)
    return res

def add_assistant_message_to_es(username, session_id, answer):
    # Create a document with the required fields
    doc = {
        'username': username,
        'session_id': session_id,
        'answer': answer,
        "created_at": round(time() * 1000),
        "lastmodified_at": round(time() * 1000),
        "history": json.dumps(
            message_to_dict(AIMessage(content=answer)),
            ensure_ascii=True,
        ),
    }
    
    # Index the document in Elasticsearch
    res = es.index(index=es_index_name, body=doc)
    return res

def search_by_session_id(index_name, session_id):
    # Define the query
    query = {
        "query": {
            "match": {
                "session_id": session_id
            }
        },
        "sort": [
            {
                "lastmodified_at": {
                    "order": "asc"
                }
            }
        ]
    }

    # Perform the search
    response = es.search(index=index_name, body=query)

    return response['hits']['hits']


def update_lastmodified_at(index_name, doc_id):
    # Get current timestamp in milliseconds
    current_timestamp = int(datetime.now().timestamp() * 1000)
    
    # Define the update body
    update_body = {
        "doc": {
            "lastmodified_at": current_timestamp  # Update with timestamp in milliseconds
        }
    }

    # Perform the update
    es.update(index=index_name, id=doc_id, body=update_body)
    
def update_create_at_with_sessionid(index_name,session_id):
    documents = search_by_session_id(index_name, session_id)
    # Update 'lastmodified_at' field for each matched document
    for doc in documents:
        doc_id = doc['_id']  # Get the document ID
        update_lastmodified_at(index_name, doc_id)
    
# @csrf_exempt
# def index(request):
#     if request.method == 'POST':
#         print('entered')
#         message = request.POST.get('message')
#         print('msg', message)
#         message='got message'
#         response = {'message': 'Message received: ' + message}
#         return JsonResponse(response)
#     else:
#         return JsonResponse({'error': 'Invalid request method'}, status=400)

@csrf_exempt
def allibot(request):
    try:
        if request.method=='POST':
            action_type = request.POST.get('operational_type')
            global session_id
            # request.session.clear()
            if action_type == 'action1':
                username =request.POST.get('username')
                session_id=request.POST.get('session_id')
                print('session id',session_id)
                print('/n')
                # chat_history_1 = ElasticsearchChatMessageHistory(es_connection=es,index=es_index_name, session_id=session_id)
                user_prompt = request.POST.get('message')
                update_create_at_with_sessionid(es_index_name, session_id)
                add_user_message_to_es(username,session_id, user_prompt)
    
                template = """Answer the question in your own words as truthfully as possible from the context given to you. If there is any MCQ question explain why the choice is correct.
                If you do not know the answer to the question, simply respond with "I don't know. Can you ask another question".
                Response must be in and around 200 words. it must be in paragraph manner and it must not exceed 4 paragraphs.
                Give a line of space between the paragraphs.
                If questions are asked where there is no relevant context available, simply respond with "I don't know. Please ask a question relevant to the documents"
                Context: {context}
        
        
                {chat_history}
                Human: {question}
                Assistant:"""
                
                prompt = PromptTemplate(input_variables=["context", "chat_history", "question"], template=template)
            
                memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True, output_key='answer')
                            
                result = es.search(
                    index=es_index_name,
                    query={"term": {"session_id": session_id}},
                        sort="lastmodified_at:asc",
                    )
                if result and len(result["hits"]["hits"]) > 0:
                    items = [
                        json.loads(document["_source"]["history"])
                        for document in result["hits"]["hits"]
                    ]
                else:
                    items = []
    
                session_chat_hist=messages_from_dict(items)
                if session_chat_hist:
                    for i in range(0,len(session_chat_hist)-1):
                        if type(session_chat_hist[i]) == HumanMessage:
                            memory.chat_memory.add_user_message(session_chat_hist[i].content)
                        elif type(session_chat_hist[i]) == AIMessage:
                            memory.chat_memory.add_ai_message(session_chat_hist[i].content)
                            
                qa = ConversationalRetrievalChain.from_llm(
                    llm=ChatOpenAI(model="gpt-3.5-turbo-1106"),retriever=db.as_retriever(search_kwargs={"k": 4}), memory=memory,
                    combine_docs_chain_kwargs={'prompt': prompt},return_source_documents=True)
        
                formatted_response = qa(user_prompt)
                answer=formatted_response['answer']
                print('answer',answer)
                # chat_history_1.add_ai_message(answer)
                add_assistant_message_to_es(username,session_id, answer)
                return JsonResponse({'response': answer,'session_id':session_id})
            

    except Exception as e:
        logger.exception('Exception occured due to %s' % e)
        return JsonResponse({'error': str(e)})
    

def doccompare(request):
    try:
        if request.method=='POST':
            action_type = request.POST.get('operational_type')
            global session_id
            # request.session.clear()
            if action_type == 'action1':
                print('entered doc compare')
                client = OpenAI()

                username =request.POST.get('username')
                session_id=request.POST.get('session_id')
                print('session id',session_id)
                print('/n')
                # chat_history_1 = ElasticsearchChatMessageHistory(es_connection=es,index=es_index_name, session_id=session_id)
                user_prompt = request.POST.get('message')
                update_create_at_with_sessionid(es_index_name, session_id)
                add_user_message_to_es(username,session_id, user_prompt)
                
                context1=get_upload_docuindex('upload1',session_id)
                context2= get_upload_docuindex('upload2',session_id)
                # context3=db.similarity_search(user_prompt)
                # Context: Document 1 context: {context1} and Document 2 context: {context2} and Document 3 context: {context3}

                
                memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True, output_key='answer')

                template = """Answer the question in your own words as truthfully as possible from the context given to you.
                If you do not know the answer to the question, simply respond with "I don't know. Please ask a question relevant to the documents."
                Response must be in and around 200 words. It must be in paragraph manner and it must not exceed 4 paragraphs.
                Give a line of space between the paragraphs.
                If questions are asked where there is no relevant context available, simply respond with "I don't know. Please ask a question relevant to the documents."

                Context: Document 1 context: {context1} and Document 2 context: {context2}

                Chat History: {chat_history}

                Human: {question}
                Assistant:"""
                

                result = es.search(
                    index=es_index_name,
                    query={"term": {"session_id": session_id}},
                        sort="lastmodified_at:asc",
                    )
                if result and len(result["hits"]["hits"]) > 0:
                    items = [
                        json.loads(document["_source"]["history"])
                        for document in result["hits"]["hits"]
                    ]
                else:
                    items = []
    
                session_chat_hist=messages_from_dict(items)
                if session_chat_hist:
                    for i in range(0,len(session_chat_hist)-1):
                        if type(session_chat_hist[i]) == HumanMessage:
                            memory.chat_memory.add_user_message(session_chat_hist[i].content)
                        elif type(session_chat_hist[i]) == AIMessage:
                            memory.chat_memory.add_ai_message(session_chat_hist[i].content)
                            
                # Retrieve the chat history from memory
                memory_variables = memory.load_memory_variables({"input": ""})  # Use an empty input since we only need chat history
                chat_history = memory_variables['chat_history']
                print(chat_history)
                # Format the template with the chat history
                formatted_template = template.format(
                    context1=context1, 
                    context2=context2, 
                    # context3=context3, 
                    chat_history=chat_history,
                    question=user_prompt
                )

                # Stream the response
                stream = client.chat.completions.create(
                    model="gpt-4o-mini",
                    messages=[{"role": "user", "content": formatted_template}],
                    stream=True,
                )

                assistant_response = ""
                for chunk in stream:
                    if chunk.choices[0].delta.content is not None:
                        print(chunk.choices[0].delta.content, end="")
                        assistant_response += chunk.choices[0].delta.content

                add_assistant_message_to_es(username,session_id, assistant_response)
                return JsonResponse({'response': assistant_response,'session_id':session_id})
            
            elif action_type == 'action2':
                print('entered second condition')
                files = request.FILES.getlist('files')
                conver_id=request.POST.get('session_id')
                print("conver_id",conver_id)
                if not files:
                    return JsonResponse({'status': 'error', 'message': 'No files uploaded'}, status=400)

                upload_dir = os.path.join(os.path.dirname(__file__))+'/uploads1'
                if not os.path.exists(upload_dir):
                    os.makedirs(upload_dir)

                for file in files:
                    file_path = os.path.join(upload_dir, file.name)
                    with open(file_path, 'wb+') as destination:
                        for chunk in file.chunks():
                            destination.write(chunk)
                ind_response=start_indexing(upload_dir,'upload1',conver_id)
                files_dir = glob(upload_dir+'/*')
                for f in files_dir:
                    os.remove(f)
                print("response status",ind_response)
                if ind_response==1:
                    res_msg=str(len(files))+' uploads complete'
                    return JsonResponse({'status': 'success', 'message':res_msg})

                else:
                    res_msg='unable to process upload1 documents.'
                    return JsonResponse({'status': 'failed', 'message':res_msg})
            
            elif action_type == 'action3':
                print('entered third condition')
                files = request.FILES.getlist('files')
                conver_id=request.POST.get('session_id')
                print("conver_id",conver_id)
                if not files:
                    return JsonResponse({'status': 'error', 'message': 'No files uploaded'}, status=400)

                upload_dir = os.path.join(os.path.dirname(__file__))+'/uploads2'
                if not os.path.exists(upload_dir):
                    os.makedirs(upload_dir)

                for file in files:
                    file_path = os.path.join(upload_dir, file.name)
                    with open(file_path, 'wb+') as destination:
                        for chunk in file.chunks():
                            destination.write(chunk)
                ind_response2=start_indexing(upload_dir,'upload2',conver_id)
                files_dir = glob(upload_dir+'/*')
                for f in files_dir:
                    os.remove(f)
                
                print("response status",ind_response2)
                if ind_response2==1:
                    res_msg=str(len(files))+' uploads complete'
                    return JsonResponse({'status': 'success', 'message':res_msg})

                else:
                    res_msg='unable to process upload2 documents.'
                    return JsonResponse({'status': 'failed', 'message':res_msg})

    except Exception as e:
        logger.exception('Exception occured due to %s' % e)
        return JsonResponse({'error': str(e)})
    

def imgtotext(request):
    try:
        if request.method=='POST':
            action_type = request.POST.get('operational_type')
            global session_id
            # request.session.clear()
            if action_type == 'action1':
                print('entered doc compare')

                username =request.POST.get('username')
                session_id=request.POST.get('session_id')
                print('session id',session_id)
                print('/n')
                # chat_history_1 = ElasticsearchChatMessageHistory(es_connection=es,index=es_index_name, session_id=session_id)
                user_prompt = request.POST.get('message')
                update_create_at_with_sessionid(es_index_name, session_id)
                add_user_message_to_es(username,session_id, user_prompt)
                
                updocuments1,sourcedata1,page_content1=get_faiss_index_doc('image_datas',session_id)
                vs1 = FAISS.from_texts(updocuments1, embedding=OpenAIEmbeddings(), metadatas=sourcedata1)
                context1 =vs1.as_retriever(search_kwargs=dict(k=4))
                
                allibot_knowl=db.similarity_search(user_prompt)
                updocuments2=[i.page_content for i in allibot_knowl]
                sourcedata2=[i.metadata for i in allibot_knowl]
                vs2= FAISS.from_texts(updocuments2, embedding=OpenAIEmbeddings(), metadatas=sourcedata2)
                context2 =vs2.as_retriever(search_kwargs=dict(k=4))
                
                ensemble_retriever = EnsembleRetriever(
                    retrievers=[context1, context2], weights=[0.5,0.5]
                )
                
                combined_results=page_content1+allibot_knowl
                context = "\n".join([doc.page_content for doc in combined_results])
                
                memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True, output_key='answer')

                template = """Answer the question in your own words as truthfully as possible from the context given to you. If there is any MCQ question explain why the choice is correct.
                If you do not know the answer to the question, simply respond with "I don't know. Can you ask another question".
                Response must be in and around 200 words. it must be in paragraph manner and it must not exceed 4 paragraphs.
                Give a line of space between the paragraphs.
                If questions are asked where there is no relevant context available, simply respond with "I don't know. Please ask a question relevant to the documents"
                Context: {context}
        
        
                {chat_history}
                Human: {question}
                Assistant:"""                

                prompt = PromptTemplate(input_variables=[context, "chat_history", "question"], template=template)

                result = es.search(
                    index=es_index_name,
                    query={"term": {"session_id": session_id}},
                        sort="lastmodified_at:asc",
                    )
                if result and len(result["hits"]["hits"]) > 0:
                    items = [
                        json.loads(document["_source"]["history"])
                        for document in result["hits"]["hits"]
                    ]
                else:
                    items = []
    
                session_chat_hist=messages_from_dict(items)
                if session_chat_hist:
                    for i in range(0,len(session_chat_hist)-1):
                        if type(session_chat_hist[i]) == HumanMessage:
                            memory.chat_memory.add_user_message(session_chat_hist[i].content)
                        elif type(session_chat_hist[i]) == AIMessage:
                            memory.chat_memory.add_ai_message(session_chat_hist[i].content)
                            
                # Retrieve the chat history from memory
                qa = ConversationalRetrievalChain.from_llm(
                    llm=ChatOpenAI(model="gpt-3.5-turbo-1106"),
                    retriever=ensemble_retriever,
                    memory=memory,
                    combine_docs_chain_kwargs={'prompt': prompt},
                    return_source_documents=True
                )

                formatted_response = qa(user_prompt)
                answer=formatted_response['answer']
                print('answer',answer)
                # chat_history_1.add_ai_message(answer)
                add_assistant_message_to_es(username,session_id, answer)
                return JsonResponse({'response': answer,'session_id':session_id})
            
            elif action_type == 'action2':
                print('entered second condition')
                files = request.FILES.getlist('files')
                conver_id=request.POST.get('session_id')
                print("conver_id",conver_id)
                if not files:
                    return JsonResponse({'status': 'error', 'message': 'No files uploaded'}, status=400)

                upload_dir = os.path.join(os.path.dirname(__file__))+'/image_pth'
                if not os.path.exists(upload_dir):
                    os.makedirs(upload_dir)

                for file in files:
                    file_path = os.path.join(upload_dir, file.name)
                    with open(file_path, 'wb+') as destination:
                        for chunk in file.chunks():
                            destination.write(chunk)
                ind_response=Image_indexing(upload_dir,'image_datas',conver_id)
                files_dir = glob(upload_dir+'/*')
                for f in files_dir:
                    os.remove(f)
                if ind_response==1:
                    res_msg=str(len(files))+' uploads complete'
                    return JsonResponse({'status': 'success', 'message':res_msg})

                else:
                    res_msg='Unable to process image.'
                    return JsonResponse({'status': 'failed', 'message':res_msg})

    except Exception as e:
            logger.exception('Exception occured due to %s' % e)
            return JsonResponse({'error': str(e)})
            
def today_messages(request):
    try:
        t=[]
        username = request.headers.get('X-Username')
        test = get_messages_by_user_and_session(username)
        # Get current date and time in UTC
        current_datetime = datetime.now(timezone.utc)
        
        # Calculate the start of today and yesterday in UTC
        start_of_today = current_datetime.replace(hour=0, minute=0, second=0, microsecond=0)
        for item in test:
            lastmodified_at_datetime = datetime.fromtimestamp(item['lastmodified_at'] / 1000, tz=timezone.utc)
            if start_of_today <= lastmodified_at_datetime <= current_datetime:
                t.append(item)
        if t:
            #session_ids = list(set(d["session_id"] for d in t))
            session_ids=list(OrderedDict.fromkeys(d["session_id"] for d in t))
            yest_dict = {}
            items=[]
            for id_user in session_ids[::-1]:
                result = es.search(
                    index=es_index_name,
                    query={"term": {"session_id": id_user}},
                    sort="lastmodified_at:asc",
                )
                if result and len(result["hits"]["hits"]) > 0:
                    session_hist = messages_from_dict(json.loads(document["_source"]["history"])
                                                      for document in result["hits"]["hits"])

                    tot_hist=[]
                    chat_h={}
                    for i in session_hist:
                        if type(i) == HumanMessage:
                            chat_h = {
                                'user': i.content}
                        elif type(i) == AIMessage:
                             chat_h= {
                                 'assistant': i.content}
                        tot_hist.append(chat_h)
                    
                    chat_id_names = get_chat_id_names_by_session_id(chatname_index, id_user)

                    yest_dict = {
                        'session_id': id_user,
                        'chat_history':tot_hist,
                        'content': chat_id_names
                    }
                    
                    items.append(yest_dict)

            # Returning the first message content and the session ID for simplicity
            formatted_yest_dict = {
                "messages": items
            }
        else:
            formatted_yest_dict = {"messages": []}
        # print('today',formatted_yest_dict)
        return  JsonResponse({'messages': formatted_yest_dict})

    except Exception as e:
        # Log the error and return a JSON error response
        print(f"Error in today_messages view: {e}")
        return JsonResponse({"error": str(e)}, status=500)

def yesterday_messages(request):
    try:
        y=[]
        username = request.headers.get('X-Username')
        print('username',username)
        test = get_messages_by_user_and_session(username)
        # Get current date and time in UTC
        current_datetime = datetime.now(timezone.utc)
        
        # Calculate the start of today and yesterday in UTC
        start_of_today = current_datetime.replace(hour=0, minute=0, second=0, microsecond=0)
        start_of_yesterday = start_of_today - timedelta(days=1)
        end_of_yesterday = start_of_today - timedelta(microseconds=1) 
        for item in test:
            lastmodified_at_datetime = datetime.fromtimestamp(item['lastmodified_at'] / 1000, tz=timezone.utc)
            if start_of_yesterday <= lastmodified_at_datetime <= end_of_yesterday:
                y.append(item)
        if y:
            # session_ids = list(set(d["session_id"] for d in y))
            session_ids=list(OrderedDict.fromkeys(d["session_id"] for d in y))

            yest_dict = {}
            items=[]
            for id_user in session_ids[::-1]:
                result = es.search(
                    index=es_index_name,
                    query={"term": {"session_id": id_user}},
                    sort="lastmodified_at:asc",
                )
                if result and len(result["hits"]["hits"]) > 0:
                    session_hist = messages_from_dict(json.loads(document["_source"]["history"])
                                                      for document in result["hits"]["hits"])

                    tot_hist=[]
                    chat_h={}
                    for i in session_hist:
                        if type(i) == HumanMessage:
                            chat_h = {
                                'user': i.content}
                        elif type(i) == AIMessage:
                             chat_h= {
                                 'assistant': i.content}
                        tot_hist.append(chat_h)
                    chat_id_names = get_chat_id_names_by_session_id(chatname_index, id_user)
                    yest_dict = {
                        'session_id': id_user,
                        'chat_history':tot_hist,
                        'content': chat_id_names
                    }
                    
                    items.append(yest_dict)

            # Returning the first message content and the session ID for simplicity
            formatted_yest_dict = {
                "messages": items
            }
        else:
            formatted_yest_dict = {"messages": []}
        # print('yesterday',formatted_yest_dict)
        return  JsonResponse({'messages': formatted_yest_dict})

    except Exception as e:
        # Log the error and return a JSON error response
        print(f"Error in yesterday_messages view: {e}")
        return JsonResponse({"error": str(e)}, status=500)
    
def previous_7_days(request):
    try:
        s=[]
        username = request.headers.get('X-Username')
        test = get_messages_by_user_and_session(username)
        # Get current date and time in UTC
        current_datetime = datetime.now(timezone.utc)
        
        # Calculate the start of today and yesterday in UTC
        start_of_today = current_datetime.replace(hour=0, minute=0, second=0, microsecond=0)
        start_of_yesterday = start_of_today - timedelta(days=1)
        start_of_seven_days_ago = start_of_today - timedelta(days=7)     
        for item in test:
            lastmodified_at_datetime = datetime.fromtimestamp(item['lastmodified_at'] / 1000, tz=timezone.utc)
            if start_of_seven_days_ago <= lastmodified_at_datetime < start_of_yesterday:
                s.append(item)

        if s:
            
            # session_ids = list(set(d["session_id"] for d in s))
            session_ids=list(OrderedDict.fromkeys(d["session_id"] for d in s))

            yest_dict = {}
            items=[]
            for id_user in session_ids[::-1]:
                result = es.search(
                    index=es_index_name,
                    query={"term": {"session_id": id_user}},
                    sort="lastmodified_at:asc",
                )
                if result and len(result["hits"]["hits"]) > 0:
                    session_hist = messages_from_dict(json.loads(document["_source"]["history"])
                                                      for document in result["hits"]["hits"])

                    tot_hist=[]
                    chat_h={}
                    for i in session_hist:
                        if type(i) == HumanMessage:
                            chat_h = {
                                'user': i.content}
                        elif type(i) == AIMessage:
                             chat_h= {
                                 'assistant': i.content}
                        tot_hist.append(chat_h)
                    chat_id_names = get_chat_id_names_by_session_id(chatname_index, id_user)
                    yest_dict = {
                        'session_id': id_user,
                        'chat_history':tot_hist,
                        'content': chat_id_names
                    }
                    
                    items.append(yest_dict)

            # Returning the first message content and the session ID for simplicity
            formatted_yest_dict = {
                "messages": items
            }
        else:
            formatted_yest_dict = {"messages": []}
        # print('previous',formatted_yest_dict)

        return  JsonResponse({'messages': formatted_yest_dict})

    except Exception as e:
        # Log the error and return a JSON error response
        print(f"Error in previous7days_messages view: {e}")
        return JsonResponse({"error": str(e)}, status=500)