import json
import logging

from psycopg2.errorcodes import DUPLICATE_COLUMN
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.lib.jsonalchemy import MutationObj, JsonType
from rhodecode.model import meta, init_model_encryption
from rhodecode.model.db import User


def upgrade(migrate_engine):
    """
    Upgrade operations go here.
    Don't create your own engine; bind migrate_engine to your metadata
    """
    _reset_base(migrate_engine)

    from rhodecode.lib.dbmigrate.schema import db_4_20_0_1 as db

    init_model_encryption(db)

    UserModel: User = db.User

    if not User.get_by_username(UserModel.GHOST_USER):
        ghost_user = UserModel()
        ghost_user.name = UserModel.GHOST_USER.capitalize()
        ghost_user.username = UserModel.GHOST_USER
        ghost_user.lastname = "User"
        ghost_user.strict_creation_check = False
        ghost_user.email = UserModel.GHOST_USER_EMAIL
        ghost_user.active = False
        ghost_user.description = "System user to own assets of deleted users (does not consume license slot)"
        ghost_user.is_new_user = False

        session = meta.Session()
        session.add(ghost_user)
        session.commit()


def downgrade(migrate_engine):
    pass
