#!/usr/bin/env python3
"""Initialize the dev environment's DB."""
import alembic.command
import alembic.config
from pyramid.paster import bootstrap
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError

from via.db import Base, create_engine


def is_stamped(engine) -> bool:
    """Return True if the DB is stamped with an Alembic revision ID."""
    with engine.connect() as connection:
        try:
            if connection.execute(text("select * from alembic_version")).first():
                return True
        except ProgrammingError:
            pass

    return False


def main():
    with bootstrap("conf/development.ini") as env:
        settings = env["registry"].settings
        engine = create_engine(settings)

        if not is_stamped(engine):
            Base.metadata.create_all(engine)
            alembic.command.stamp(alembic.config.Config("conf/alembic.ini"), "head")


if __name__ == "__main__":
    main()
