# 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 sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from oslo_config import cfg
from oslo_db.sqlalchemy import models

from vmms import config

Base = declarative_base()

# Global variables to cache engine
_engine = None

def get_engine():
    """Get database engine"""
    global _engine
    
    if _engine is None:
        # Import config only when needed
        
        # Try to get existing CONF, if not available, initialize
        try:
            CONF = cfg.CONF
            # Check if config is already initialized
            if not hasattr(CONF, 'database') or not hasattr(CONF.database, 'connection'):
                CONF = config.init_config()
        except Exception:
            CONF = config.init_config()
        
        _engine = create_engine(CONF.database.connection)
    
    return _engine

def get_session():
    """Get database session"""
    engine = get_engine()
    Session = sessionmaker(bind=engine)
    return Session()
