"""
Linux BenchTools - Database Sessions
"""

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from app.core.config import settings


# ========================================
# DATABASE PRINCIPALE (Benchmarks)
# ========================================

# Create main engine
engine_main = create_engine(
    settings.DATABASE_URL,
    connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {},
    echo=False,  # Set to True for SQL query logging during development
)

# Create SessionLocal class for main DB
SessionLocalMain = sessionmaker(autocommit=False, autoflush=False, bind=engine_main)

# Backward compatibility
engine = engine_main
SessionLocal = SessionLocalMain


# ========================================
# DATABASE PÉRIPHÉRIQUES
# ========================================

# Create peripherals engine
engine_peripherals = create_engine(
    settings.PERIPHERALS_DB_URL,
    connect_args={"check_same_thread": False} if "sqlite" in settings.PERIPHERALS_DB_URL else {},
    echo=False,
)

# Create SessionLocal class for peripherals DB
SessionLocalPeripherals = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine_peripherals
)


# ========================================
# DEPENDENCY INJECTION
# ========================================

def get_db() -> Session:
    """
    Main database session dependency for FastAPI (benchmarks, devices)
    """
    db = SessionLocalMain()
    try:
        yield db
    finally:
        db.close()


def get_peripherals_db() -> Session:
    """
    Peripherals database session dependency for FastAPI
    """
    db = SessionLocalPeripherals()
    try:
        yield db
    finally:
        db.close()
