"""Database configuration and session management using SQLModel"""
import os
from typing import Generator
from sqlalchemy import create_engine
from sqlmodel import SQLModel, Session, create_engine
from app.config import get_settings

settings = get_settings()

# Database URL can be overridden by environment variable DATABASE_URL
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./ohm_streaming.db")

# Create the engine
# connect_args={"check_same_thread": False} is required for SQLite and FastAPI
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})


def create_db_and_tables():
    """Create the database and tables based on the models"""
    # Import all models here to ensure they are registered with SQLModel.metadata
    from app.models.auth import UserTable
    from app.models.watchlist import WatchlistItemTable
    # Add other models as they are migrated
    
    SQLModel.metadata.create_all(engine)


def get_session() -> Generator[Session, None, None]:
    """Dependency for getting a database session"""
    with Session(engine) as session:
        yield session
