# app/core/time.py
from datetime import datetime
from zoneinfo import ZoneInfo
from app.core.config import settings
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import sessionmaker, Session
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('adimsayar')

# SQLAlchemy 엔진 생성
engine = create_engine(
    settings.SQLALCHEMY_DATABASE_URI,
    echo=False,           # SQLAlchemy 로깅 비활성화
    pool_pre_ping=True,
    pool_size=10,
    max_overflow=20,
    pool_recycle=3600     # 연결을 1시간마다 재활용
)

# SessionLocal 클래스 생성
SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine,
    expire_on_commit=False
)

def get_db():
    db = SessionLocal()
    try:
        yield db
    except Exception as e:
        logger.error(f"Database session error: {str(e)}")
        db.rollback()
        raise
    finally:
        db.close()

def now() -> datetime:
    """
    Returns the current datetime in the timezone specified in settings.TIMEZONE.
    If the timezone is not available, it falls back to UTC.
    """
    try:
        tz = ZoneInfo(settings.TIMEZONE)
    except Exception as e:
        # Fallback to UTC if the timezone cannot be loaded
        tz = ZoneInfo("UTC")
    return datetime.now(tz)