import logging
from typing import AsyncGenerator

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from app.core.config import settings

logger = logging.getLogger(__name__)

engine = create_async_engine(
    settings.METADATA_DATABASE_URI,
    pool_size=settings.METADATA_DB_POOL_SIZE,
    max_overflow=settings.METADATA_DB_MAX_OVERFLOW,
    pool_pre_ping=True,
)

SessionLocal = async_sessionmaker(engine, expire_on_commit=False)


async def get_metadata_session() -> AsyncGenerator[AsyncSession, None]:
    async with SessionLocal() as session:
        yield session


async def close_metadata_engine() -> None:
    await engine.dispose()
    logger.info("Metadata database engine disposed.")
