"""Alembic env: use duty_teller config DATABASE_URL and db.models.Base."""

import logging
import os
import sys

from sqlalchemy import create_engine
from alembic import context

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import duty_teller.config as config
from duty_teller.db.models import Base

# Logging when config is in pyproject.toml (no fileConfig)
logging.basicConfig(
    format="%(levelname)-5.5s [%(name)s] %(message)s",
    datefmt="%H:%M:%S",
    level=logging.INFO,
)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARN)

config_alembic = context.config

database_url = config.DATABASE_URL
config_alembic.set_main_option("sqlalchemy.url", database_url)

target_metadata = Base.metadata

connect_args = {"check_same_thread": False} if "sqlite" in database_url else {}


def run_migrations_offline() -> None:
    context.configure(
        url=database_url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    engine = create_engine(database_url, connect_args=connect_args)
    with engine.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)
        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
