"""
FastAPI dependencies for wiki API routes.

Uses pycharter's database configuration (PYCHARTER_DATABASE_URL)
instead of the standalone wiki's PYCHARTER_WIKI_DATABASE_URL.
"""

from __future__ import annotations

import os
from typing import Generator

_engine = None
_SessionLocal = None


def _get_session_factory():
    """Lazy-initialize session factory using pycharter's DB config."""
    global _engine, _SessionLocal
    if _SessionLocal is None:
        from sqlalchemy.orm import sessionmaker

        url = None
        try:
            from pycharter.config import get_database_url

            url = get_database_url()
        except ImportError:
            url = os.getenv("PYCHARTER_DATABASE_URL")

        if url:
            from pycharter.db.models.base import get_engine

            _engine = get_engine(url)
            _SessionLocal = sessionmaker(bind=_engine)
    return _SessionLocal


def get_db_session() -> Generator:
    """
    FastAPI dependency that provides a database session for wiki routes.

    Yields a SQLAlchemy session and ensures it's closed after use.
    """
    SessionLocal = _get_session_factory()
    if SessionLocal is None:
        raise RuntimeError(
            "Database not configured. Set PYCHARTER_DATABASE_URL (env or pycharter.cfg [database])."
        )
    session = SessionLocal()
    try:
        yield session
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()
