from __future__ import annotations

from contextlib import contextmanager
from pathlib import Path

from sqlmodel import Session, SQLModel, create_engine


def get_engine(db_path: str | Path):
    """Create SQLite engine."""
    db_path = Path(db_path)
    db_path.parent.mkdir(parents=True, exist_ok=True)
    url = f"sqlite:///{db_path}"
    return create_engine(url, echo=False)


@contextmanager
def get_session(engine):
    """Context manager for database sessions."""
    with Session(engine) as session:
        yield session


def init_database(engine):
    """Create all tables."""
    SQLModel.metadata.create_all(engine)
