import os

from sqlalchemy.engine import URL

from app.core.settings import get_settings


def sqlite_url(path: str) -> str:
    parent = os.path.dirname(path)
    if parent:
        os.makedirs(parent, exist_ok=True)
    return f"sqlite+pysqlite:///{path}"


def postgres_url(user: str, password: str, host: str, port: int, db: str) -> str:
    return URL.create(
        drivername="postgresql+psycopg",
        username=user,
        password=password,
        host=host,
        port=port,
        database=db,
    ).render_as_string(hide_password=False)


def get_common_db_url() -> str:
    s = get_settings()
    if s.DB_BACKEND.lower() == "sqlite":
        return sqlite_url(s.SQLITE_COMMON_PATH)
    return postgres_url(s.PG_USER, s.PG_PASSWORD, s.PG_HOST, s.PG_PORT, s.PG_DB_COMMON)
