"""
database.py
------------
SQLAlchemy engine/session setup. Defaults to a local SQLite file for
zero-config local development; set DATABASE_URL to a MySQL DSN for
production, e.g.:

    export DATABASE_URL="mysql+pymysql://mindscreen_user:password@localhost:3306/mindscreen_ai"

Requires `pymysql` (pure-Python MySQL driver, no system libmysqlclient
needed) when using MySQL — see requirements.txt.
"""

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

from .config import settings

connect_args = {"check_same_thread": False} if settings.DATABASE_URL.startswith("sqlite") else {}

engine = create_engine(settings.DATABASE_URL, connect_args=connect_args, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


def get_db():
    """FastAPI dependency: yields a DB session and always closes it."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_db():
    """Create all tables. In production prefer proper migrations (Alembic)
    over this — it's fine for local dev / first run."""
    from . import db_models  # noqa: F401  (ensure models are registered on Base)
    Base.metadata.create_all(bind=engine)
