import os
from pymongo import MongoClient
import urllib.parse
from dotenv import load_dotenv

load_dotenv()  # This line will load the .env file

def get_database():
        mongo_host = os.getenv("MONGO_HOST", "localhost")
        mongo_user = os.getenv("MONGO_USER")
        mongo_pass = os.getenv("MONGO_PASS")
        mongo_db_name = os.getenv("MONGO_DB", "thought")
        mongo_uri = os.getenv("MONGO_URI")

        if not mongo_uri:
            if mongo_user and mongo_pass:
                mongo_pass = urllib.parse.quote_plus(mongo_pass)
                mongo_uri = f"mongodb://{mongo_user}:{mongo_pass}@{mongo_host}:27017/{mongo_db_name}"
                #print( "Mongo URI is ", mongo_uri)
            else:
                mongo_uri = f"mongodb://{mongo_host}:27017/{mongo_db_name}"

        # Directly creating MongoClient instance
        client = MongoClient(mongo_uri)
        db = client[mongo_db_name]
        #print("DBBBBBB Connection OPEN ")
        return db

def check_connection(client):
    try:
        # The 'admin' database is always present in MongoDB instances.
        client.thought.command('ping')
        print("MongoDB is connected")
    except Exception as e:
        print("MongoDB is not connected", e)
