# Copyright (c) 2025 Thomas Goirand <zigo@debian.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import threading
from oslo_db.sqlalchemy import enginefacade
from oslo_config import cfg

# Global variables for engine facade
_LOCK = threading.Lock()
_MAIN_CONTEXT_MANAGER = None

def _get_main_context_manager():
    global _LOCK, _MAIN_CONTEXT_MANAGER

    if _MAIN_CONTEXT_MANAGER is not None:
        return _MAIN_CONTEXT_MANAGER

    with _LOCK:
        if _MAIN_CONTEXT_MANAGER is None:
            _MAIN_CONTEXT_MANAGER = enginefacade.transaction_context()
    return _MAIN_CONTEXT_MANAGER

def init_database_config(CONF):
    """Initialize database configuration with the given CONF object."""
    context_manager = _get_main_context_manager()
    context_manager.configure(
        connection=CONF.database.connection
    )

def get_session():
    """Get database session using oslo.db enginefacade."""
    return _get_main_context_manager().writer.get_sessionmaker()()

def get_engine():
    """Get database engine using oslo.db enginefacade."""
    return _get_main_context_manager().writer.get_engine()

def get_reader_session():
    """Get read-only database session."""
    return _get_main_context_manager().reader.get_sessionmaker()()

def get_writer_session():
    """Get write database session."""
    return _get_main_context_manager().writer.get_sessionmaker()()
