# Requirement: pymongo bson

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

mongoclient = "mongodb+srv://navin:<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>/mydatabase?retryWrites=true&w=majority"
client = MongoClient(f"{mongoclient}mydatabase?retryWrites=true&w=majority")

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

def create_chat_session(device_id, chat_session_id, 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,
                '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)
    except Exception as e:
        logging.error("Error when creating chat session.")

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

def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        device_id = req.params.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 = req.params.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 = req.params.get('user_query')
        bot_reply = req.params.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')
        
        create_chat_session(device_id, chat_session_id)        
        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')

does this look right?