import logging
from sqlalchemy import *
from sqlalchemy.engine import reflection

from alembic.migration import MigrationContext
from alembic.operations import Operations

from rhodecode.lib.dbmigrate.versions import _reset_base
from rhodecode.model import meta, init_model_encryption


log = logging.getLogger(__name__)


def _get_indexes_list(migrate_engine, table_name):
    inspector = reflection.Inspector.from_engine(migrate_engine)
    return inspector.get_indexes(table_name)


def upgrade(migrate_engine):
    """
    Upgrade operations go here.
    Don't create your own engine; bind migrate_engine to your metadata
    """
    from rhodecode.model import db as db_5_1_0_0

    # issue fixups
    fixups(db_5_1_0_0, meta.Session)


def downgrade(migrate_engine):
    pass


def fixups(models, _SESSION):
    for db_repo in _SESSION.query(models.Repository).all():
        try:
            config = db_repo._config
            config.set("extensions", "largefiles", "")

            scm = db_repo.scm_instance(cache=False, config=config, vcs_full_cache=False)
            if scm:
                print(f"installing hook for repo: {db_repo}")
                scm.install_hooks(force=True)
            del scm  # force GC
            del config
        except Exception as e:
            print(e)
            print("continue...")
