"""
Database connection management for Demo Session Service
"""

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.pool import NullPool
import structlog

from .config import settings

logger = structlog.get_logger()


class DatabaseManager:
    """Database connection manager"""

    def __init__(self, database_url: str = None):
        self.database_url = database_url or settings.DATABASE_URL
        self.engine = None
        self.session_factory = None

    def initialize(self):
        """Initialize database engine and session factory"""
        self.engine = create_async_engine(
            self.database_url,
            echo=settings.DEBUG,
            poolclass=NullPool,
            pool_pre_ping=True
        )

        self.session_factory = async_sessionmaker(
            self.engine,
            class_=AsyncSession,
            expire_on_commit=False,
            autocommit=False,
            autoflush=False
        )

        logger.info("Database manager initialized", database_url=self.database_url.split("@")[-1])

    async def close(self):
        """Close database connections"""
        if self.engine:
            await self.engine.dispose()
            logger.info("Database connections closed")

    async def get_session(self) -> AsyncSession:
        """Get database session"""
        if not self.session_factory:
            self.initialize()
        async with self.session_factory() as session:
            yield session


db_manager = DatabaseManager()


async def get_db() -> AsyncSession:
    """Dependency for FastAPI"""
    async for session in db_manager.get_session():
        yield session
