"""Database configuration and session management using SQLModel."""

from pathlib import Path
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel

from backend.config import settings


# Create async engine
# Note: echo=False to disable SQL query logging (too verbose)
engine = create_async_engine(
    settings.data_entry_database_url,
    echo=False,
    future=True,
)

# Create async session factory
async_session_maker = sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


async def init_db() -> None:
    """Initialize database - create tables if they don't exist."""
    # Ensure data directory exists
    db_path = Path(settings.data_entry_sqlite_database_path)
    db_path.parent.mkdir(parents=True, exist_ok=True)

    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)


async def get_session() -> AsyncGenerator[AsyncSession, None]:
    """Get async database session for dependency injection."""
    async with async_session_maker() as session:
        try:
            yield session
        finally:
            await session.close()


# Convenience function for manual session usage
async def get_db_session() -> AsyncSession:
    """Get a new database session (manual management)."""
    return async_session_maker()
