from collections.abc import Generator

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker

from app.config import get_settings


class Base(DeclarativeBase):
    pass


settings = get_settings()
connect_args = {"check_same_thread": False} if settings.resolved_database_url.startswith("sqlite") else {}
engine = create_engine(settings.resolved_database_url, connect_args=connect_args, future=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)


def get_db() -> Generator[Session, None, None]:
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_db() -> None:
    from app import models

    Base.metadata.create_all(bind=engine)
    with SessionLocal() as db:
        if not db.query(models.User).first():
            db.add(
                models.User(
                    name="默认审核员",
                    email="reviewer@example.local",
                    role=models.UserRole.reviewer,
                )
            )
        defaults = {
            "risk_policy": "AI 只做初筛，未审核内容不能进入标准问答库或可调用库。",
            "mock_mode": "true" if settings.mock_mode else "false",
        }
        for key, value in defaults.items():
            exists = db.query(models.SystemSetting).filter(models.SystemSetting.key == key).first()
            if not exists:
                db.add(models.SystemSetting(key=key, value=value, description="系统内置非敏感配置"))
        db.commit()

