from sqlalchemy import create_engine, event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
from .settings import settings
from .logging_config import get_logger
logger = get_logger(__name__)
DATABASE_URL = settings.database_url
engine = create_engine(DATABASE_URL, poolclass=QueuePool, pool_pre_ping=True, pool_recycle=3600, pool_size=10, max_overflow=20, echo=settings.is_development, future=True, connect_args={'charset': 'utf8mb4', 'connect_timeout': 10})

@event.listens_for(engine, 'connect')
def set_sqlite_pragma(dbapi_conn, connection_record):
    logger.debug('New database connection established')

@event.listens_for(engine, 'checkout')
def receive_checkout(dbapi_conn, connection_record, connection_proxy):
    logger.debug('Connection checked out from pool')

@event.listens_for(engine, 'checkin')
def receive_checkin(dbapi_conn, connection_record):
    logger.debug('Connection returned to pool')
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()