"""Database setup and session management."""

from __future__ import annotations

from collections.abc import Generator

from sqlalchemy import create_engine, event, text
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, sessionmaker

from app.core.config import settings
from app.models.base import Base
from app.services.vault import ensure_vault_fts

engine = create_engine(
    settings.database_url,
    connect_args={"check_same_thread": False},
)

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


def _ensure_engagement_columns(engine: Engine) -> None:
    """Apply lightweight SQLite schema upgrades for engagement optional fields."""
    with engine.begin() as conn:
        rows = conn.execute(text("PRAGMA table_info(engagements)")).mappings().all()
        if not rows:
            return

        existing = {str(row.get("name")) for row in rows}
        if "description" not in existing:
            conn.execute(text("ALTER TABLE engagements ADD COLUMN description TEXT"))
        if "metadata_json" not in existing:
            conn.execute(text("ALTER TABLE engagements ADD COLUMN metadata_json JSON"))


@event.listens_for(Engine, "connect")
def _set_sqlite_pragma(dbapi_connection, _connection_record) -> None:
    """Enable SQLite foreign keys for every connection."""
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()


def get_db() -> Generator[Session, None, None]:
    """Yield a DB session for request scope."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_db() -> None:
    """Create DB folders and tables if they do not exist."""
    settings.db_path.parent.mkdir(parents=True, exist_ok=True)

    # Register model metadata before creating tables.
    from app.models import coverage, engagement, event, vault  # noqa: F401

    Base.metadata.create_all(bind=engine)
    _ensure_engagement_columns(engine)
    ensure_vault_fts(engine)
