# Requirement: pymongo bson

import os
import json
import logging
from pymongo import MongoClient
from datetime import datetime
import azure.functions as func

mongoclient = "mongodb+srv://navin:<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>"
try:
    client = MongoClient(f"{mongoclient}/mydatabase?retryWrites=true&w=majority")
except Exception as e:
    logging.error(f"Error while connecting to MongoDB: {str(e)}")
    raise

db = client['TwT-memory-assist']
chat_sessions_col = db['ChatSessions']
message_pairs_col = db['MessagePairs']

def create_chat_session(device_id, chat_session_id, summary, title=None):
    try:
        existing_chat_session = chat_sessions_col.find_one({
            'device_id': device_id,
            'chat_session_id': chat_session_id
        })
        if not existing_chat_session:
            chat_session = {
                # 'userId': ObjectId(user_id),
                'device_id': device_id,
                'chat_session_id': chat_session_id,
                'summary': summary,
                'title': title if title else 'New Chat Session',
                'isActive': True,
                'createdAt': datetime.now().isoformat(),
                'lastUpdatedAt': datetime.now().isoformat(),
                'metadata': {}
            }
            result = chat_sessions_col.insert_one(chat_session)
            logging.info(f"Chat session successfully created with id: {result.inserted_id}")
            return result.inserted_id
        else:
            chat_sessions_col.update_one(
                {'device_id': device_id, 'chat_session_id': chat_session_id},
                {'$set': {'summary': summary, 'lastUpdatedAt': datetime.now().isoformat()}}
            )
            logging.info("Summary successfully updated in existing chat session.")
        
    except Exception as e:
        logging.error(f"Error when creating chat session: {str(e)}")
        return None

def store_message_pair(device_id, chat_session_id, user_message, bot_reply, summary):
    message_pair = {
        'device_id': device_id,
        'chat_session_id': chat_session_id,
        'userMessage': {
            # 'messageType': user_message['type'],
            'content': str(user_message),
            # 'media': user_message.get('media', {}),
            'createdAt': datetime.now().isoformat()
        },
        'botReply': {
            # 'messageType': bot_reply['type'],
            'content': str(bot_reply),
            'createdAt': datetime.now().isoformat()
        },
        'metadata': {}
    }
    result = message_pairs_col.insert_one(message_pair)
    return result.inserted_id

def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        data = req.get_json()
        device_id = data.get('device_id')
        if not device_id:
            logging.error("Device ID missing!")
            return func.HttpResponse(json.dumps({'error': 'Device ID not found.'}), status_code=400, mimetype='application/json')
        chat_session_id = data.get('chat_session_id')
        if not chat_session_id:
            logging.error("Chat session ID not found!")
            return func.HttpResponse(json.dumps({'error': 'Chat session ID not found.'}), status_code=400, mimetype='application/json')
        user_query = data.get('user_query')
        bot_reply = data.get('bot_reply')
        if not user_query or not bot_reply:
            logging.error("Chat incomplete.")
            return func.HttpResponse(json.dumps({'error': 'Incomplete chat received'}), status_code=400, mimetype='application/json')
        summary=data.get('summary')
        
        create_chat_session(device_id, chat_session_id, summary)
        store_message_pair(device_id, chat_session_id, user_query, bot_reply)

        return func.HttpResponse(json.dumps({'message': 'Chat successfully stored.'}), status_code=200, mimetype='application/json')
    
    except Exception as e:
        logging.error("Error while storing chat. (main)")
        return func.HttpResponse(json.dumps({'error': 'Error while storing chat. (main)'}), status_code=400, mimetype='application/json')

API error:
{
    "error": "400 Client Error: Bad Request for url: http://localhost:7071/api/retrieve_chat"
}