import os

from dotenv import load_dotenv
from pymongo import MongoClient

from pif_compiler.services.common_log import get_logger

# config log and env
logger = get_logger()
load_dotenv()

def get_client():
    ADMIN_USER = os.getenv("ADMIN_USER")
    ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
    MONGO_HOST = os.getenv("MONGO_HOST")
    MONGO_PORT = os.getenv("MONGO_PORT")

    client = MongoClient(
        f"mongodb://{ADMIN_USER}:{ADMIN_PASSWORD}@{MONGO_HOST}:{MONGO_PORT}/?authSource=admin",
        serverSelectionTimeoutMS=5000
    )

    return client if client else None

def db_connect(db_name : str = 'toxinfo', collection_name : str = 'substance_index') -> dict:
    """
    Connect to the MongoDB database and return the specified collection.
    """
    try:
        client = get_client()
        db = client.get_database(name=db_name)
        collection = db.get_collection(collection_name)
    except Exception as e:
        logger.error(f"Error connecting to MongoDB: {e}")
        return None

    return client, db, collection
