# Copyright (c) 2025 OpenStack Foundation
#
# 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.

from oslo_db.sqlalchemy import enginefacade
from oslo_config import cfg

# Global variables for engine facade
context_manager = None
_config_initialized = False

def init_database_config(CONF):
    """Initialize database configuration with the given CONF object."""
    global context_manager, _config_initialized

    if _config_initialized:
        return

    # Create engine facade using the provided configuration
    context_manager = enginefacade.transaction_context()

    # Configure with the connection string - oslo.db handles connection management
    context_manager.configure(
        connection=CONF.database.connection
    )

    _config_initialized = True

def _ensure_config_initialized():
    """Ensure database configuration is initialized."""
    if not _config_initialized:
        raise RuntimeError("Database configuration not initialized. Call init_database_config() first.")

def get_session():
    """Get database session using oslo.db enginefacade.

    This session is automatically managed and handles disconnections.
    """
    _ensure_config_initialized()
    return context_manager.get_session()

def get_engine():
    """Get database engine using oslo.db enginefacade."""
    _ensure_config_initialized()
    return context_manager.get_engine()

def get_reader_session():
    """Get read-only database session."""
    _ensure_config_initialized()
    return context_manager.get_reader_session()

def get_writer_session():
    """Get write database session."""
    _ensure_config_initialized()
    return context_manager.get_writer_session()

def get_transaction_context():
    """Get transaction context for database operations."""
    _ensure_config_initialized()
    return context_manager
