"""
Database connection management

Provides database engine and session factory
"""

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from loguru import logger

from config.settings import Settings


# Global engine and session factory
_engine = None
_SessionFactory = None


def get_engine():
    """Get or create database engine"""
    global _engine

    if _engine is None:
        settings = Settings()
        database_url = settings.database_url

        logger.info(f"Creating database engine: {database_url.split('@')[1] if '@' in database_url else 'local'}")

        _engine = create_engine(
            database_url,
            pool_size=10,
            max_overflow=20,
            pool_pre_ping=True,  # Verify connections
            echo=False  # Set to True for SQL logging
        )

    return _engine


def get_session() -> Session:
    """Get a new database session"""
    global _SessionFactory

    if _SessionFactory is None:
        engine = get_engine()
        _SessionFactory = sessionmaker(bind=engine)

    return _SessionFactory()


def close_engine():
    """Close database engine"""
    global _engine, _SessionFactory

    if _engine:
        _engine.dispose()
        _engine = None
        _SessionFactory = None
        logger.info("Database engine closed")
