from django.conf import settings
import pyodbc

def create_db_connection(env="dev"):
    try:
        connection_details = settings.DATABASE_CONNECTIONS.get(env)
        if not connection_details:
            raise ValueError(f"Environment '{env}' not found in DATABASE_CONNECTIONS")
        
        connection_string = (
            f"DRIVER={connection_details['DRIVER']};"
            f"SERVER={connection_details['SERVER']};"
            f"DATABASE={connection_details['DATABASE']};"
            f"UID={connection_details['UID']};"
            f"PWD={connection_details['PWD']}"
        )
        return pyodbc.connect(connection_string)
    except Exception as e:
        raise RuntimeError(f"Failed to establish database connection: {e}")

