"""
app/core/database.py — SQLAlchemy 双库连接（MySQL + MongoDB）
"""

from motor.motor_asyncio import AsyncIOMotorClient
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker

from app.core.config import get_settings

settings = get_settings()

# ── MySQL（主业务库）──────────────────────────────────
engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,
    pool_size=10,
    max_overflow=20,
    echo=(settings.APP_ENV == "development"),
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


class Base(DeclarativeBase):
    """所有 ORM 模型的基类。"""
    pass


def get_db():
    """FastAPI 依赖注入：获取 DB Session，用完自动关闭。"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# ── MongoDB（只存 AI debug trace，业务不依赖）──────────
_mongo_client: AsyncIOMotorClient | None = None


def get_mongo_client() -> AsyncIOMotorClient:
    global _mongo_client
    if _mongo_client is None:
        _mongo_client = AsyncIOMotorClient(settings.MONGO_URI)
    return _mongo_client


def get_mongo_db():
    """获取 MongoDB 数据库实例（clover_trace）。"""
    client = get_mongo_client()
    return client["clover_trace"]
