{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pinged your deployment. You successfully connected to MongoDB!\n"
     ]
    }
   ],
   "source": [
    "from core.chat.chatstore import ChatStore\n",
    "from pymongo.mongo_client import MongoClient\n",
    "from dotenv import load_dotenv\n",
    "import os\n",
    "\n",
    "load_dotenv()\n",
    "# uri = \"mongodb+srv://summariz:testdb@cluster0.bw0sr.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0\"\n",
    "uri = os.getenv(\"MONGO_URI\")\n",
    "client = MongoClient(uri)\n",
    "\n",
    "try:\n",
    "    client.admin.command('ping')\n",
    "    print(\"Pinged your deployment. You successfully connected to MongoDB!\")\n",
    "except Exception as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'role': 'user', 'content': 'hallo', 'additional_kwargs': {}},\n",
       " {'role': 'assistant',\n",
       "  'content': 'Halo! Ada yang bisa saya bantu hari ini, dok? 😊',\n",
       "  'metadata': []}]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_store = ChatStore()\n",
    "session_id = \"dfe69118-355b-4276-adc8-0a82e5706f44\"\n",
    "chat_history = chat_store.get_messages(session_id)\n",
    "chat_history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "db = client['bot_database']  # Replace with your database name\n",
    "collection = db['bot']  # Replace with your collection name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = collection.insert_many(chat_history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data inserted with record ids [ObjectId('67060bd6c8ffb964976540a5'), ObjectId('67060bd6c8ffb964976540a6')]\n"
     ]
    }
   ],
   "source": [
    "# Print the IDs of the inserted documents\n",
    "print(\"Data inserted with record ids\", result.inserted_ids)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'role': 'system',\n",
       "  'content': 'halo',\n",
       "  'timestamp': datetime.datetime(2024, 10, 10, 11, 18, 10, 779000)},\n",
       " {'role': 'assistant',\n",
       "  'content': 'Halo! 😊 Ada yang bisa saya bantu hari ini, dok? Jika ada pertanyaan tentang kedokteran atau kesehatan, silakan tanyakan saja!',\n",
       "  'metadata': [],\n",
       "  'timestamp': datetime.datetime(2024, 10, 10, 11, 18, 10, 779000)}]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Select your database\n",
    "db = client['bot_database']  # Replace with your database name\n",
    "\n",
    "# Select your collection\n",
    "collection = db['6fd735b8-a814-47ce-8427-a7bbe4c14ec6']  # Replace with your collection name\n",
    "\n",
    "# Retrieve all documents from the collection\n",
    "documents = collection.find()\n",
    "\n",
    "# Convert the cursor to a list and exclude the _id field\n",
    "documents_list = [{key: doc[key] for key in doc if key != '_id' and doc[key] is not None} for doc in documents]\n",
    "\n",
    "# Print the list of documents without the _id field\n",
    "documents_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collection 'bot' exists in the database 'bot_database'.\n",
      "Doing something because the collection exists.\n"
     ]
    }
   ],
   "source": [
    "def check_collection_exists(db_name, collection_name):\n",
    "    # Connect to the MongoDB server\n",
    "    db = client[db_name]\n",
    "\n",
    "    # Check if the collection exists\n",
    "    if collection_name in db.list_collection_names():\n",
    "        print(f\"Collection '{collection_name}' exists in the database '{db_name}'.\")\n",
    "        # Perform your desired action here\n",
    "        do_something()\n",
    "    else:\n",
    "        print(f\"Collection '{collection_name}' does not exist in the database '{db_name}'.\")\n",
    "\n",
    "def do_something():\n",
    "    # Define the action you want to perform\n",
    "    print(\"Doing something because the collection exists.\")\n",
    "\n",
    "# Example usage\n",
    "check_collection_exists('bot_database', \"bot\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test Redis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The collection 'test' does not exists.\n"
     ]
    }
   ],
   "source": [
    "    \n",
    "import redis\n",
    "from dotenv import load_dotenv\n",
    "import os\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "redis_client = redis.Redis(\n",
    "    host=\"redis-10365.c244.us-east-1-2.ec2.redns.redis-cloud.com\",\n",
    "    port=10365,\n",
    "    password=os.environ.get(\"REDIS_PASSWORD\"),\n",
    ")\n",
    "\n",
    "session_id =\"test\"\n",
    "        \n",
    "if redis_client.exists(session_id):\n",
    "    print(f\"The collection '{session_id}' exists.\")\n",
    "else: \n",
    "    print(f\"The collection '{session_id}' does not exists.\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<starlette.responses.JSONResponse at 0x1e94fe62850>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from core.chat.chatstore import ChatStore\n",
    "\n",
    "chat_store = ChatStore()\n",
    "\n",
    "\n",
    "session_id = \"6fd735b8-a814-47ce-8427-a7bbe4c14ec6\"\n",
    "\n",
    "chat_store.add_chat_history_to_redis(session_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collection(Database(MongoClient(host=['cluster0-shard-00-00.bw0sr.mongodb.net:27017', 'cluster0-shard-00-02.bw0sr.mongodb.net:27017', 'cluster0-shard-00-01.bw0sr.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, retrywrites=True, w='majority', appname='Cluster0', authsource='admin', replicaset='atlas-ukfsmn-shard-0', ssl=True), 'bot_database'), '6fd735b8-a814-47ce-8427-a7bbe4c14ec6')\n",
      "[{'role': 'system', 'content': 'halo'}, {'role': 'assistant', 'content': 'Halo! 😊 Ada yang bisa saya bantu hari ini, dok? Jika ada pertanyaan tentang kedokteran atau kesehatan, silakan tanyakan saja!', 'metadata': []}]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "import redis\n",
    "from service.dto import ChatMessage\n",
    "\n",
    "redis_client = redis.Redis(\n",
    "    host=\"redis-10365.c244.us-east-1-2.ec2.redns.redis-cloud.com\",\n",
    "    port=10365,\n",
    "    password=os.environ.get(\"REDIS_PASSWORD\"),\n",
    ")\n",
    "\n",
    "def message_to_dict(message: ChatMessage) -> dict:\n",
    "    return message.model_dump()\n",
    "\n",
    "session_id = \"6fd735b8-a814-47ce-8427-a7bbe4c14ec6\"\n",
    "db = client[\"bot_database\"]\n",
    "collection = db[session_id]\n",
    "\n",
    "print(collection)\n",
    "\n",
    "chat_history = collection.find()\n",
    "chat_history_list = [\n",
    "    {key: message[key] for key in message if key not in ['_id', 'timestamp'] and message[key] is not None}\n",
    "    for message in chat_history if message is not None\n",
    "]\n",
    "\n",
    "print(chat_history_list)\n",
    "\n",
    "for message in chat_history_list:\n",
    "    # Convert MongoDB document to the format you need\n",
    "    item = json.dumps(message_to_dict(ChatMessage(**message)))  # Convert message to dict\n",
    "    redis_client.rpush(session_id, item)\n",
    "    \n",
    "redis_client.expire(session_id, time=86400)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pinged your deployment. You successfully connected to MongoDB!\n",
      "Saya tidak memiliki informasi spesifik mengenai gejala penyakit jantung dari buku yang tersedia. Namun, secara umum, gejala penyakit jantung dapat mencakup:\n",
      "\n",
      "1. **Nyeri Dada**: Rasa tidak nyaman atau nyeri di dada, sering kali digambarkan sebagai tekanan atau rasa penuh.\n",
      "2. **Sesak Napas**: Kesulitan bernapas, baik saat beraktivitas maupun saat istirahat.\n",
      "3. **Kelelahan**: Rasa lelah yang tidak biasa, bahkan setelah aktivitas ringan.\n",
      "4. **Palpitasi**: Detak jantung yang cepat atau tidak teratur.\n",
      "5. **Pusing atau Pingsan**: Rasa pusing yang bisa berujung pada pingsan.\n",
      "\n",
      "Jika Anda mengalami gejala-gejala tersebut, sangat penting untuk berkonsultasi dengan dokter atau ahli kesehatan untuk evaluasi lebih lanjut. Semoga informasi ini bermanfaat, dok ✨ Jika ada pertanyaan lain, jangan ragu untuk bertanya ya dok 😊\n"
     ]
    }
   ],
   "source": [
    "from pymongo.mongo_client import MongoClient\n",
    "from dotenv import load_dotenv\n",
    "import os\n",
    "\n",
    "load_dotenv()\n",
    "# uri = \"mongodb+srv://summariz:testdb@cluster0.bw0sr.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0\"\n",
    "uri = os.getenv(\"MONGO_URI\")\n",
    "client = MongoClient(uri)\n",
    "\n",
    "try:\n",
    "    client.admin.command('ping')\n",
    "    print(\"Pinged your deployment. You successfully connected to MongoDB!\")\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "    \n",
    "session_id = \"06715451-874f-41e8-8734-d4666d640539\"\n",
    "\n",
    "db = client[\"bot_database\"]\n",
    "collection = db[session_id]\n",
    "\n",
    "# Get the last document by sorting by _id in descending order\n",
    "last_document = collection.find().sort(\"_id\", -1).limit(1)\n",
    "\n",
    "for doc in last_document:\n",
    "    doc['content']"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "fullstack",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}