import logging
from pathlib import Path

from rich.logging import RichHandler
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker

from app.models import Base
from utils.settings import get_settings

logging.basicConfig(
    level="INFO", format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]
)
logger = logging.getLogger(__name__)


def init_db(override: bool = False):
    DB_PATH = get_settings().get("db_path", "")
    db_file = Path(DB_PATH.replace("sqlite:", "", 1))
    logger.debug(f"Database path is: {db_file}")
    if db_file.exists():
        if override:
            db_file.unlink()
            logger.info("Existing database deleted (override=True).")
        else:
            logger.info(
                "Database already exists. Use --override to delete and recreate."
            )
            return

    if not db_file.parent.exists():
        db_file.parent.mkdir(parents=True, exist_ok=True)

    engine = create_engine(DB_PATH, echo=False)
    Base.metadata.create_all(engine)
    logger.info("Database initialized.")


def get_session() -> "Session":
    db_path = get_settings().get("db_path", "")
    engine = create_engine(db_path, echo=False)
    Session = sessionmaker(bind=engine)
    return Session()
